title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Exploratory Data Analysis of Well Log Data - Andy McDonald | Towards Data Science
Machine learning and Artificial Intelligence are becoming popular within the geoscience and petrophysics domains. Especially over the past decade. Machine learning is a subdivision of Artificial Intelligence and is the process by which computers can learn and make predictions from data without being explicitly programmed to do so. We can use machine learning in a number of ways within petrophysics, including automating outlier detection, property prediction, facies classification, etc. This series of articles will look at taking a dataset from basic well log measurements through to petrophysical property prediction. These articles were originally presented at the SPWLA 2021 Conference during a Machine Learning and AI Workshop. They have since been expanded and updated to form these articles. The series will consist of the following, and links will be included once they have been released. 1. Initial Data Exploration of selected wells from the Volve field dataset2. Identification of missing data3. Detection of outliers / anomalous data points using manual and automated methods4. Prediction of key reservoir properties using Machine Learning In 2018, Equinor released the entire contents of the Volve Field to the public domain to foster research and learning. The released data includes: Well Logs Petrophysical Interpretations Reports (geological, completion, petrophysical, core etc) Core Measurements Seismic Data Geological Models and more... The Volve Field is located some 200 km west of Stavanger in the Norwegian Sector of the North Sea. Hydrocarbons were discovered within the Jurassic aged Hugin Formation in 1993. Oil production began in 2008 and lasted for 8 years (twice as long as planned) until 2016, when production ceased. In total 63 MMBO were produced over the field’s lifetime and reached a plateau of 56,000 B/D. Further details about the Volve Field and the entire dataset can be found at: https://www.equinor.com/en/what-we-do/norwegian-continental-shelf-platforms/volve.html The data is licensed under the Equinor Open Data Licence. The Volve dataset consists of 24 wells containing a variety of well log data and other associated measurements. For this small tutorial series, we are going to take a selection of five wells. These are: 15/9-F-1 A 15/9-F-1 B 15/9-F-1 C 15/9-F-11 A 15/9-F-11 B From these wells, a standard set of well logging measurements (features)have been selected. Their names, units, and descriptions are detailed in the table below. The goal over the series of notebooks will be to predict three commonly derived petrophysical measurements: Porosity (PHIF), Water Saturation (SW), and Shale Volume (VSH). Traditionally, these are calculated through a number of empirically derived equations. Exploratory Data Analysis (EDA) is an important step within a data science workflow. It allows you to become familiar with your data and understand its contents, extent, quality, and variation. It is within this stage, you can identify patterns within the data and also relationships between the features (well logs). I have previously covered a number of EDA processes and plots in my previous medium articles: Exploratory Data Analysis with Well Log Data Visualising Well Data Coverage Using Matplotlib How to use Unsupervised Learning to Cluster Well Log Data Using Python As petrophysicists /geoscientists we commonly use well log plots (line plots with data vs depth), histograms, and crossplots (scatter plots) to analyse and explore well log data. Python provides a great toolset for visualising the data from different perspectives in a quick and easy way. In this tutorial, we will cover: Reading in data from a CSV file Viewing data on a log plot Viewing data on a crossplot / scatter plot Viewing data on a histogram Visualising all well log curves on a crossplot and histogram using a pairplot The first step is to import the libraries that we require. These are, pandas for loading and storing the data, matplotlib and seaborn both for visualising the data. import pandas as pdimport matplotlib.pyplot as pltimport matplotlibimport seaborn as sns After importing the libraries, we will load the data using the pandas read_csv function and assign it to the variable df. df = pd.read_csv('data/spwla_volve_data.csv') Once the data has been loaded it will be stored within a structured object, similar to a table, known as a dataframe. We can check the contents of the dataframe in a number of ways. First, we can check the summary statistics of numeric columns using the .describe() function. From this, we are able to find information out about the number of datapoints per feature, the mean, the standard deviation, minimum, maximum and percentile values. For the purposes of making the table easier to read, we will append the .transpose() function. This puts the column names in the rows, and the statistical measurements in the columns. df.describe().transpose() The next method we can call upon is .info(). This provides a list of all of the columns within the dataframe, their data type (e.g, float, integer, string, etc.), and the number of non-null values contained within each column. We can see below, that we have a column called wellName that was not contained in the dataframe shown above. df.info()RangeIndex: 27845 entries, 0 to 27844Data columns (total 16 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 wellName 27845 non-null object 1 MD 27845 non-null float64 2 BS 27845 non-null float64 3 CALI 27845 non-null float64 4 DT 5493 non-null float64 5 DTS 5420 non-null float64 6 GR 27845 non-null float64 7 NPHI 27845 non-null float64 8 RACEHM 27845 non-null float64 9 RACELM 27845 non-null float64 10 RHOB 27845 non-null float64 11 RPCEHM 27845 non-null float64 12 RPCELM 27600 non-null float64 13 PHIF 27736 non-null float64 14 SW 27736 non-null float64 15 VSH 27844 non-null float64dtypes: float64(15), object(1)memory usage: 3.4+ MB The next useful set of methods available to us is the head() and .tail() functions. These return the first / last five rows of the dataframe df.head() df.tail() We know from the introduction that we should have 5 wells within this dataset. We can check that out by calling upon the wellName column and using the method .unique(). This will return back an array listing all of the unique values within that column. df['wellName'].unique()array(['15/9-F-1 A', '15/9-F-1 B', '15/9-F-1 C', '15/9-F-11 A', '15/9-F-11 B'], dtype=object) As seen above, we can call upon specific columns within the dataframe by name. If we do this for a numeric column, such as CALI, we will return a pandas series containing the first 5 values, last 5 values, and details about that column. df['CALI']0 8.67181 8.62502 8.62503 8.62504 8.6250 ... 27840 8.875027841 8.851027842 8.804027843 8.726027844 8.6720Name: CALI, Length: 27845, dtype: float64 Log plots are one of the bread and butter tools that we use to analyse well log data. They consist of several columns called tracks. Each column can have one or more logging curves within them, plotted against depth. They help us visualise the subsurface and allow us to identify potential hydrocarbon intervals. As we are going to be creating multiple log plots, we can create a simple function that can be called upon multiple times. Functions allow us to break down our code into manageable chunks and saves the need for repeating code multiple times. This create_plot function takes a number of arguments (inputs): wellname: the wellname as a string dataframe: the dataframe for the selected well curves_to_plot: a list of logging curves / dataframe columns we are wanting to plot depth_curve: the depth curve we are wanting to plot against log_curves: a list of curves that need to be displayed on a logarithmic scale As there are 5 wells within the dataframe, if we try to plot all of that data in one go, we will have mixed measurements from all of the wells. To resolve this, we can create a new dataframe that is grouped by the wellname. grouped =df.groupby('wellName') When we call upon the head() function of this new grouped dataframe, we will get the first 5 rows for each well. grouped.head() To have more control over the well we are wanting to plot, we can split the grouped dataframe into single dataframes and store them within a list. This will allow us to access specific wells by passing in a list index value. Additionally, it will allow us to use all available pandas dataframe functions on the data, something that is limited and changes when working with a grouped dataframe. # Create empty listsdfs_wells = []wellnames = []#Split up the data by wellfor well, data in grouped: dfs_wells.append(data) wellnames.append(well) If we loop through the wellnames list we can get the index number and the associated wellname. for i, well in enumerate(wellnames): print(f'Index: {i} - {well}')Index: 0 - 15/9-F-1 AIndex: 1 - 15/9-F-1 BIndex: 2 - 15/9-F-1 CIndex: 3 - 15/9-F-11 AIndex: 4 - 15/9-F-11 B Before we plot the data, we need to specify the curves we are wanting to plot, and also specify which of those curves are logarithmically scaled. curves_to_plot = ['BS', 'CALI', 'DT', 'DTS', 'GR', 'NPHI', 'RACEHM', 'RACELM', 'RHOB', 'RPCEHM', 'RPCELM', 'PHIF', 'SW', 'VSH']logarithmic_curves = ['RACEHM', 'RACELM', 'RPCEHM', 'RPCELM'] Let’s call upon the first well and make a plot. Note that Python lists are indexed from 0, therefore the first well in the list will be at position 0. well = 0create_plot(wellnames[well], dfs_wells[well], curves_to_plot, dfs_wells[well]['MD'], logarithmic_curves) When we execute this code, we generate the following plot for 15/9-F-1 A. We have all of our well logging measurements on a single plot, and the resistivity curves are displayed logarithmically, as we would expect them to be. We can do the same with the second well: well = 1create_plot(wellnames[well], dfs_wells[well], curves_to_plot, dfs_wells[well]['MD'], logarithmic_curves) Crossplots (also known as scatter plots) are another common data visualisation tool we use during a petrophysical analysis. More information on working with crossplots (scatter plots) and well log data can be found here: Creating Scatter Plots (Crossplots) of Well Log Data Using Matplotlib in Python Similar to the log plots section above, we will create a simple function where we can generate multiple crossplots using a simple function. This function utilises the FacetGrid function from Seaborn and allows us to map plots directly on top of the grid. This is a much easier way to plot data compared to subplot2grid in matplotlib. The arguments (inputs) to this function are: x — X-axis variable as a string, e.g. ‘NPHI’ y — Y-axis variable as a string, e.g. ‘RHOB’ c — A third variable used for applying colour to the crossplot, e.g. ‘GR’ dataframe — The grouped dataframe created using .groupby('wellName') columns — The number of columns to display on the figure xscale — The X-axis scale yscale — The Y-axis scale vmin — The minimum value for the colour shading vmax — The maximum value for the colour shading Evaluating Neutron Porosity & Bulk Density Data Quality Using Borehole Caliper We can now use our function to create density-neutron crossplots coloured by caliper. Caliper provides an indication of the size of the borehole. During the drilling of the borehole, the walls of the borehole can collapse resulting in the borehole becoming larger. From the plot above, we can see that most of the wells are in good shape and not too significantly washed out, although well 15/9-F11 B contains some borehole enlargement as indicated by the redder colours. Acoustic Compressional vs Shear Crossplot with Gamma Ray Colouring The next crossplot we will look at is acoustic compressional (DTC) versus acoustic shear (DTS). When we view this data, we can see that two of the charts are blank. This lets us know right away we may have missing data within our dataset. We will explore this in the next article in the series. Histograms are a commonly used tool within exploratory data analysis and data science. They are an excellent data visualisation tool and appear similar to bar charts. However, histograms allow us to gain insights about the distribution of the values within a set of data and allow us to display a large range of data in a concise plot. Within the petrophysics and geoscience domains, we can use histograms to identify outliers and also pick key interpretation parameters. For example, clay volume or shale volume endpoints from a gamma ray. Histograms allow us to view the distribution, shape, and range of numerical data. The data is split up into a number of bins, which are represented by individual bars on the plot. You can find out more about working with histograms and well log data in this article: Creating Histograms of Well Log Data Using Matplotlib in Python We can call upon a simple histogram from our main dataframe, simply by appending .hist(column-name) onto the end of the dataframe object. df.hist('GR') Right away we can see we have a few issues. The first is that all wells are grouped together, the number of bins is too few, and the plot does not look great. Se we can change it up a bit, by first increasing the number of bins and removing the grid lines. df.hist('GR', bins=40)plt.grid(False) The above generates an instant improvement to the plot. We can see the distribution of the data much more clearly now, however, all of the data is still combined. We can also call upon the Seaborn plotting library, which gives us much more control over the aesthetics of the plot. In the first example, we can add on a Kernel Density Estimate (KDE). From the plot above, we can see that the labels are automatically generated for us, and we have the KDE line plotted as well. To split the data into the different wells, we can supply another argument: hue which will allow us to use a third variable to split out the data. If we pass in the wellName for the hue, we can generate separate histograms for each well. We can do the same with Bulk Density (RHOB). We can also add in the number of bins that we are wanting to display. If we want to split the data up into individual histograms per well, we need to use a FacetGrid and map the required histogram plot to it. For the FacetGrid we specify the dataframe and the columns we which to split the data into. hue , as mentioned in the crossplot section, controls the colour of the data in each column, and col_wrap specifies the maximum number of columns before the plot wraps to a new row If we want to view the distribution of the data as a line, we can use the Kernel Density Estimation plot (kdeplot). This is useful if we looking to see if the data requires normalisation. Rather than looking at a limited number of variables each time, we can quickly create a grid containing a mixture of crossplots and histograms using a simple line of code from the seaborn library. This is known as a pair plot. We pass in the dataframe, along with the variables that we want to analyse. Along the diagonal of the pair plot, we can have a histogram, but in this example, we will use the KDE plot. Additionally, we can specify colors, shapes, etc using the plot_kws argument. We can now easily see the relationship between each of the well logging measurements rather than creating individual plots. This can be further enhanced by splitting out the data into each well through the use of the hue argument. In this tutorial, we have used a number of tools to explore the dataset and gain some initial insights into it. This has been achieved through well log plots, crossplots (scatter plots), histograms, and pairplots. These tools allow us to get an initial feel for the data and its contents. The next step is to identify if there is any missing data present within the dataset. This article will be published soon. This notebook was originally published for the SPWLA Machine Learning Workshop at the 2021 SPWLA Conference. Thanks for reading! If you have found this article useful, please feel free to check out my other articles looking at various aspects of Python and well log data. You can also find my code used in this article and others at GitHub. If you want to get in touch you can find me on LinkedIn or at my website. Interested in learning more about python and well log data or petrophysics? Follow me on Medium. If you enjoy reading these tutorials and want to support me as a writer and creator, then please consider signing up to become a Medium member. It’s $5 a month and you get unlimited access to many thousands of articles on a wide range of topics. If you sign up using my link, I will earn a small commission with no extra cost to you!
[ { "code": null, "e": 663, "s": 172, "text": "Machine learning and Artificial Intelligence are becoming popular within the geoscience and petrophysics domains. Especially over the past decade. Machine learning is a subdivision of Artificial Intelligence and is the process by which computers can learn and make predictions from data without being explicitly programmed to do so. We can use machine learning in a number of ways within petrophysics, including automating outlier detection, property prediction, facies classification, etc." }, { "code": null, "e": 1074, "s": 663, "text": "This series of articles will look at taking a dataset from basic well log measurements through to petrophysical property prediction. These articles were originally presented at the SPWLA 2021 Conference during a Machine Learning and AI Workshop. They have since been expanded and updated to form these articles. The series will consist of the following, and links will be included once they have been released." }, { "code": null, "e": 1329, "s": 1074, "text": "1. Initial Data Exploration of selected wells from the Volve field dataset2. Identification of missing data3. Detection of outliers / anomalous data points using manual and automated methods4. Prediction of key reservoir properties using Machine Learning" }, { "code": null, "e": 1476, "s": 1329, "text": "In 2018, Equinor released the entire contents of the Volve Field to the public domain to foster research and learning. The released data includes:" }, { "code": null, "e": 1486, "s": 1476, "text": "Well Logs" }, { "code": null, "e": 1516, "s": 1486, "text": "Petrophysical Interpretations" }, { "code": null, "e": 1574, "s": 1516, "text": "Reports (geological, completion, petrophysical, core etc)" }, { "code": null, "e": 1592, "s": 1574, "text": "Core Measurements" }, { "code": null, "e": 1605, "s": 1592, "text": "Seismic Data" }, { "code": null, "e": 1623, "s": 1605, "text": "Geological Models" }, { "code": null, "e": 1635, "s": 1623, "text": "and more..." }, { "code": null, "e": 2022, "s": 1635, "text": "The Volve Field is located some 200 km west of Stavanger in the Norwegian Sector of the North Sea. Hydrocarbons were discovered within the Jurassic aged Hugin Formation in 1993. Oil production began in 2008 and lasted for 8 years (twice as long as planned) until 2016, when production ceased. In total 63 MMBO were produced over the field’s lifetime and reached a plateau of 56,000 B/D." }, { "code": null, "e": 2187, "s": 2022, "text": "Further details about the Volve Field and the entire dataset can be found at: https://www.equinor.com/en/what-we-do/norwegian-continental-shelf-platforms/volve.html" }, { "code": null, "e": 2245, "s": 2187, "text": "The data is licensed under the Equinor Open Data Licence." }, { "code": null, "e": 2448, "s": 2245, "text": "The Volve dataset consists of 24 wells containing a variety of well log data and other associated measurements. For this small tutorial series, we are going to take a selection of five wells. These are:" }, { "code": null, "e": 2459, "s": 2448, "text": "15/9-F-1 A" }, { "code": null, "e": 2470, "s": 2459, "text": "15/9-F-1 B" }, { "code": null, "e": 2481, "s": 2470, "text": "15/9-F-1 C" }, { "code": null, "e": 2493, "s": 2481, "text": "15/9-F-11 A" }, { "code": null, "e": 2505, "s": 2493, "text": "15/9-F-11 B" }, { "code": null, "e": 2667, "s": 2505, "text": "From these wells, a standard set of well logging measurements (features)have been selected. Their names, units, and descriptions are detailed in the table below." }, { "code": null, "e": 2926, "s": 2667, "text": "The goal over the series of notebooks will be to predict three commonly derived petrophysical measurements: Porosity (PHIF), Water Saturation (SW), and Shale Volume (VSH). Traditionally, these are calculated through a number of empirically derived equations." }, { "code": null, "e": 3244, "s": 2926, "text": "Exploratory Data Analysis (EDA) is an important step within a data science workflow. It allows you to become familiar with your data and understand its contents, extent, quality, and variation. It is within this stage, you can identify patterns within the data and also relationships between the features (well logs)." }, { "code": null, "e": 3338, "s": 3244, "text": "I have previously covered a number of EDA processes and plots in my previous medium articles:" }, { "code": null, "e": 3383, "s": 3338, "text": "Exploratory Data Analysis with Well Log Data" }, { "code": null, "e": 3431, "s": 3383, "text": "Visualising Well Data Coverage Using Matplotlib" }, { "code": null, "e": 3502, "s": 3431, "text": "How to use Unsupervised Learning to Cluster Well Log Data Using Python" }, { "code": null, "e": 3791, "s": 3502, "text": "As petrophysicists /geoscientists we commonly use well log plots (line plots with data vs depth), histograms, and crossplots (scatter plots) to analyse and explore well log data. Python provides a great toolset for visualising the data from different perspectives in a quick and easy way." }, { "code": null, "e": 3824, "s": 3791, "text": "In this tutorial, we will cover:" }, { "code": null, "e": 3856, "s": 3824, "text": "Reading in data from a CSV file" }, { "code": null, "e": 3883, "s": 3856, "text": "Viewing data on a log plot" }, { "code": null, "e": 3926, "s": 3883, "text": "Viewing data on a crossplot / scatter plot" }, { "code": null, "e": 3954, "s": 3926, "text": "Viewing data on a histogram" }, { "code": null, "e": 4032, "s": 3954, "text": "Visualising all well log curves on a crossplot and histogram using a pairplot" }, { "code": null, "e": 4197, "s": 4032, "text": "The first step is to import the libraries that we require. These are, pandas for loading and storing the data, matplotlib and seaborn both for visualising the data." }, { "code": null, "e": 4286, "s": 4197, "text": "import pandas as pdimport matplotlib.pyplot as pltimport matplotlibimport seaborn as sns" }, { "code": null, "e": 4408, "s": 4286, "text": "After importing the libraries, we will load the data using the pandas read_csv function and assign it to the variable df." }, { "code": null, "e": 4454, "s": 4408, "text": "df = pd.read_csv('data/spwla_volve_data.csv')" }, { "code": null, "e": 4895, "s": 4454, "text": "Once the data has been loaded it will be stored within a structured object, similar to a table, known as a dataframe. We can check the contents of the dataframe in a number of ways. First, we can check the summary statistics of numeric columns using the .describe() function. From this, we are able to find information out about the number of datapoints per feature, the mean, the standard deviation, minimum, maximum and percentile values." }, { "code": null, "e": 5079, "s": 4895, "text": "For the purposes of making the table easier to read, we will append the .transpose() function. This puts the column names in the rows, and the statistical measurements in the columns." }, { "code": null, "e": 5105, "s": 5079, "text": "df.describe().transpose()" }, { "code": null, "e": 5441, "s": 5105, "text": "The next method we can call upon is .info(). This provides a list of all of the columns within the dataframe, their data type (e.g, float, integer, string, etc.), and the number of non-null values contained within each column. We can see below, that we have a column called wellName that was not contained in the dataframe shown above." }, { "code": null, "e": 6255, "s": 5441, "text": "df.info()RangeIndex: 27845 entries, 0 to 27844Data columns (total 16 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 wellName 27845 non-null object 1 MD 27845 non-null float64 2 BS 27845 non-null float64 3 CALI 27845 non-null float64 4 DT 5493 non-null float64 5 DTS 5420 non-null float64 6 GR 27845 non-null float64 7 NPHI 27845 non-null float64 8 RACEHM 27845 non-null float64 9 RACELM 27845 non-null float64 10 RHOB 27845 non-null float64 11 RPCEHM 27845 non-null float64 12 RPCELM 27600 non-null float64 13 PHIF 27736 non-null float64 14 SW 27736 non-null float64 15 VSH 27844 non-null float64dtypes: float64(15), object(1)memory usage: 3.4+ MB" }, { "code": null, "e": 6396, "s": 6255, "text": "The next useful set of methods available to us is the head() and .tail() functions. These return the first / last five rows of the dataframe" }, { "code": null, "e": 6406, "s": 6396, "text": "df.head()" }, { "code": null, "e": 6416, "s": 6406, "text": "df.tail()" }, { "code": null, "e": 6669, "s": 6416, "text": "We know from the introduction that we should have 5 wells within this dataset. We can check that out by calling upon the wellName column and using the method .unique(). This will return back an array listing all of the unique values within that column." }, { "code": null, "e": 6792, "s": 6669, "text": "df['wellName'].unique()array(['15/9-F-1 A', '15/9-F-1 B', '15/9-F-1 C', '15/9-F-11 A', '15/9-F-11 B'], dtype=object)" }, { "code": null, "e": 7029, "s": 6792, "text": "As seen above, we can call upon specific columns within the dataframe by name. If we do this for a numeric column, such as CALI, we will return a pandas series containing the first 5 values, last 5 values, and details about that column." }, { "code": null, "e": 7246, "s": 7029, "text": "df['CALI']0 8.67181 8.62502 8.62503 8.62504 8.6250 ... 27840 8.875027841 8.851027842 8.804027843 8.726027844 8.6720Name: CALI, Length: 27845, dtype: float64" }, { "code": null, "e": 7559, "s": 7246, "text": "Log plots are one of the bread and butter tools that we use to analyse well log data. They consist of several columns called tracks. Each column can have one or more logging curves within them, plotted against depth. They help us visualise the subsurface and allow us to identify potential hydrocarbon intervals." }, { "code": null, "e": 7801, "s": 7559, "text": "As we are going to be creating multiple log plots, we can create a simple function that can be called upon multiple times. Functions allow us to break down our code into manageable chunks and saves the need for repeating code multiple times." }, { "code": null, "e": 7865, "s": 7801, "text": "This create_plot function takes a number of arguments (inputs):" }, { "code": null, "e": 7900, "s": 7865, "text": "wellname: the wellname as a string" }, { "code": null, "e": 7947, "s": 7900, "text": "dataframe: the dataframe for the selected well" }, { "code": null, "e": 8031, "s": 7947, "text": "curves_to_plot: a list of logging curves / dataframe columns we are wanting to plot" }, { "code": null, "e": 8091, "s": 8031, "text": "depth_curve: the depth curve we are wanting to plot against" }, { "code": null, "e": 8169, "s": 8091, "text": "log_curves: a list of curves that need to be displayed on a logarithmic scale" }, { "code": null, "e": 8393, "s": 8169, "text": "As there are 5 wells within the dataframe, if we try to plot all of that data in one go, we will have mixed measurements from all of the wells. To resolve this, we can create a new dataframe that is grouped by the wellname." }, { "code": null, "e": 8425, "s": 8393, "text": "grouped =df.groupby('wellName')" }, { "code": null, "e": 8538, "s": 8425, "text": "When we call upon the head() function of this new grouped dataframe, we will get the first 5 rows for each well." }, { "code": null, "e": 8553, "s": 8538, "text": "grouped.head()" }, { "code": null, "e": 8778, "s": 8553, "text": "To have more control over the well we are wanting to plot, we can split the grouped dataframe into single dataframes and store them within a list. This will allow us to access specific wells by passing in a list index value." }, { "code": null, "e": 8947, "s": 8778, "text": "Additionally, it will allow us to use all available pandas dataframe functions on the data, something that is limited and changes when working with a grouped dataframe." }, { "code": null, "e": 9100, "s": 8947, "text": "# Create empty listsdfs_wells = []wellnames = []#Split up the data by wellfor well, data in grouped: dfs_wells.append(data) wellnames.append(well)" }, { "code": null, "e": 9195, "s": 9100, "text": "If we loop through the wellnames list we can get the index number and the associated wellname." }, { "code": null, "e": 9372, "s": 9195, "text": "for i, well in enumerate(wellnames): print(f'Index: {i} - {well}')Index: 0 - 15/9-F-1 AIndex: 1 - 15/9-F-1 BIndex: 2 - 15/9-F-1 CIndex: 3 - 15/9-F-11 AIndex: 4 - 15/9-F-11 B" }, { "code": null, "e": 9518, "s": 9372, "text": "Before we plot the data, we need to specify the curves we are wanting to plot, and also specify which of those curves are logarithmically scaled." }, { "code": null, "e": 9743, "s": 9518, "text": "curves_to_plot = ['BS', 'CALI', 'DT', 'DTS', 'GR', 'NPHI', 'RACEHM', 'RACELM', 'RHOB', 'RPCEHM', 'RPCELM', 'PHIF', 'SW', 'VSH']logarithmic_curves = ['RACEHM', 'RACELM', 'RPCEHM', 'RPCELM']" }, { "code": null, "e": 9791, "s": 9743, "text": "Let’s call upon the first well and make a plot." }, { "code": null, "e": 9894, "s": 9791, "text": "Note that Python lists are indexed from 0, therefore the first well in the list will be at position 0." }, { "code": null, "e": 10030, "s": 9894, "text": "well = 0create_plot(wellnames[well], dfs_wells[well], curves_to_plot, dfs_wells[well]['MD'], logarithmic_curves)" }, { "code": null, "e": 10256, "s": 10030, "text": "When we execute this code, we generate the following plot for 15/9-F-1 A. We have all of our well logging measurements on a single plot, and the resistivity curves are displayed logarithmically, as we would expect them to be." }, { "code": null, "e": 10297, "s": 10256, "text": "We can do the same with the second well:" }, { "code": null, "e": 10434, "s": 10297, "text": "well = 1create_plot(wellnames[well], dfs_wells[well], curves_to_plot, dfs_wells[well]['MD'], logarithmic_curves)" }, { "code": null, "e": 10655, "s": 10434, "text": "Crossplots (also known as scatter plots) are another common data visualisation tool we use during a petrophysical analysis. More information on working with crossplots (scatter plots) and well log data can be found here:" }, { "code": null, "e": 10735, "s": 10655, "text": "Creating Scatter Plots (Crossplots) of Well Log Data Using Matplotlib in Python" }, { "code": null, "e": 11069, "s": 10735, "text": "Similar to the log plots section above, we will create a simple function where we can generate multiple crossplots using a simple function. This function utilises the FacetGrid function from Seaborn and allows us to map plots directly on top of the grid. This is a much easier way to plot data compared to subplot2grid in matplotlib." }, { "code": null, "e": 11114, "s": 11069, "text": "The arguments (inputs) to this function are:" }, { "code": null, "e": 11159, "s": 11114, "text": "x — X-axis variable as a string, e.g. ‘NPHI’" }, { "code": null, "e": 11204, "s": 11159, "text": "y — Y-axis variable as a string, e.g. ‘RHOB’" }, { "code": null, "e": 11278, "s": 11204, "text": "c — A third variable used for applying colour to the crossplot, e.g. ‘GR’" }, { "code": null, "e": 11347, "s": 11278, "text": "dataframe — The grouped dataframe created using .groupby('wellName')" }, { "code": null, "e": 11404, "s": 11347, "text": "columns — The number of columns to display on the figure" }, { "code": null, "e": 11430, "s": 11404, "text": "xscale — The X-axis scale" }, { "code": null, "e": 11456, "s": 11430, "text": "yscale — The Y-axis scale" }, { "code": null, "e": 11504, "s": 11456, "text": "vmin — The minimum value for the colour shading" }, { "code": null, "e": 11552, "s": 11504, "text": "vmax — The maximum value for the colour shading" }, { "code": null, "e": 11631, "s": 11552, "text": "Evaluating Neutron Porosity & Bulk Density Data Quality Using Borehole Caliper" }, { "code": null, "e": 11896, "s": 11631, "text": "We can now use our function to create density-neutron crossplots coloured by caliper. Caliper provides an indication of the size of the borehole. During the drilling of the borehole, the walls of the borehole can collapse resulting in the borehole becoming larger." }, { "code": null, "e": 12103, "s": 11896, "text": "From the plot above, we can see that most of the wells are in good shape and not too significantly washed out, although well 15/9-F11 B contains some borehole enlargement as indicated by the redder colours." }, { "code": null, "e": 12170, "s": 12103, "text": "Acoustic Compressional vs Shear Crossplot with Gamma Ray Colouring" }, { "code": null, "e": 12266, "s": 12170, "text": "The next crossplot we will look at is acoustic compressional (DTC) versus acoustic shear (DTS)." }, { "code": null, "e": 12465, "s": 12266, "text": "When we view this data, we can see that two of the charts are blank. This lets us know right away we may have missing data within our dataset. We will explore this in the next article in the series." }, { "code": null, "e": 13006, "s": 12465, "text": "Histograms are a commonly used tool within exploratory data analysis and data science. They are an excellent data visualisation tool and appear similar to bar charts. However, histograms allow us to gain insights about the distribution of the values within a set of data and allow us to display a large range of data in a concise plot. Within the petrophysics and geoscience domains, we can use histograms to identify outliers and also pick key interpretation parameters. For example, clay volume or shale volume endpoints from a gamma ray." }, { "code": null, "e": 13186, "s": 13006, "text": "Histograms allow us to view the distribution, shape, and range of numerical data. The data is split up into a number of bins, which are represented by individual bars on the plot." }, { "code": null, "e": 13273, "s": 13186, "text": "You can find out more about working with histograms and well log data in this article:" }, { "code": null, "e": 13337, "s": 13273, "text": "Creating Histograms of Well Log Data Using Matplotlib in Python" }, { "code": null, "e": 13475, "s": 13337, "text": "We can call upon a simple histogram from our main dataframe, simply by appending .hist(column-name) onto the end of the dataframe object." }, { "code": null, "e": 13489, "s": 13475, "text": "df.hist('GR')" }, { "code": null, "e": 13746, "s": 13489, "text": "Right away we can see we have a few issues. The first is that all wells are grouped together, the number of bins is too few, and the plot does not look great. Se we can change it up a bit, by first increasing the number of bins and removing the grid lines." }, { "code": null, "e": 13784, "s": 13746, "text": "df.hist('GR', bins=40)plt.grid(False)" }, { "code": null, "e": 13947, "s": 13784, "text": "The above generates an instant improvement to the plot. We can see the distribution of the data much more clearly now, however, all of the data is still combined." }, { "code": null, "e": 14134, "s": 13947, "text": "We can also call upon the Seaborn plotting library, which gives us much more control over the aesthetics of the plot. In the first example, we can add on a Kernel Density Estimate (KDE)." }, { "code": null, "e": 14260, "s": 14134, "text": "From the plot above, we can see that the labels are automatically generated for us, and we have the KDE line plotted as well." }, { "code": null, "e": 14407, "s": 14260, "text": "To split the data into the different wells, we can supply another argument: hue which will allow us to use a third variable to split out the data." }, { "code": null, "e": 14498, "s": 14407, "text": "If we pass in the wellName for the hue, we can generate separate histograms for each well." }, { "code": null, "e": 14613, "s": 14498, "text": "We can do the same with Bulk Density (RHOB). We can also add in the number of bins that we are wanting to display." }, { "code": null, "e": 14752, "s": 14613, "text": "If we want to split the data up into individual histograms per well, we need to use a FacetGrid and map the required histogram plot to it." }, { "code": null, "e": 15025, "s": 14752, "text": "For the FacetGrid we specify the dataframe and the columns we which to split the data into. hue , as mentioned in the crossplot section, controls the colour of the data in each column, and col_wrap specifies the maximum number of columns before the plot wraps to a new row" }, { "code": null, "e": 15213, "s": 15025, "text": "If we want to view the distribution of the data as a line, we can use the Kernel Density Estimation plot (kdeplot). This is useful if we looking to see if the data requires normalisation." }, { "code": null, "e": 15440, "s": 15213, "text": "Rather than looking at a limited number of variables each time, we can quickly create a grid containing a mixture of crossplots and histograms using a simple line of code from the seaborn library. This is known as a pair plot." }, { "code": null, "e": 15703, "s": 15440, "text": "We pass in the dataframe, along with the variables that we want to analyse. Along the diagonal of the pair plot, we can have a histogram, but in this example, we will use the KDE plot. Additionally, we can specify colors, shapes, etc using the plot_kws argument." }, { "code": null, "e": 15934, "s": 15703, "text": "We can now easily see the relationship between each of the well logging measurements rather than creating individual plots. This can be further enhanced by splitting out the data into each well through the use of the hue argument." }, { "code": null, "e": 16223, "s": 15934, "text": "In this tutorial, we have used a number of tools to explore the dataset and gain some initial insights into it. This has been achieved through well log plots, crossplots (scatter plots), histograms, and pairplots. These tools allow us to get an initial feel for the data and its contents." }, { "code": null, "e": 16346, "s": 16223, "text": "The next step is to identify if there is any missing data present within the dataset. This article will be published soon." }, { "code": null, "e": 16455, "s": 16346, "text": "This notebook was originally published for the SPWLA Machine Learning Workshop at the 2021 SPWLA Conference." }, { "code": null, "e": 16475, "s": 16455, "text": "Thanks for reading!" }, { "code": null, "e": 16687, "s": 16475, "text": "If you have found this article useful, please feel free to check out my other articles looking at various aspects of Python and well log data. You can also find my code used in this article and others at GitHub." }, { "code": null, "e": 16761, "s": 16687, "text": "If you want to get in touch you can find me on LinkedIn or at my website." }, { "code": null, "e": 16858, "s": 16761, "text": "Interested in learning more about python and well log data or petrophysics? Follow me on Medium." } ]
Min-Max Range Queries in Array in C++
Given an array Arr[] containing N elements. The goal is to find the minimum and maximum value from indexes of query. According to the query we are given starting index and ending indexes. In − Arr[] = { 1, 2, 3, 4, 5 } QStart = 1 QEnd = 4 Out − Minimum Value : 2 Maximum Value : 5 Explanation −In the above queries the starting index is 1 and ending index is 4. Between these two indexes, minimum value in Arr is 2 and maximum value is 5 In − Arr[] = { 10, 12, 3, 2, 5, 18 } QStart = 2 QEnd = 5 Out − Minimum Value : 2 Maximum Value : 18 Explanation − In the above queries the starting index is 2 and ending index is 5. Between these two indexes, minimum value in Arr is 2 and maximum value is 18 In this approach we will use segment trees for the range lpos to rpos to find the minimum and maximum values in the given query range. Take the input array Arr[] and query indexes QStart and QEnd. Take the input array Arr[] and query indexes QStart and QEnd. Take the result of type value. Take the result of type value. Structure value is used to store minimum and maximum value found in an array using a given query. Structure value is used to store minimum and maximum value found in an array using a given query. Structure value is used to store minimum and maximum value found in an array using a given query. Structure value is used to store minimum and maximum value found in an array using a given query. Function minMax(struct value *root1, int num, int qStart1, int qEnd1) takes query indexes and finds minimum and maximum in an array between index range qStart1 and qEnd1. Function minMax(struct value *root1, int num, int qStart1, int qEnd1) takes query indexes and finds minimum and maximum in an array between index range qStart1 and qEnd1. Check if ( qStart1 < 0 OR qEnd1 > num-1 OR qStart1 > qEnd1 ). If true then input range in the query is invalid. Check if ( qStart1 < 0 OR qEnd1 > num-1 OR qStart1 > qEnd1 ). If true then input range in the query is invalid. Otherwise, call minmaxFind(root1, 0, num-1, qStart1, qEnd1, 0). Otherwise, call minmaxFind(root1, 0, num-1, qStart1, qEnd1, 0). Function minmaxFind(struct value *root, int startT, int endT, int qStart, int qEnd, int pos) is a recursive function. It takes a pointer to segment tree- root, starting and ending index of current value as startT and endT. Function minmaxFind(struct value *root, int startT, int endT, int qStart, int qEnd, int pos) is a recursive function. It takes a pointer to segment tree- root, starting and ending index of current value as startT and endT. It also takes a starting and ending index in query range. The current index of value in the segment tree has index pos. It also takes a starting and ending index in query range. The current index of value in the segment tree has index pos. If (qStart <= startT) AND if( qEnd >= endT) then the segment of current value is part of the given range. So return minimum and maximum in that value. If (qStart <= startT) AND if( qEnd >= endT) then the segment of current value is part of the given range. So return minimum and maximum in that value. If it is outside the range then update the current value with minVal and maxVal. If it is outside the range then update the current value with minVal and maxVal. If current part overlaps with given range then :- If current part overlaps with given range then :- Take middl = startT + ( endT - startT )/2. Take middl = startT + ( endT - startT )/2. Take p1 and p2 as 2*pos+1 and =2*pos+2. Take p1 and p2 as 2*pos+1 and =2*pos+2. Update lpos as lpos = minmaxFind(root, startT, middl, qStart, qEnd, p1) and rpos as minmaxFind(root, middl+1, endT, qStart, qEnd, p2). Update lpos as lpos = minmaxFind(root, startT, middl, qStart, qEnd, p1) and rpos as minmaxFind(root, middl+1, endT, qStart, qEnd, p2). Set temp.minVal as minimum of lpos.minVal and rpos.minVal. Set temp.minVal as minimum of lpos.minVal and rpos.minVal. Set temp.maxVal as maximum of lpos.maxVal and rpos.maxVal. Set temp.maxVal as maximum of lpos.maxVal and rpos.maxVal. Return temp. Return temp. Function segmentTree(int arr2[], int startT2, int endT2, struct value *root2, int pos2) is used to construct a segment tree for array arr2[] with index range as startT2 and endT2 and current value position is pos2. Function segmentTree(int arr2[], int startT2, int endT2, struct value *root2, int pos2) is used to construct a segment tree for array arr2[] with index range as startT2 and endT2 and current value position is pos2. Function *createTree(int arr0[], int num0) is used to construct a segment tree from a given array arr0. This function allocates memory for segment trees and calls segmentTree() for memory allocation. Function *createTree(int arr0[], int num0) is used to construct a segment tree from a given array arr0. This function allocates memory for segment trees and calls segmentTree() for memory allocation. #include<bits/stdc++.h> using namespace std; struct value{ int minVal; int maxVal; }; struct value minmaxFind(struct value *root, int startT, int endT, int qStart, int qEnd, int pos){ struct value temp, lpos ,rpos; if (qStart <= startT) { if( qEnd >= endT) { return root[pos]; } } if (endT < qStart || startT > qEnd) { temp.minVal = 9999; temp.maxVal = -9999; return temp; } int middl = startT + ( endT - startT )/2; int p1=2*pos+1; int p2=2*pos+2; lpos = minmaxFind(root, startT, middl, qStart, qEnd, p1); rpos = minmaxFind(root, middl+1, endT, qStart, qEnd, p2); temp.minVal = (lpos.minVal<rpos.minVal) ? lpos.minVal : rpos.minVal ; temp.maxVal = (lpos.maxVal>rpos.maxVal) ? lpos.maxVal : rpos.maxVal ; return temp; } struct value minMax(struct value *root1, int num, int qStart1, int qEnd1){ struct value temp1; if (qStart1 < 0 || qEnd1 > num-1 || qStart1 > qEnd1){ cout<<"Please enter Valid input!!"; temp1.minVal = 9999; temp1.maxVal = -9999; return temp1; } return minmaxFind(root1, 0, num-1, qStart1, qEnd1, 0); } void segmentTree(int arr2[], int startT2, int endT2, struct value *root2, int pos2){ if (startT2 == endT2) { root2[pos2].minVal = arr2[startT2]; root2[pos2].maxVal = arr2[startT2]; return ; } int p1=pos2*2+1; int p2=pos2*2+2; int middl2 = startT2+(endT2-startT2)/2; segmentTree(arr2, startT2, middl2, root2, p1); segmentTree(arr2, middl2+1, endT2, root2, p2); root2[pos2].minVal = root2[p1].minVal<root2[p2].minVal ? root2[p1].minVal : root2[p2].minVal; root2[pos2].maxVal = root2[p1].maxVal>root2[p2].maxVal ? root2[p1].maxVal : root2[p2].maxVal; } struct value *createTree(int arr0[], int num0) { int height = (int)(ceil(log2(num0))); int maxS = 2*(int)pow(2, height) - 1; struct value *root0 = new struct value[maxS]; segmentTree(arr0, 0, num0-1, root0, 0); return root0; } int main() { int Arr[] = { 1, 2, 3, 4, 5 }; int length = sizeof(Arr)/sizeof(Arr[0]); struct value *tree = createTree(Arr, length); int QStart = 1; int QEnd = 4; struct value answer=minMax(tree, length, QStart, QEnd); cout<<"Minimum Value : "<<answer.minVal<<endl; cout<<"Maximum Value : "<<answer.maxVal; return 0; } If we run the above code it will generate the following Output Minimum Value : 2 Maximum Value : 5
[ { "code": null, "e": 1179, "s": 1062, "text": "Given an array Arr[] containing N elements. The goal is to find the minimum and maximum value from indexes of query." }, { "code": null, "e": 1250, "s": 1179, "text": "According to the query we are given starting index and ending indexes." }, { "code": null, "e": 1301, "s": 1250, "text": "In − Arr[] = { 1, 2, 3, 4, 5 } QStart = 1 QEnd = 4" }, { "code": null, "e": 1307, "s": 1301, "text": "Out −" }, { "code": null, "e": 1325, "s": 1307, "text": "Minimum Value : 2" }, { "code": null, "e": 1343, "s": 1325, "text": "Maximum Value : 5" }, { "code": null, "e": 1500, "s": 1343, "text": "Explanation −In the above queries the starting index is 1 and ending index is 4. Between these two indexes, minimum value in Arr is 2 and maximum value is 5" }, { "code": null, "e": 1557, "s": 1500, "text": "In − Arr[] = { 10, 12, 3, 2, 5, 18 } QStart = 2 QEnd = 5" }, { "code": null, "e": 1563, "s": 1557, "text": "Out −" }, { "code": null, "e": 1581, "s": 1563, "text": "Minimum Value : 2" }, { "code": null, "e": 1600, "s": 1581, "text": "Maximum Value : 18" }, { "code": null, "e": 1759, "s": 1600, "text": "Explanation − In the above queries the starting index is 2 and ending index is 5. Between these two indexes, minimum value in Arr is 2 and maximum value is 18" }, { "code": null, "e": 1894, "s": 1759, "text": "In this approach we will use segment trees for the range lpos to rpos to find the minimum and maximum values in the given query range." }, { "code": null, "e": 1956, "s": 1894, "text": "Take the input array Arr[] and query indexes QStart and QEnd." }, { "code": null, "e": 2018, "s": 1956, "text": "Take the input array Arr[] and query indexes QStart and QEnd." }, { "code": null, "e": 2049, "s": 2018, "text": "Take the result of type value." }, { "code": null, "e": 2080, "s": 2049, "text": "Take the result of type value." }, { "code": null, "e": 2178, "s": 2080, "text": "Structure value is used to store minimum and maximum value found in an array using a given query." }, { "code": null, "e": 2276, "s": 2178, "text": "Structure value is used to store minimum and maximum value found in an array using a given query." }, { "code": null, "e": 2374, "s": 2276, "text": "Structure value is used to store minimum and maximum value found in an array using a given query." }, { "code": null, "e": 2472, "s": 2374, "text": "Structure value is used to store minimum and maximum value found in an array using a given query." }, { "code": null, "e": 2643, "s": 2472, "text": "Function minMax(struct value *root1, int num, int qStart1, int qEnd1) takes query indexes and finds minimum and maximum in an array between index range qStart1 and qEnd1." }, { "code": null, "e": 2814, "s": 2643, "text": "Function minMax(struct value *root1, int num, int qStart1, int qEnd1) takes query indexes and finds minimum and maximum in an array between index range qStart1 and qEnd1." }, { "code": null, "e": 2926, "s": 2814, "text": "Check if ( qStart1 < 0 OR qEnd1 > num-1 OR qStart1 > qEnd1 ). If true then input range in the query is invalid." }, { "code": null, "e": 3038, "s": 2926, "text": "Check if ( qStart1 < 0 OR qEnd1 > num-1 OR qStart1 > qEnd1 ). If true then input range in the query is invalid." }, { "code": null, "e": 3102, "s": 3038, "text": "Otherwise, call minmaxFind(root1, 0, num-1, qStart1, qEnd1, 0)." }, { "code": null, "e": 3166, "s": 3102, "text": "Otherwise, call minmaxFind(root1, 0, num-1, qStart1, qEnd1, 0)." }, { "code": null, "e": 3389, "s": 3166, "text": "Function minmaxFind(struct value *root, int startT, int endT, int qStart, int qEnd, int pos) is a recursive function. It takes a pointer to segment tree- root, starting and ending index of current value as startT and endT." }, { "code": null, "e": 3612, "s": 3389, "text": "Function minmaxFind(struct value *root, int startT, int endT, int qStart, int qEnd, int pos) is a recursive function. It takes a pointer to segment tree- root, starting and ending index of current value as startT and endT." }, { "code": null, "e": 3732, "s": 3612, "text": "It also takes a starting and ending index in query range. The current index of value in the segment tree has index pos." }, { "code": null, "e": 3852, "s": 3732, "text": "It also takes a starting and ending index in query range. The current index of value in the segment tree has index pos." }, { "code": null, "e": 4003, "s": 3852, "text": "If (qStart <= startT) AND if( qEnd >= endT) then the segment of current value is part of the given range. So return minimum and maximum in that value." }, { "code": null, "e": 4154, "s": 4003, "text": "If (qStart <= startT) AND if( qEnd >= endT) then the segment of current value is part of the given range. So return minimum and maximum in that value." }, { "code": null, "e": 4235, "s": 4154, "text": "If it is outside the range then update the current value with minVal and maxVal." }, { "code": null, "e": 4316, "s": 4235, "text": "If it is outside the range then update the current value with minVal and maxVal." }, { "code": null, "e": 4366, "s": 4316, "text": "If current part overlaps with given range then :-" }, { "code": null, "e": 4416, "s": 4366, "text": "If current part overlaps with given range then :-" }, { "code": null, "e": 4459, "s": 4416, "text": "Take middl = startT + ( endT - startT )/2." }, { "code": null, "e": 4502, "s": 4459, "text": "Take middl = startT + ( endT - startT )/2." }, { "code": null, "e": 4542, "s": 4502, "text": "Take p1 and p2 as 2*pos+1 and =2*pos+2." }, { "code": null, "e": 4582, "s": 4542, "text": "Take p1 and p2 as 2*pos+1 and =2*pos+2." }, { "code": null, "e": 4717, "s": 4582, "text": "Update lpos as lpos = minmaxFind(root, startT, middl, qStart, qEnd, p1) and rpos as minmaxFind(root, middl+1, endT, qStart, qEnd, p2)." }, { "code": null, "e": 4852, "s": 4717, "text": "Update lpos as lpos = minmaxFind(root, startT, middl, qStart, qEnd, p1) and rpos as minmaxFind(root, middl+1, endT, qStart, qEnd, p2)." }, { "code": null, "e": 4911, "s": 4852, "text": "Set temp.minVal as minimum of lpos.minVal and rpos.minVal." }, { "code": null, "e": 4970, "s": 4911, "text": "Set temp.minVal as minimum of lpos.minVal and rpos.minVal." }, { "code": null, "e": 5029, "s": 4970, "text": "Set temp.maxVal as maximum of lpos.maxVal and rpos.maxVal." }, { "code": null, "e": 5088, "s": 5029, "text": "Set temp.maxVal as maximum of lpos.maxVal and rpos.maxVal." }, { "code": null, "e": 5101, "s": 5088, "text": "Return temp." }, { "code": null, "e": 5114, "s": 5101, "text": "Return temp." }, { "code": null, "e": 5329, "s": 5114, "text": "Function segmentTree(int arr2[], int startT2, int endT2, struct value *root2, int pos2) is used to construct a segment tree for array arr2[] with index range as startT2 and endT2 and current value position is pos2." }, { "code": null, "e": 5544, "s": 5329, "text": "Function segmentTree(int arr2[], int startT2, int endT2, struct value *root2, int pos2) is used to construct a segment tree for array arr2[] with index range as startT2 and endT2 and current value position is pos2." }, { "code": null, "e": 5744, "s": 5544, "text": "Function *createTree(int arr0[], int num0) is used to construct a segment tree from a given array arr0. This function allocates memory for segment trees and calls segmentTree() for memory allocation." }, { "code": null, "e": 5944, "s": 5744, "text": "Function *createTree(int arr0[], int num0) is used to construct a segment tree from a given array arr0. This function allocates memory for segment trees and calls segmentTree() for memory allocation." }, { "code": null, "e": 8270, "s": 5944, "text": "#include<bits/stdc++.h>\nusing namespace std;\nstruct value{\n int minVal;\n int maxVal;\n};\nstruct value minmaxFind(struct value *root, int startT, int endT, int qStart,\n int qEnd, int pos){\n struct value temp, lpos ,rpos;\n if (qStart <= startT) {\n if( qEnd >= endT)\n { return root[pos]; }\n }\n if (endT < qStart || startT > qEnd) {\n temp.minVal = 9999;\n temp.maxVal = -9999;\n return temp;\n }\n int middl = startT + ( endT - startT )/2;\n int p1=2*pos+1;\n int p2=2*pos+2;\n lpos = minmaxFind(root, startT, middl, qStart, qEnd, p1);\n rpos = minmaxFind(root, middl+1, endT, qStart, qEnd, p2);\n temp.minVal = (lpos.minVal<rpos.minVal) ? lpos.minVal : rpos.minVal ;\n temp.maxVal = (lpos.maxVal>rpos.maxVal) ? lpos.maxVal : rpos.maxVal ;\n return temp;\n}\nstruct value minMax(struct value *root1, int num, int qStart1, int qEnd1){\n struct value temp1;\n if (qStart1 < 0 || qEnd1 > num-1 || qStart1 > qEnd1){\n cout<<\"Please enter Valid input!!\";\n temp1.minVal = 9999;\n temp1.maxVal = -9999;\n return temp1;\n }\n return minmaxFind(root1, 0, num-1, qStart1, qEnd1, 0);\n}\nvoid segmentTree(int arr2[], int startT2, int endT2, struct value *root2, int pos2){ \n if (startT2 == endT2) { \n root2[pos2].minVal = arr2[startT2];\n root2[pos2].maxVal = arr2[startT2];\n return ;\n }\n int p1=pos2*2+1; \n int p2=pos2*2+2;\n int middl2 = startT2+(endT2-startT2)/2;\n segmentTree(arr2, startT2, middl2, root2, p1);\n segmentTree(arr2, middl2+1, endT2, root2, p2);\n root2[pos2].minVal = root2[p1].minVal<root2[p2].minVal ? root2[p1].minVal : root2[p2].minVal;\n root2[pos2].maxVal = root2[p1].maxVal>root2[p2].maxVal ? root2[p1].maxVal : root2[p2].maxVal;\n}\nstruct value *createTree(int arr0[], int num0) { \n int height = (int)(ceil(log2(num0)));\n int maxS = 2*(int)pow(2, height) - 1;\n struct value *root0 = new struct value[maxS];\n segmentTree(arr0, 0, num0-1, root0, 0);\n return root0;\n}\nint main() { \n int Arr[] = { 1, 2, 3, 4, 5 };\n int length = sizeof(Arr)/sizeof(Arr[0]);\n struct value *tree = createTree(Arr, length);\n int QStart = 1;\n int QEnd = 4;\n struct value answer=minMax(tree, length, QStart, QEnd);\n cout<<\"Minimum Value : \"<<answer.minVal<<endl;\n cout<<\"Maximum Value : \"<<answer.maxVal;\n return 0;\n}" }, { "code": null, "e": 8333, "s": 8270, "text": "If we run the above code it will generate the following Output" }, { "code": null, "e": 8369, "s": 8333, "text": "Minimum Value : 2\nMaximum Value : 5" } ]
How to save a Librosa spectrogram plot as a specific sized image?
Librosa is a Python package that helps to analyse audio and music files. This package also helps to create music retrieval information systems. In this article, we will see how to save a Librosa spectrogram plot as an image of specific size. Set the figure size and adjust the padding between and around the subplots.. Set the figure size and adjust the padding between and around the subplots.. Create a figure and a set of subplots. Create a figure and a set of subplots. Initialize three different variables, hl, hi, wi, to store samples per time in the spectrogram, height and width of the images. Initialize three different variables, hl, hi, wi, to store samples per time in the spectrogram, height and width of the images. Load a demo track. Load a demo track. Create a window, i.e., a list for audio time series.. Create a window, i.e., a list for audio time series.. Compute a mel-scaled spectrogram, using melspectrogram() with window and step 3 data. Compute a mel-scaled spectrogram, using melspectrogram() with window and step 3 data. Convert the power spectrogram (amplitude squared) to decibel (dB) units, using power_to_db() method.. Convert the power spectrogram (amplitude squared) to decibel (dB) units, using power_to_db() method.. Display the spectrogram as img (we can save it here). Display the spectrogram as img (we can save it here). Save the img using savefig(). Save the img using savefig(). Display the image using plt.show() method. Display the image using plt.show() method. import numpy as np import matplotlib.pyplot as plt import librosa.display plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True fig, ax = plt.subplots() hl = 512 # number of samples per time-step in spectrogram hi = 128 # Height of image wi = 384 # Width of image # Loading demo track y, sr = librosa.load(librosa.ex('trumpet')) window = y[0:wi*hl] S = librosa.feature.melspectrogram(y=window, sr=sr, n_mels=hi, fmax=8000, hop_length=hl) S_dB = librosa.power_to_db(S, ref=np.max) img = librosa.display.specshow(S_dB, x_axis='time', y_axis='mel', sr=sr, fmax=8000, ax=ax) plt.savefig("out.png") plt.show()
[ { "code": null, "e": 1304, "s": 1062, "text": "Librosa is a Python package that helps to analyse audio and music files. This package also helps to create music retrieval information systems. In this article, we will see how to save a Librosa spectrogram plot as an image of specific size." }, { "code": null, "e": 1381, "s": 1304, "text": "Set the figure size and adjust the padding between and around the subplots.." }, { "code": null, "e": 1458, "s": 1381, "text": "Set the figure size and adjust the padding between and around the subplots.." }, { "code": null, "e": 1497, "s": 1458, "text": "Create a figure and a set of subplots." }, { "code": null, "e": 1536, "s": 1497, "text": "Create a figure and a set of subplots." }, { "code": null, "e": 1664, "s": 1536, "text": "Initialize three different variables, hl, hi, wi, to store samples per time in the spectrogram, height and width of the images." }, { "code": null, "e": 1792, "s": 1664, "text": "Initialize three different variables, hl, hi, wi, to store samples per time in the spectrogram, height and width of the images." }, { "code": null, "e": 1811, "s": 1792, "text": "Load a demo track." }, { "code": null, "e": 1830, "s": 1811, "text": "Load a demo track." }, { "code": null, "e": 1884, "s": 1830, "text": "Create a window, i.e., a list for audio time series.." }, { "code": null, "e": 1938, "s": 1884, "text": "Create a window, i.e., a list for audio time series.." }, { "code": null, "e": 2024, "s": 1938, "text": "Compute a mel-scaled spectrogram, using melspectrogram() with window and step 3 data." }, { "code": null, "e": 2110, "s": 2024, "text": "Compute a mel-scaled spectrogram, using melspectrogram() with window and step 3 data." }, { "code": null, "e": 2212, "s": 2110, "text": "Convert the power spectrogram (amplitude squared) to decibel (dB) units, using power_to_db() method.." }, { "code": null, "e": 2314, "s": 2212, "text": "Convert the power spectrogram (amplitude squared) to decibel (dB) units, using power_to_db() method.." }, { "code": null, "e": 2368, "s": 2314, "text": "Display the spectrogram as img (we can save it here)." }, { "code": null, "e": 2422, "s": 2368, "text": "Display the spectrogram as img (we can save it here)." }, { "code": null, "e": 2452, "s": 2422, "text": "Save the img using savefig()." }, { "code": null, "e": 2482, "s": 2452, "text": "Save the img using savefig()." }, { "code": null, "e": 2525, "s": 2482, "text": "Display the image using plt.show() method." }, { "code": null, "e": 2568, "s": 2525, "text": "Display the image using plt.show() method." }, { "code": null, "e": 3212, "s": 2568, "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport librosa.display\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nfig, ax = plt.subplots()\n\nhl = 512 # number of samples per time-step in spectrogram\nhi = 128 # Height of image\nwi = 384 # Width of image\n\n# Loading demo track\ny, sr = librosa.load(librosa.ex('trumpet'))\nwindow = y[0:wi*hl]\n\nS = librosa.feature.melspectrogram(y=window, sr=sr, n_mels=hi, fmax=8000,\nhop_length=hl)\nS_dB = librosa.power_to_db(S, ref=np.max)\nimg = librosa.display.specshow(S_dB, x_axis='time', y_axis='mel', sr=sr, fmax=8000, ax=ax)\n\nplt.savefig(\"out.png\")\nplt.show()" } ]
Rainfall Time Series Analysis and Forecasting | by Dery Kurniawan | Towards Data Science
A forecast is calculation or estimation of future events, especially for financial trends or coming weather. Until this year, forecasting was very helpful as a foundation to create any action or policy before facing any events. As an example, in the tropics region which several countries only had two seasons in a year (dry season and rainy season), many countries especially country which relies so much on agricultural commodities will need to forecast rainfall in term to decide the best time to start planting their products and maximizing their harvest. Another example is forecast can be used for a company to predict raw material prices movements and arrange the best strategy to maximize profit from it. In this article, we will try to do Rainfall forecasting in Banten Province located in Indonesia (One of the tropical country which relies on their agriculture commodity), we have 2006–2018 historical rainfall data1 and will try to forecast using “R” Language. A simple workflow will be used during this process: This data set contains Banten Province, Indonesia, rainfall historical data from January 2005 until December 2018. For this forecast, I will drop 2005 and start from 2006–2018 as a foundation for our forecast. #Import Necessary Librarylibrary(lubridate)library(ggplot2)library(tidyverse)library(dplyr)library(astsa)library(forecast)library(readxl)library(urca)library(ggfortify)library(tsutils)#Import Datahujan <- read_excel("../input/hujan-update/Hujan_Update.xlsx", sheet = 'Sheet1')hujan <- hujan %>% gather(key = "Tahun", value = "Curah_Hujan", -Bulan)#Converting To Time Serieshujan_ts <- ts(data = hujan[,3], frequency = 12, start = c(2005,1))#Selecting Data hujan_ts <- window(hujan_ts, start=c(2006,1))hujan_ts After running those code, we will get this following time series data: The first step on exploratory data analysis for any time series data is to visualize the value against the time. We will visualize our rainfall data into time series plot (Line chart, values against time) with this following code: #Plot Time Series Dataautoplot(hujan_ts) + ylab("Rainfall (mm2)") + xlab("Datetime") + scale_x_date(date_labels = '%b - %Y', breaks = '1 year', minor_breaks = '2 month') + theme_bw() + ggtitle("Banten Rainfall 2006 - 2018") Time series plot visualizes that rainfall has seasonality pattern without any trends occurred; rainfall will reach its higher value at the end of the years until January (Rainy Season) and decreased start from March to August (Dry Season). This pattern will always be repeated from year to year during 2006–2018 periods. We will decompose our time series data into more detail based on Trend, Seasonality, and Remainder component. Using this decomposition result, we hope to gain more precise insight into rainfall behavior during 2006–2018 periods. Decomposition will be done using stl() function and will automatically divide the time series into three components (Trend, Seasonality, Remainder). #Decomposition using stl()decomp <- stl(hujan_ts[,1], s.window = 'periodic')#Plot decompositionautoplot(decomp) + theme_bw() + scale_x_date(date_labels = '%b - %Y', breaks = '1 year', minor_breaks = '2 month') + ggtitle("Remainder") The trend cycle and the seasonal plot shows there’s seasonal fluctuation occurred with no specific trend and fairly random remainder/residual. There’s a calculation to measure trend and seasonality strength: Ft: Trend Strength Fs: Seasonal Strength The strength of the trend and seasonal measured between 0 and 1, while “1” means there’s very strong of trend and seasonal occurred. Tt <- trendcycle(decomp)St <- seasonal(decomp)Rt <- remainder(decomp)#Trend Strength CalculationFt <- round(max(0,1 - (var(Rt)/var(Tt + Rt))),1)#Seasonal Strength CalculationFs <- round(max(0,1 - (var(Rt)/var(St + Rt))),1)data.frame('Trend Strength' = Ft , 'Seasonal Strength' = Fs) By using the formula for measuring both trend and seasonal strength, we’re proving that our data has a seasonality pattern (Seasonal strength: 0.6) with no trend occurred (Trend Strength: 0.2). Seasonality Analysis We know that our data has a seasonality pattern. So, to explore more about our rainfall data seasonality; seasonal plot, seasonal-subseries plot, and seasonal boxplot will provide a much more insightful explanation about our data. #Seasonal Plotseasonplot(hujan_ts, year.labels = TRUE, col = 1:13, main = "Seasonal Plot", ylab= "Rainfall (mm2)") Seasonal plot indeed shows a seasonal pattern that occurred each year. Still, due to variances on several years during the period, we can’t see the pattern with only using this plot. Further exploration will use Seasonal Boxplot and Subseries plot to gain more in-depth analysis and insight from our data. #Seasonal Sub-Series Plotseasplot(hujan_ts, outplot = 3, trend = FALSE, main = "Seasonal Subseries Plot", ylab= "Rainfall (mm2)")#Seasonal Boxplotseasplot(hujan_ts, outplot = 2, trend = FALSE, main = "Seasonal Box Plot", ylab= "Rainfall (mm2)") Using seasonal boxplot and sub-series plot, we can more clearly see the data pattern. The horizontal lines indicate rainfall value means grouped by month, with using this information we’ve got the insight that Rainfall will start to decrease from April and reach its lowest point in August and September. Rainfall will begin to climb again after September and reach its peak in January. With this, we can assign Dry Season on April-September period and Rainy Season on October-March. It can be a beneficial insight for the country which relies on agriculture commodity like Indonesia. Dry and Rainy season prediction can be used to determine the right time to start planting agriculture commodities and maximize its output. Also, this information can help the government to prepare any policy as a prevention method against a flood that occurred due to heavy rain on the rainy season or against drought on dry season. The first step in forecasting is to choose the right model. To do so, we need to split our time series data set into the train and test set. The train set will be used to train several models, and further, this model should be tested on the test set. Split Train/Test Set Train set: We will use all of the data until December-2017 as our training set Test set: 2018 Period (January-December) will act as our test set #Create Train Sethujan_train <- window(hujan_ts, end = c(2017,12))#Create Test Set hujan_test <- window(hujan_ts, start = c(2018,1)) Stationary Test Train set data should be checked about its stationary before starting to build an ARIMA model. A stationary test can be done using Kwiatkowski–Phillips–Schmidt–Shin Test (KPSS) and Dickey-Fuller Test (D-F Test) from URCA package. #Kwiatkowski–Phillips–Schmidt–Shin Testsummary(ur.kpss(hujan_train)) #Dickey-Fuller Testsummary(ur.df(hujan_train)) ####################### # KPSS Unit Root Test # ####################### Test is of type: mu with 4 lags. Value of test-statistic is: 0.0531 Critical value for a significance level of: 10pct 5pct 2.5pct 1pctcritical values 0.347 0.463 0.574 0.739############################################### # Augmented Dickey-Fuller Test Unit Root Test # ############################################### Test regression none Call:lm(formula = z.diff ~ z.lag.1 - 1 + z.diff.lag)Residuals: Min 1Q Median 3Q Max -176.15 -43.66 3.80 68.21 355.75 Coefficients: Estimate Std. Error t value Pr(>|t|) z.lag.1 -0.15081 0.05230 -2.883 0.004555 ** z.diff.lag -0.28241 0.08111 -3.482 0.000664 ***---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Residual standard error: 96.77 on 140 degrees of freedomMultiple R-squared: 0.1755, Adjusted R-squared: 0.1637 F-statistic: 14.9 on 2 and 140 DF, p-value: 1.36e-06Value of test-statistic is: -2.8835 Critical values for test statistics: 1pct 5pct 10pcttau1 -2.58 -1.95 -1.62 Using 95% as confidence level, the null hypothesis (ho) for both of test defined as: KPSS Test: Data are stationary D-F Test: Data are non-stationary So, for KPSS Test we want p-value > 0.5 which we can accept null hypothesis and for D-F Test we want p-value < 0.05 to reject its null hypothesis. Based on the test which been done before, we can comfortably say that our training data is stationary. Model Assignment Forecasting will be done using both of ARIMA and ETS model, the comparison between those models also will be evaluated using some parameters against the test set. ARIMA Model The first step in building the ARIMA model is to create an autocorrelation plot on stationary time series data. Sometimes to have stationary data, we need to do differencing; for our case, we already have a stationary set. Therefore the number of differences (d, D) on our model can be set as zero. Our dataset has seasonality, so we need to build ARIMA (p,d,q)(P, D, Q)m, to get (p, P,q, Q) we will see autocorrelation plot (ACF/PACF) and derived those parameters from the plot. acf2(hujan_train) ACF Plot is used to get MA parameter (q, Q), there’s a significant spike at lag 2 and the sinusoidal curve indicates annual seasonality (m = 12). PACF Plot is used to get AR parameter (p, P), there’s a significant spike at lag 1 for AR parameter. This ACF/PACF plot suggests that the appropriate model might be ARIMA(1,0,2)(1,0,2). To make sure about this model, we will set other model based on our suggestion with modifying (AR) and (MA) component by ±1. Model-1 : ARIMA(1,0,2)(1,0,2)Model-2 : ARIMA(2,0,2)(2,0,2)Model-3 : ARIMA(1,0,1)(1,0,1)Model-4 : ARIMA(2,0,1)(2,0,1)Model-5 : ARIMA(0,0,2)(0,0,2)Model-6 : auto.arima() Model-1 : ARIMA(1,0,2)(1,0,2) Model-2 : ARIMA(2,0,2)(2,0,2) Model-3 : ARIMA(1,0,1)(1,0,1) Model-4 : ARIMA(2,0,1)(2,0,1) Model-5 : ARIMA(0,0,2)(0,0,2) Model-6 : auto.arima() we will also set auto.arima() as another comparison for our model and expecting to find a better fit for our time series. fit1 <- Arima(hujan_train, order = c(1,0,2), seasonal = c(1,0,2))fit2 <- Arima(hujan_train, order = c(2,0,2), seasonal = c(2,0,2))fit3 <- Arima(hujan_train, order = c(1,0,1), seasonal = c(1,0,1))fit4 <- Arima(hujan_train, order = c(2,0,1), seasonal = c(2,0,1))fit5 <- Arima(hujan_train, order = c(0,0,2), seasonal = c(0,0,2))fit6 <- auto.arima(hujan_train, stepwise = FALSE, approximation = FALSE) To choose the best fit among all of the ARIMA models for our data, we will compare AICc value between those models. The model with minimum AICc often is the best model for forecasting. data.frame('Model-1' = fit1$aicc, 'Model-2' = fit2$aicc, 'Model-3' = fit3$aicc, 'Model-4' = fit4$aicc, 'Model-5' = fit5$aicc,'Auto.Arima'= fit6$aicc, row.names = "AICc Value") AICc value of Model-1 is the lowest among other models, that’s why we will choose this model as our ARIMA model for forecasting. But, we also need to have residuals checked for this model to make sure this model will be appropriate for our time series forecasting. checkresiduals(fit1) Ljung-Box testdata: Residuals from ARIMA(1,0,2)(1,0,2)[12] with non-zero meanQ* = 10.187, df = 17, p-value = 0.8956Model df: 7. Total lags used: 24 Based on the Ljung-Box test and ACF plot of model residuals, we can conclude that this model is appropriate for forecasting since its residuals show white noise behavior and uncorrelated against each other. ETS Model We will build ETS model and compares its model with our chosen ARIMA model to see which model is better against our Test Set. #ETS Modelfit_ets <- ets(hujan_train, damped =TRUE) Similar to the ARIMA model, we also need to check its residuals behavior to make sure this model will work well for forecasting. checkresiduals(fit_ets)Ljung-Box testdata: Residuals from ETS(A,Ad,A)Q* = 40.433, df = 7, p-value = 1.04e-06Model df: 17. Total lags used: 24 After a residual check, ACF Plot shows ETS Model residuals have little correlation between each other on several lag, but most of the residuals are still within the limits and we will stay using this model as a comparison with our chosen ARIMA model. ARIMA vs ETS Model on Test Set Better models for our time series data can be checked using the test set. We will use both of ARIMA and ETS models to predict and see their accuracy against the test set (2018, Jan-Dec). In the first step, we need to plot visualization between ARIMA Model, ETS Model, and our actual 2018 data. But since ggfortify package doesn’t fit nicely with the other packages, we should little modify our code to show beautiful visualization. note: if you didn’t load ggfortify package, you can directly use : autoplot(actual data) + autolayer(forecast_data) , to do visualization. #Modifying Data For ggplotmodel_1 <- forecast(fit1, h=12) model_ets <- forecast(fit_ets, h=12)model_1 <- as.data.frame(model_1$mean)model_ets <- as.data.frame(model_ets$mean)colnames(model_1) <- "Curah_Hujan"colnames(model_ets) <- "Curah_Hujan"hujan_train_df <- as.data.frame(hujan_train)model_1_plot <- rbind(hujan_train_df,model_1)model_ets_plot <- rbind(hujan_train_df, model_ets)model_1_plot <- model_1_plot %>% mutate('Date' = seq(from = as.Date("2006-01-01", '%Y-%m-%d'), to = as.Date("2018-12-31",'%Y-%m-%d'),by = 'month'))model_ets_plot <- model_ets_plot %>% mutate('Date' = seq(from = as.Date("2006-01-01", '%Y-%m-%d'), to = as.Date("2018-12-31",'%Y-%m-%d'),by = 'month'))hujan_ts_df <- as.data.frame(hujan_ts)hujan_ts_df <- hujan_ts_df %>% mutate('Date' = seq(from = as.Date("2006-01-01", '%Y-%m-%d'), to = as.Date("2018-12-31",'%Y-%m-%d'),by = 'month'))hujan_train_df <- hujan_train_df %>% mutate('Date' = seq(from = as.Date("2006-01-01", '%Y-%m-%d'), to = as.Date("2017-12-31",'%Y-%m-%d'),by = 'month'))colors <- c("ARIMA Model Forecast 2018" = "blue", "ETS Model Forecast 2018" = "red", "Actual Data" = "black")#Creating Plotggplot() + geom_line(model_1_plot, mapping = aes(x=Date, y=Curah_Hujan, color= "ARIMA Model Forecast 2018"),lty = 2) + geom_line(model_ets_plot, mapping = aes(x=Date, y=Curah_Hujan, color= "ETS Model Forecast 2018"),lty= 2) + geom_line(hujan_ts_df,mapping = aes(x=Date, y=Curah_Hujan, color= "Actual Data"), lty = 1, show.legend = TRUE) + ylab("Rainfall (mm2)") + xlab("Datetime") + scale_x_date(date_labels = '%b - %Y', breaks = '1 year', minor_breaks = '2 month') + theme_bw() + ggtitle("Banten Rainfall 2006 - 2018") + scale_color_manual(values=colors) Even though both ARIMA and ETS models are not exactly fit the same value with actual data, but surely both of them plotting a quite similar movement against it. In numbers, we can calculate accuracy between those model with actual data and decide which one is most accurate with our data: #ARIMA Model Accuracyaccuracy(forecast(fit1, h=12), hujan_test) #ETS Model Accuracyaccuracy(forecast(fit_ets, h=12), hujan_test) based on the accuracy, ETS Model doing better in both training and test set compared to ARIMA Model. 2019–2020 Rainfall Forecasting Using the same parameter with the model that created using our train set, we will forecast 2019–2020 rainfall forecasting (h=24). Forecasting and Plot: #Create ModelARIMA_Model <- Arima(hujan_ts, order = c(1,0,2), seasonal = c(1,0,2))ETS_Model <- ets(hujan_ts, damped = TRUE, model = "AAA")#ARIMA Model Forecastautoplot(forecast(ARIMA_Model, h=24)) + theme_bw() + ylab("Rainfall (mm2)") + xlab("Datetime") + scale_x_date(date_labels = '%b - %Y', breaks = '1 year', minor_breaks = '2 month') + theme_bw() + ggtitle("Banten Rainfall Forecast 2019-2020 ARIMA Model")#ETS Model Forecastautoplot(forecast(ETS_Model, h=24)) + theme_bw() + ylab("Rainfall (mm2)") + xlab("Datetime") + scale_x_date(date_labels = '%b - %Y', breaks = '1 year', minor_breaks = '2 month') + theme_bw() + ggtitle("Banten Rainfall Forecast 2019-2020 ETS Model") Forecasting was done using both of the models, and they share similar movement based on the plot with the lowest value of rainfall will occur during August on both of 2019 and 2020. Our prediction can be useful for a farmer who wants to know which the best month to start planting and also for the government who need to prepare any policy for preventing flood on rainy season & drought on dry season. The most important thing is that this forecasting is based only on the historical trend, the more accurate prediction must be combined using meteorological data and some expertise from climate experts. [1]banten.bps.go.id.Accessed on May,17th 2020 [2]Hyndman, R.J., & Athanasopoulos, G. (2018) Forecasting: principles and practice, 2nd edition, OTexts: Melbourne, Australia. OTexts.com/fpp2.Accessed on May,17th 2020.
[ { "code": null, "e": 885, "s": 172, "text": "A forecast is calculation or estimation of future events, especially for financial trends or coming weather. Until this year, forecasting was very helpful as a foundation to create any action or policy before facing any events. As an example, in the tropics region which several countries only had two seasons in a year (dry season and rainy season), many countries especially country which relies so much on agricultural commodities will need to forecast rainfall in term to decide the best time to start planting their products and maximizing their harvest. Another example is forecast can be used for a company to predict raw material prices movements and arrange the best strategy to maximize profit from it." }, { "code": null, "e": 1145, "s": 885, "text": "In this article, we will try to do Rainfall forecasting in Banten Province located in Indonesia (One of the tropical country which relies on their agriculture commodity), we have 2006–2018 historical rainfall data1 and will try to forecast using “R” Language." }, { "code": null, "e": 1197, "s": 1145, "text": "A simple workflow will be used during this process:" }, { "code": null, "e": 1407, "s": 1197, "text": "This data set contains Banten Province, Indonesia, rainfall historical data from January 2005 until December 2018. For this forecast, I will drop 2005 and start from 2006–2018 as a foundation for our forecast." }, { "code": null, "e": 1919, "s": 1407, "text": "#Import Necessary Librarylibrary(lubridate)library(ggplot2)library(tidyverse)library(dplyr)library(astsa)library(forecast)library(readxl)library(urca)library(ggfortify)library(tsutils)#Import Datahujan <- read_excel(\"../input/hujan-update/Hujan_Update.xlsx\", sheet = 'Sheet1')hujan <- hujan %>% gather(key = \"Tahun\", value = \"Curah_Hujan\", -Bulan)#Converting To Time Serieshujan_ts <- ts(data = hujan[,3], frequency = 12, start = c(2005,1))#Selecting Data hujan_ts <- window(hujan_ts, start=c(2006,1))hujan_ts" }, { "code": null, "e": 1990, "s": 1919, "text": "After running those code, we will get this following time series data:" }, { "code": null, "e": 2221, "s": 1990, "text": "The first step on exploratory data analysis for any time series data is to visualize the value against the time. We will visualize our rainfall data into time series plot (Line chart, values against time) with this following code:" }, { "code": null, "e": 2448, "s": 2221, "text": "#Plot Time Series Dataautoplot(hujan_ts) + ylab(\"Rainfall (mm2)\") + xlab(\"Datetime\") + scale_x_date(date_labels = '%b - %Y', breaks = '1 year', minor_breaks = '2 month') + theme_bw() + ggtitle(\"Banten Rainfall 2006 - 2018\")" }, { "code": null, "e": 2769, "s": 2448, "text": "Time series plot visualizes that rainfall has seasonality pattern without any trends occurred; rainfall will reach its higher value at the end of the years until January (Rainy Season) and decreased start from March to August (Dry Season). This pattern will always be repeated from year to year during 2006–2018 periods." }, { "code": null, "e": 2998, "s": 2769, "text": "We will decompose our time series data into more detail based on Trend, Seasonality, and Remainder component. Using this decomposition result, we hope to gain more precise insight into rainfall behavior during 2006–2018 periods." }, { "code": null, "e": 3147, "s": 2998, "text": "Decomposition will be done using stl() function and will automatically divide the time series into three components (Trend, Seasonality, Remainder)." }, { "code": null, "e": 3383, "s": 3147, "text": "#Decomposition using stl()decomp <- stl(hujan_ts[,1], s.window = 'periodic')#Plot decompositionautoplot(decomp) + theme_bw() + scale_x_date(date_labels = '%b - %Y', breaks = '1 year', minor_breaks = '2 month') + ggtitle(\"Remainder\")" }, { "code": null, "e": 3526, "s": 3383, "text": "The trend cycle and the seasonal plot shows there’s seasonal fluctuation occurred with no specific trend and fairly random remainder/residual." }, { "code": null, "e": 3591, "s": 3526, "text": "There’s a calculation to measure trend and seasonality strength:" }, { "code": null, "e": 3610, "s": 3591, "text": "Ft: Trend Strength" }, { "code": null, "e": 3632, "s": 3610, "text": "Fs: Seasonal Strength" }, { "code": null, "e": 3765, "s": 3632, "text": "The strength of the trend and seasonal measured between 0 and 1, while “1” means there’s very strong of trend and seasonal occurred." }, { "code": null, "e": 4048, "s": 3765, "text": "Tt <- trendcycle(decomp)St <- seasonal(decomp)Rt <- remainder(decomp)#Trend Strength CalculationFt <- round(max(0,1 - (var(Rt)/var(Tt + Rt))),1)#Seasonal Strength CalculationFs <- round(max(0,1 - (var(Rt)/var(St + Rt))),1)data.frame('Trend Strength' = Ft , 'Seasonal Strength' = Fs)" }, { "code": null, "e": 4242, "s": 4048, "text": "By using the formula for measuring both trend and seasonal strength, we’re proving that our data has a seasonality pattern (Seasonal strength: 0.6) with no trend occurred (Trend Strength: 0.2)." }, { "code": null, "e": 4263, "s": 4242, "text": "Seasonality Analysis" }, { "code": null, "e": 4494, "s": 4263, "text": "We know that our data has a seasonality pattern. So, to explore more about our rainfall data seasonality; seasonal plot, seasonal-subseries plot, and seasonal boxplot will provide a much more insightful explanation about our data." }, { "code": null, "e": 4613, "s": 4494, "text": "#Seasonal Plotseasonplot(hujan_ts, year.labels = TRUE, col = 1:13, main = \"Seasonal Plot\", ylab= \"Rainfall (mm2)\")" }, { "code": null, "e": 4919, "s": 4613, "text": "Seasonal plot indeed shows a seasonal pattern that occurred each year. Still, due to variances on several years during the period, we can’t see the pattern with only using this plot. Further exploration will use Seasonal Boxplot and Subseries plot to gain more in-depth analysis and insight from our data." }, { "code": null, "e": 5175, "s": 4919, "text": "#Seasonal Sub-Series Plotseasplot(hujan_ts, outplot = 3, trend = FALSE, main = \"Seasonal Subseries Plot\", ylab= \"Rainfall (mm2)\")#Seasonal Boxplotseasplot(hujan_ts, outplot = 2, trend = FALSE, main = \"Seasonal Box Plot\", ylab= \"Rainfall (mm2)\")" }, { "code": null, "e": 5562, "s": 5175, "text": "Using seasonal boxplot and sub-series plot, we can more clearly see the data pattern. The horizontal lines indicate rainfall value means grouped by month, with using this information we’ve got the insight that Rainfall will start to decrease from April and reach its lowest point in August and September. Rainfall will begin to climb again after September and reach its peak in January." }, { "code": null, "e": 5899, "s": 5562, "text": "With this, we can assign Dry Season on April-September period and Rainy Season on October-March. It can be a beneficial insight for the country which relies on agriculture commodity like Indonesia. Dry and Rainy season prediction can be used to determine the right time to start planting agriculture commodities and maximize its output." }, { "code": null, "e": 6093, "s": 5899, "text": "Also, this information can help the government to prepare any policy as a prevention method against a flood that occurred due to heavy rain on the rainy season or against drought on dry season." }, { "code": null, "e": 6344, "s": 6093, "text": "The first step in forecasting is to choose the right model. To do so, we need to split our time series data set into the train and test set. The train set will be used to train several models, and further, this model should be tested on the test set." }, { "code": null, "e": 6365, "s": 6344, "text": "Split Train/Test Set" }, { "code": null, "e": 6444, "s": 6365, "text": "Train set: We will use all of the data until December-2017 as our training set" }, { "code": null, "e": 6510, "s": 6444, "text": "Test set: 2018 Period (January-December) will act as our test set" }, { "code": null, "e": 6643, "s": 6510, "text": "#Create Train Sethujan_train <- window(hujan_ts, end = c(2017,12))#Create Test Set hujan_test <- window(hujan_ts, start = c(2018,1))" }, { "code": null, "e": 6659, "s": 6643, "text": "Stationary Test" }, { "code": null, "e": 6889, "s": 6659, "text": "Train set data should be checked about its stationary before starting to build an ARIMA model. A stationary test can be done using Kwiatkowski–Phillips–Schmidt–Shin Test (KPSS) and Dickey-Fuller Test (D-F Test) from URCA package." }, { "code": null, "e": 8092, "s": 6889, "text": "#Kwiatkowski–Phillips–Schmidt–Shin Testsummary(ur.kpss(hujan_train)) #Dickey-Fuller Testsummary(ur.df(hujan_train)) ####################### # KPSS Unit Root Test # ####################### Test is of type: mu with 4 lags. Value of test-statistic is: 0.0531 Critical value for a significance level of: 10pct 5pct 2.5pct 1pctcritical values 0.347 0.463 0.574 0.739############################################### # Augmented Dickey-Fuller Test Unit Root Test # ############################################### Test regression none Call:lm(formula = z.diff ~ z.lag.1 - 1 + z.diff.lag)Residuals: Min 1Q Median 3Q Max -176.15 -43.66 3.80 68.21 355.75 Coefficients: Estimate Std. Error t value Pr(>|t|) z.lag.1 -0.15081 0.05230 -2.883 0.004555 ** z.diff.lag -0.28241 0.08111 -3.482 0.000664 ***---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Residual standard error: 96.77 on 140 degrees of freedomMultiple R-squared: 0.1755,\tAdjusted R-squared: 0.1637 F-statistic: 14.9 on 2 and 140 DF, p-value: 1.36e-06Value of test-statistic is: -2.8835 Critical values for test statistics: 1pct 5pct 10pcttau1 -2.58 -1.95 -1.62" }, { "code": null, "e": 8177, "s": 8092, "text": "Using 95% as confidence level, the null hypothesis (ho) for both of test defined as:" }, { "code": null, "e": 8208, "s": 8177, "text": "KPSS Test: Data are stationary" }, { "code": null, "e": 8242, "s": 8208, "text": "D-F Test: Data are non-stationary" }, { "code": null, "e": 8492, "s": 8242, "text": "So, for KPSS Test we want p-value > 0.5 which we can accept null hypothesis and for D-F Test we want p-value < 0.05 to reject its null hypothesis. Based on the test which been done before, we can comfortably say that our training data is stationary." }, { "code": null, "e": 8509, "s": 8492, "text": "Model Assignment" }, { "code": null, "e": 8672, "s": 8509, "text": "Forecasting will be done using both of ARIMA and ETS model, the comparison between those models also will be evaluated using some parameters against the test set." }, { "code": null, "e": 8684, "s": 8672, "text": "ARIMA Model" }, { "code": null, "e": 8983, "s": 8684, "text": "The first step in building the ARIMA model is to create an autocorrelation plot on stationary time series data. Sometimes to have stationary data, we need to do differencing; for our case, we already have a stationary set. Therefore the number of differences (d, D) on our model can be set as zero." }, { "code": null, "e": 9164, "s": 8983, "text": "Our dataset has seasonality, so we need to build ARIMA (p,d,q)(P, D, Q)m, to get (p, P,q, Q) we will see autocorrelation plot (ACF/PACF) and derived those parameters from the plot." }, { "code": null, "e": 9182, "s": 9164, "text": "acf2(hujan_train)" }, { "code": null, "e": 9429, "s": 9182, "text": "ACF Plot is used to get MA parameter (q, Q), there’s a significant spike at lag 2 and the sinusoidal curve indicates annual seasonality (m = 12). PACF Plot is used to get AR parameter (p, P), there’s a significant spike at lag 1 for AR parameter." }, { "code": null, "e": 9639, "s": 9429, "text": "This ACF/PACF plot suggests that the appropriate model might be ARIMA(1,0,2)(1,0,2). To make sure about this model, we will set other model based on our suggestion with modifying (AR) and (MA) component by ±1." }, { "code": null, "e": 9807, "s": 9639, "text": "Model-1 : ARIMA(1,0,2)(1,0,2)Model-2 : ARIMA(2,0,2)(2,0,2)Model-3 : ARIMA(1,0,1)(1,0,1)Model-4 : ARIMA(2,0,1)(2,0,1)Model-5 : ARIMA(0,0,2)(0,0,2)Model-6 : auto.arima()" }, { "code": null, "e": 9837, "s": 9807, "text": "Model-1 : ARIMA(1,0,2)(1,0,2)" }, { "code": null, "e": 9867, "s": 9837, "text": "Model-2 : ARIMA(2,0,2)(2,0,2)" }, { "code": null, "e": 9897, "s": 9867, "text": "Model-3 : ARIMA(1,0,1)(1,0,1)" }, { "code": null, "e": 9927, "s": 9897, "text": "Model-4 : ARIMA(2,0,1)(2,0,1)" }, { "code": null, "e": 9957, "s": 9927, "text": "Model-5 : ARIMA(0,0,2)(0,0,2)" }, { "code": null, "e": 9980, "s": 9957, "text": "Model-6 : auto.arima()" }, { "code": null, "e": 10102, "s": 9980, "text": "we will also set auto.arima() as another comparison for our model and expecting to find a better fit for our time series." }, { "code": null, "e": 10508, "s": 10102, "text": "fit1 <- Arima(hujan_train, order = c(1,0,2), seasonal = c(1,0,2))fit2 <- Arima(hujan_train, order = c(2,0,2), seasonal = c(2,0,2))fit3 <- Arima(hujan_train, order = c(1,0,1), seasonal = c(1,0,1))fit4 <- Arima(hujan_train, order = c(2,0,1), seasonal = c(2,0,1))fit5 <- Arima(hujan_train, order = c(0,0,2), seasonal = c(0,0,2))fit6 <- auto.arima(hujan_train, stepwise = FALSE, approximation = FALSE)" }, { "code": null, "e": 10693, "s": 10508, "text": "To choose the best fit among all of the ARIMA models for our data, we will compare AICc value between those models. The model with minimum AICc often is the best model for forecasting." }, { "code": null, "e": 10891, "s": 10693, "text": "data.frame('Model-1' = fit1$aicc, 'Model-2' = fit2$aicc, 'Model-3' = fit3$aicc, 'Model-4' = fit4$aicc, 'Model-5' = fit5$aicc,'Auto.Arima'= fit6$aicc, row.names = \"AICc Value\")" }, { "code": null, "e": 11156, "s": 10891, "text": "AICc value of Model-1 is the lowest among other models, that’s why we will choose this model as our ARIMA model for forecasting. But, we also need to have residuals checked for this model to make sure this model will be appropriate for our time series forecasting." }, { "code": null, "e": 11328, "s": 11156, "text": "checkresiduals(fit1)\tLjung-Box testdata: Residuals from ARIMA(1,0,2)(1,0,2)[12] with non-zero meanQ* = 10.187, df = 17, p-value = 0.8956Model df: 7. Total lags used: 24" }, { "code": null, "e": 11535, "s": 11328, "text": "Based on the Ljung-Box test and ACF plot of model residuals, we can conclude that this model is appropriate for forecasting since its residuals show white noise behavior and uncorrelated against each other." }, { "code": null, "e": 11545, "s": 11535, "text": "ETS Model" }, { "code": null, "e": 11671, "s": 11545, "text": "We will build ETS model and compares its model with our chosen ARIMA model to see which model is better against our Test Set." }, { "code": null, "e": 11723, "s": 11671, "text": "#ETS Modelfit_ets <- ets(hujan_train, damped =TRUE)" }, { "code": null, "e": 11852, "s": 11723, "text": "Similar to the ARIMA model, we also need to check its residuals behavior to make sure this model will work well for forecasting." }, { "code": null, "e": 11997, "s": 11852, "text": "checkresiduals(fit_ets)Ljung-Box testdata: Residuals from ETS(A,Ad,A)Q* = 40.433, df = 7, p-value = 1.04e-06Model df: 17. Total lags used: 24" }, { "code": null, "e": 12248, "s": 11997, "text": "After a residual check, ACF Plot shows ETS Model residuals have little correlation between each other on several lag, but most of the residuals are still within the limits and we will stay using this model as a comparison with our chosen ARIMA model." }, { "code": null, "e": 12279, "s": 12248, "text": "ARIMA vs ETS Model on Test Set" }, { "code": null, "e": 12466, "s": 12279, "text": "Better models for our time series data can be checked using the test set. We will use both of ARIMA and ETS models to predict and see their accuracy against the test set (2018, Jan-Dec)." }, { "code": null, "e": 12711, "s": 12466, "text": "In the first step, we need to plot visualization between ARIMA Model, ETS Model, and our actual 2018 data. But since ggfortify package doesn’t fit nicely with the other packages, we should little modify our code to show beautiful visualization." }, { "code": null, "e": 12850, "s": 12711, "text": "note: if you didn’t load ggfortify package, you can directly use : autoplot(actual data) + autolayer(forecast_data) , to do visualization." }, { "code": null, "e": 14572, "s": 12850, "text": "#Modifying Data For ggplotmodel_1 <- forecast(fit1, h=12) model_ets <- forecast(fit_ets, h=12)model_1 <- as.data.frame(model_1$mean)model_ets <- as.data.frame(model_ets$mean)colnames(model_1) <- \"Curah_Hujan\"colnames(model_ets) <- \"Curah_Hujan\"hujan_train_df <- as.data.frame(hujan_train)model_1_plot <- rbind(hujan_train_df,model_1)model_ets_plot <- rbind(hujan_train_df, model_ets)model_1_plot <- model_1_plot %>% mutate('Date' = seq(from = as.Date(\"2006-01-01\", '%Y-%m-%d'), to = as.Date(\"2018-12-31\",'%Y-%m-%d'),by = 'month'))model_ets_plot <- model_ets_plot %>% mutate('Date' = seq(from = as.Date(\"2006-01-01\", '%Y-%m-%d'), to = as.Date(\"2018-12-31\",'%Y-%m-%d'),by = 'month'))hujan_ts_df <- as.data.frame(hujan_ts)hujan_ts_df <- hujan_ts_df %>% mutate('Date' = seq(from = as.Date(\"2006-01-01\", '%Y-%m-%d'), to = as.Date(\"2018-12-31\",'%Y-%m-%d'),by = 'month'))hujan_train_df <- hujan_train_df %>% mutate('Date' = seq(from = as.Date(\"2006-01-01\", '%Y-%m-%d'), to = as.Date(\"2017-12-31\",'%Y-%m-%d'),by = 'month'))colors <- c(\"ARIMA Model Forecast 2018\" = \"blue\", \"ETS Model Forecast 2018\" = \"red\", \"Actual Data\" = \"black\")#Creating Plotggplot() + geom_line(model_1_plot, mapping = aes(x=Date, y=Curah_Hujan, color= \"ARIMA Model Forecast 2018\"),lty = 2) + geom_line(model_ets_plot, mapping = aes(x=Date, y=Curah_Hujan, color= \"ETS Model Forecast 2018\"),lty= 2) + geom_line(hujan_ts_df,mapping = aes(x=Date, y=Curah_Hujan, color= \"Actual Data\"), lty = 1, show.legend = TRUE) + ylab(\"Rainfall (mm2)\") + xlab(\"Datetime\") + scale_x_date(date_labels = '%b - %Y', breaks = '1 year', minor_breaks = '2 month') + theme_bw() + ggtitle(\"Banten Rainfall 2006 - 2018\") + scale_color_manual(values=colors)" }, { "code": null, "e": 14733, "s": 14572, "text": "Even though both ARIMA and ETS models are not exactly fit the same value with actual data, but surely both of them plotting a quite similar movement against it." }, { "code": null, "e": 14861, "s": 14733, "text": "In numbers, we can calculate accuracy between those model with actual data and decide which one is most accurate with our data:" }, { "code": null, "e": 14925, "s": 14861, "text": "#ARIMA Model Accuracyaccuracy(forecast(fit1, h=12), hujan_test)" }, { "code": null, "e": 14990, "s": 14925, "text": "#ETS Model Accuracyaccuracy(forecast(fit_ets, h=12), hujan_test)" }, { "code": null, "e": 15091, "s": 14990, "text": "based on the accuracy, ETS Model doing better in both training and test set compared to ARIMA Model." }, { "code": null, "e": 15122, "s": 15091, "text": "2019–2020 Rainfall Forecasting" }, { "code": null, "e": 15252, "s": 15122, "text": "Using the same parameter with the model that created using our train set, we will forecast 2019–2020 rainfall forecasting (h=24)." }, { "code": null, "e": 15274, "s": 15252, "text": "Forecasting and Plot:" }, { "code": null, "e": 15974, "s": 15274, "text": "#Create ModelARIMA_Model <- Arima(hujan_ts, order = c(1,0,2), seasonal = c(1,0,2))ETS_Model <- ets(hujan_ts, damped = TRUE, model = \"AAA\")#ARIMA Model Forecastautoplot(forecast(ARIMA_Model, h=24)) + theme_bw() + ylab(\"Rainfall (mm2)\") + xlab(\"Datetime\") + scale_x_date(date_labels = '%b - %Y', breaks = '1 year', minor_breaks = '2 month') + theme_bw() + ggtitle(\"Banten Rainfall Forecast 2019-2020 ARIMA Model\")#ETS Model Forecastautoplot(forecast(ETS_Model, h=24)) + theme_bw() + ylab(\"Rainfall (mm2)\") + xlab(\"Datetime\") + scale_x_date(date_labels = '%b - %Y', breaks = '1 year', minor_breaks = '2 month') + theme_bw() + ggtitle(\"Banten Rainfall Forecast 2019-2020 ETS Model\")" }, { "code": null, "e": 16156, "s": 15974, "text": "Forecasting was done using both of the models, and they share similar movement based on the plot with the lowest value of rainfall will occur during August on both of 2019 and 2020." }, { "code": null, "e": 16578, "s": 16156, "text": "Our prediction can be useful for a farmer who wants to know which the best month to start planting and also for the government who need to prepare any policy for preventing flood on rainy season & drought on dry season. The most important thing is that this forecasting is based only on the historical trend, the more accurate prediction must be combined using meteorological data and some expertise from climate experts." }, { "code": null, "e": 16624, "s": 16578, "text": "[1]banten.bps.go.id.Accessed on May,17th 2020" } ]
Explain Lifetime of a variable in C language.
Storage classes specify the scope, lifetime and binding of variables. To fully define a variable, one needs to mention not only its ‘type’ but also its storage class. A variable name identifies some physical location within computer memory, where a collection of bits are allocated for storing values of variable. Storage class tells us the following factors − Where the variable is stored (in memory or cpu register)? What will be the initial value of variable, if nothing is initialized? What is the scope of variable (where it can be accessed)? What is the life of a variable? The lifetime of a variable defines the duration for which the computer allocates memory for it (the duration between allocation and deallocation of memory). In C language, a variable can have automatic, static or dynamic lifetime. Automatic − A variable with automatic lifetime are created. Every time, their declaration is encountered and destroyed. Also, their blocks are exited. Static − A variable is created when the declaration is executed for the first time. It is destroyed when the execution stops/terminates. Dynamic − The variables memory is allocated and deallocated through memory management functions. There are four storage classes in C language − Following is the C program for automatic storage class − Live Demo #include<stdio.h> main ( ){ auto int i=1;{ auto int i=2;{ auto int i=3; printf ("%d",i) } printf("%d", i); } printf("%d", i); } When the above program is executed, it produces the following output − 3 2 1 Following is the C program for external storage class − Live Demo #include<stdio.h> extern int i =1; /* this ‘i’ is available throughout program */ main ( ){ int i = 3; /* this ‘i' available only in main */ printf ("%d", i); fun ( ); } fun ( ) { printf ("%d", i); } When the above program is executed, it produces the following output − 3 1
[ { "code": null, "e": 1132, "s": 1062, "text": "Storage classes specify the scope, lifetime and binding of variables." }, { "code": null, "e": 1229, "s": 1132, "text": "To fully define a variable, one needs to mention not only its ‘type’ but also its storage class." }, { "code": null, "e": 1376, "s": 1229, "text": "A variable name identifies some physical location within computer memory, where a collection of bits are allocated for storing values of variable." }, { "code": null, "e": 1423, "s": 1376, "text": "Storage class tells us the following factors −" }, { "code": null, "e": 1481, "s": 1423, "text": "Where the variable is stored (in memory or cpu register)?" }, { "code": null, "e": 1552, "s": 1481, "text": "What will be the initial value of variable, if nothing is initialized?" }, { "code": null, "e": 1610, "s": 1552, "text": "What is the scope of variable (where it can be accessed)?" }, { "code": null, "e": 1642, "s": 1610, "text": "What is the life of a variable?" }, { "code": null, "e": 1799, "s": 1642, "text": "The lifetime of a variable defines the duration for which the computer allocates memory for it (the duration between allocation and deallocation of memory)." }, { "code": null, "e": 1873, "s": 1799, "text": "In C language, a variable can have automatic, static or dynamic lifetime." }, { "code": null, "e": 2024, "s": 1873, "text": "Automatic − A variable with automatic lifetime are created. Every time, their declaration is encountered and destroyed. Also, their blocks are exited." }, { "code": null, "e": 2161, "s": 2024, "text": "Static − A variable is created when the declaration is executed for the first time. It is destroyed when the execution stops/terminates." }, { "code": null, "e": 2258, "s": 2161, "text": "Dynamic − The variables memory is allocated and deallocated through memory management functions." }, { "code": null, "e": 2305, "s": 2258, "text": "There are four storage classes in C language −" }, { "code": null, "e": 2362, "s": 2305, "text": "Following is the C program for automatic storage class −" }, { "code": null, "e": 2373, "s": 2362, "text": " Live Demo" }, { "code": null, "e": 2546, "s": 2373, "text": "#include<stdio.h>\nmain ( ){\n auto int i=1;{\n auto int i=2;{\n auto int i=3;\n printf (\"%d\",i)\n }\n printf(\"%d\", i);\n }\n printf(\"%d\", i);\n}" }, { "code": null, "e": 2617, "s": 2546, "text": "When the above program is executed, it produces the following output −" }, { "code": null, "e": 2623, "s": 2617, "text": "3 2 1" }, { "code": null, "e": 2679, "s": 2623, "text": "Following is the C program for external storage class −" }, { "code": null, "e": 2690, "s": 2679, "text": " Live Demo" }, { "code": null, "e": 2902, "s": 2690, "text": "#include<stdio.h>\nextern int i =1; /* this ‘i’ is available throughout program */\nmain ( ){\n int i = 3; /* this ‘i' available only in main */\n printf (\"%d\", i);\n fun ( );\n}\nfun ( ) {\n printf (\"%d\", i);\n}" }, { "code": null, "e": 2973, "s": 2902, "text": "When the above program is executed, it produces the following output −" }, { "code": null, "e": 2977, "s": 2973, "text": "3 1" } ]
<mat-grid-list> in Angular Material - GeeksforGeeks
24 Sep, 2021 Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. mat-grid-list tag is used for styling the content in grids form. Installation syntax: ng add @angular/material Approach: First, install the angular material using the above-mentioned command. After completing the installation, Import ‘MatGridListModule’ from ‘@angular/material/grid-list’ in the app.module.ts file. Then use <mat-grid-list> tag to group all the items inside this group tag. Inside the <mat-grid-list> tag we need to use <mat-grid-tile tag for every item. We also have properties like cols and rowHeight which we can use for styling. cols property is used to display number of grids in a row. Once done with the above steps then serve or start the project. Code Implementation: app.module.ts import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatGridListModule } from '@angular/material'; import { AppComponent } from './example.component'; @NgModule({ declarations: [AppComponent], exports: [AppComponent], imports: [ CommonModule, FormsModule, MatGridListModule ], }) export class AppModule {} app.component.html <mat-grid-list cols="3" rowHeight="2:1"> <mat-grid-tile>First Grid</mat-grid-tile> <mat-grid-tile>Second Grid</mat-grid-tile> <mat-grid-tile>Third Grid</mat-grid-tile> <mat-grid-tile>Fourth Grid</mat-grid-tile> <mat-grid-tile>Fifth Grid</mat-grid-tile> <mat-grid-tile>Sixth Frid</mat-grid-tile> </mat-grid-list> app.component.scss : mat-grid-tile { background: lightsalmon; } Output: simmytarika5 Angular-material Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Angular Libraries For Web Developers Angular 10 (blur) Event Angular PrimeNG Dropdown Component How to make a Bootstrap Modal Popup in Angular 9/8 ? How to create module with Routing in Angular 9 ? Roadmap to Become a Web Developer in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? Installation of Node.js on Linux Convert a string to an integer in JavaScript
[ { "code": null, "e": 25181, "s": 25150, "text": " \n24 Sep, 2021\n" }, { "code": null, "e": 25539, "s": 25181, "text": "Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. mat-grid-list tag is used for styling the content in grids form." }, { "code": null, "e": 25560, "s": 25539, "text": "Installation syntax:" }, { "code": null, "e": 25585, "s": 25560, "text": "ng add @angular/material" }, { "code": null, "e": 25595, "s": 25585, "text": "Approach:" }, { "code": null, "e": 25666, "s": 25595, "text": "First, install the angular material using the above-mentioned command." }, { "code": null, "e": 25790, "s": 25666, "text": "After completing the installation, Import ‘MatGridListModule’ from ‘@angular/material/grid-list’ in the app.module.ts file." }, { "code": null, "e": 25865, "s": 25790, "text": "Then use <mat-grid-list> tag to group all the items inside this group tag." }, { "code": null, "e": 25946, "s": 25865, "text": "Inside the <mat-grid-list> tag we need to use <mat-grid-tile tag for every item." }, { "code": null, "e": 26083, "s": 25946, "text": "We also have properties like cols and rowHeight which we can use for styling. cols property is used to display number of grids in a row." }, { "code": null, "e": 26147, "s": 26083, "text": "Once done with the above steps then serve or start the project." }, { "code": null, "e": 26168, "s": 26147, "text": "Code Implementation:" }, { "code": null, "e": 26182, "s": 26168, "text": "app.module.ts" }, { "code": "\n\n\n\n\n\n\nimport { CommonModule } from '@angular/common'; \nimport { NgModule } from '@angular/core'; \nimport { FormsModule } from '@angular/forms'; \nimport { MatGridListModule } from '@angular/material'; \n \nimport { AppComponent } from './example.component'; \n \n@NgModule({ \n declarations: [AppComponent], \n exports: [AppComponent], \n imports: [ \n CommonModule, \n FormsModule, \n MatGridListModule \n \n ], \n}) \nexport class AppModule {}\n\n\n\n\n\n", "e": 26663, "s": 26192, "text": null }, { "code": null, "e": 26682, "s": 26663, "text": "app.component.html" }, { "code": "\n\n\n\n\n\n\n<mat-grid-list cols=\"3\" rowHeight=\"2:1\"> \n \n <mat-grid-tile>First Grid</mat-grid-tile> \n <mat-grid-tile>Second Grid</mat-grid-tile> \n <mat-grid-tile>Third Grid</mat-grid-tile> \n <mat-grid-tile>Fourth Grid</mat-grid-tile> \n <mat-grid-tile>Fifth Grid</mat-grid-tile> \n <mat-grid-tile>Sixth Frid</mat-grid-tile> \n \n</mat-grid-list> \n\n\n\n\n\n", "e": 27045, "s": 26692, "text": null }, { "code": null, "e": 27066, "s": 27045, "text": "app.component.scss :" }, { "code": null, "e": 27111, "s": 27066, "text": "mat-grid-tile {\n background: lightsalmon;\n}" }, { "code": null, "e": 27119, "s": 27111, "text": "Output:" }, { "code": null, "e": 27136, "s": 27123, "text": "simmytarika5" }, { "code": null, "e": 27155, "s": 27136, "text": "\nAngular-material\n" }, { "code": null, "e": 27164, "s": 27155, "text": "\nPicked\n" }, { "code": null, "e": 27176, "s": 27164, "text": "\nAngularJS\n" }, { "code": null, "e": 27195, "s": 27176, "text": "\nWeb Technologies\n" }, { "code": null, "e": 27400, "s": 27195, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 27444, "s": 27400, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 27468, "s": 27444, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 27503, "s": 27468, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 27556, "s": 27503, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 27605, "s": 27556, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 27647, "s": 27605, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27709, "s": 27647, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27752, "s": 27709, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27785, "s": 27752, "text": "Installation of Node.js on Linux" } ]
How can I show figures separately in Matplotlib?
To show multiple figures in matplotlib, we can take the following Steps − To create a new figure, or activate an existing figure, use the figure() method. (Create two figures namely, Figure1 and Figure2). To create a new figure, or activate an existing figure, use the figure() method. (Create two figures namely, Figure1 and Figure2). Plot the lines with the same lists (colors red and green and linewidth 2 and 5). Plot the lines with the same lists (colors red and green and linewidth 2 and 5). Set the title of the plot over both the figures. Set the title of the plot over both the figures. To display the figure, use the show() method. To display the figure, use the show() method. from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True fig1 = plt.figure("Figure 1") plt.plot([1, 3, 7, 3, 1], c="red", lw=2) plt.title("I am the part of figure 1") fig2 = plt.figure("Figure 2") plt.plot([1, 3, 7, 3, 1], c="green", lw=5) plt.title("I am the part of figure 2") plt.show()
[ { "code": null, "e": 1136, "s": 1062, "text": "To show multiple figures in matplotlib, we can take the following Steps −" }, { "code": null, "e": 1267, "s": 1136, "text": "To create a new figure, or activate an existing figure, use the figure() method. (Create two figures namely, Figure1 and Figure2)." }, { "code": null, "e": 1398, "s": 1267, "text": "To create a new figure, or activate an existing figure, use the figure() method. (Create two figures namely, Figure1 and Figure2)." }, { "code": null, "e": 1479, "s": 1398, "text": "Plot the lines with the same lists (colors red and green and linewidth 2 and 5)." }, { "code": null, "e": 1560, "s": 1479, "text": "Plot the lines with the same lists (colors red and green and linewidth 2 and 5)." }, { "code": null, "e": 1609, "s": 1560, "text": "Set the title of the plot over both the figures." }, { "code": null, "e": 1658, "s": 1609, "text": "Set the title of the plot over both the figures." }, { "code": null, "e": 1704, "s": 1658, "text": "To display the figure, use the show() method." }, { "code": null, "e": 1750, "s": 1704, "text": "To display the figure, use the show() method." }, { "code": null, "e": 2107, "s": 1750, "text": "from matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nfig1 = plt.figure(\"Figure 1\")\nplt.plot([1, 3, 7, 3, 1], c=\"red\", lw=2)\nplt.title(\"I am the part of figure 1\")\nfig2 = plt.figure(\"Figure 2\")\nplt.plot([1, 3, 7, 3, 1], c=\"green\", lw=5)\nplt.title(\"I am the part of figure 2\")\nplt.show()" } ]
How to find difference between 2 files in Python?
The Python standard library has a module specifically for the purpose of finding diffs between strings/files. To get a diff using the difflib library, you can simply call the united_diff function on it. For example, Lets say you have 2 files, file1 and file2 with the following content: file1: Hello People of the world file2: Hello People from India Now to take their diff use the following code: import difflib with open('file1') as f1: f1_text = f1.read() with open('file2') as f2: f2_text = f2.read() # Find and print the diff: for line in difflib.unified_diff(f1_text, f2_text, fromfile='file1', tofile='file2', lineterm=''): print line This will give the output: --- file1 +++ file2 @@ -1,5 +1,4 @@ Hello People -of -the -world +from +India
[ { "code": null, "e": 1265, "s": 1062, "text": "The Python standard library has a module specifically for the purpose of finding diffs between strings/files. To get a diff using the difflib library, you can simply call the united_diff function on it." }, { "code": null, "e": 1349, "s": 1265, "text": "For example, Lets say you have 2 files, file1 and file2 with the following content:" }, { "code": null, "e": 1413, "s": 1349, "text": "file1:\nHello\nPeople\nof\nthe\nworld\nfile2:\nHello\nPeople\nfrom\nIndia" }, { "code": null, "e": 1460, "s": 1413, "text": "Now to take their diff use the following code:" }, { "code": null, "e": 1716, "s": 1460, "text": "import difflib\nwith open('file1') as f1:\n f1_text = f1.read()\nwith open('file2') as f2:\n f2_text = f2.read()\n# Find and print the diff:\nfor line in difflib.unified_diff(f1_text, f2_text, fromfile='file1', tofile='file2', lineterm=''):\n print line" }, { "code": null, "e": 1743, "s": 1716, "text": "This will give the output:" }, { "code": null, "e": 1823, "s": 1743, "text": "--- file1\n+++ file2\n@@ -1,5 +1,4 @@\n Hello\n People\n-of\n-the\n-world\n+from\n+India" } ]
How to change opacity of every data element on hover in a table using CSS ?
28 May, 2020 There is a Table made by using HTML in which data elements are set to a low opacity. The task is to change the opacity of a particular element when user hover over data elements. To make a table look better, we will use gradient colors to set backgrounds of the table data elements. In this approach, we will be using the opacity property of CSS to complete the task. opacity: The opacity property is used in the image to describe the transparency of the image. The value of opacity lies between 0.0 to 1.0 where the low value represents high transparent and high value represents low transparent. Approach: First Make the HTML file with defining the Table and its data.<table> <tr> <td> data 1</td> <td> data 2</td> <td> data 3</td> </tr> </table> <table> <tr> <td> data 1</td> <td> data 2</td> <td> data 3</td> </tr> </table> The table heading tags <th> is styled with white text and gradient background color. For table data element tags <td> opacity is set to 0.7 initially, with light gradient background which seems faded initially. On hover, the opacity of element is set to 1, this makes the element clear and defined.td:nth-child(odd):hover { opacity: 1; } For all odd child of <td> tagtd:nth-child(even):hover{ opacity: 1; } td:nth-child(odd):hover { opacity: 1; } For all odd child of <td> tag td:nth-child(even):hover{ opacity: 1; } Example: <!DOCTYPE html><html> <head> <title>Table Styling</title> <style> h1 { text-align: center; margin-top: 5vw; color: green; } table { margin-left: 25vw; } th { text-align: center; width: 200px; color: white; background-image:linear-gradient( to bottom, #6B8E23, #556B2F); height: 40px; padding: 0px 10px; border-bottom: 3px solid #9ACD32; border-radius: 5px 5px 0px 0px; } td:nth-child(odd):hover { opacity: 1; } td:nth-child(even):hover { opacity: 1; } td { opacity: 0.7; border-radius: 2px; text-align: center; vertical-align: middle; height: 40px; background: rgb(144, 238, 144, 0.3); padding: 0px 10px; } </style></head> <body> <h1>GeeksforGeeks</h1> <table> <tr> <th>Name</th> <th>Age</th> <th>Address</th> </tr> <tr> <td>Name 1</td> <td>Age 1</td> <td>Address 1</td> </tr> <tr> <td>Name 2</td> <td>Age 2</td> <td>Address 2</td> </tr> <tr> <td>Name 3</td> <td>Age 3</td> <td>Address 3</td> </tr> <tr> <td>Name 4</td> <td>Age 4</td> <td>Address 4</td> </tr> </table></body> </html> Output: You can see that when mouse hover over <td> elements, their opacity changes to 1 and they seem more clear and defined. CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 May, 2020" }, { "code": null, "e": 207, "s": 28, "text": "There is a Table made by using HTML in which data elements are set to a low opacity. The task is to change the opacity of a particular element when user hover over data elements." }, { "code": null, "e": 396, "s": 207, "text": "To make a table look better, we will use gradient colors to set backgrounds of the table data elements. In this approach, we will be using the opacity property of CSS to complete the task." }, { "code": null, "e": 626, "s": 396, "text": "opacity: The opacity property is used in the image to describe the transparency of the image. The value of opacity lies between 0.0 to 1.0 where the low value represents high transparent and high value represents low transparent." }, { "code": null, "e": 637, "s": 626, "text": "Approach: " }, { "code": null, "e": 795, "s": 637, "text": "First Make the HTML file with defining the Table and its data.<table>\n <tr>\n <td> data 1</td>\n <td> data 2</td>\n <td> data 3</td>\n </tr>\n</table>\n" }, { "code": null, "e": 891, "s": 795, "text": "<table>\n <tr>\n <td> data 1</td>\n <td> data 2</td>\n <td> data 3</td>\n </tr>\n</table>\n" }, { "code": null, "e": 976, "s": 891, "text": "The table heading tags <th> is styled with white text and gradient background color." }, { "code": null, "e": 1102, "s": 976, "text": "For table data element tags <td> opacity is set to 0.7 initially, with light gradient background which seems faded initially." }, { "code": null, "e": 1307, "s": 1102, "text": "On hover, the opacity of element is set to 1, this makes the element clear and defined.td:nth-child(odd):hover {\n opacity: 1;\n}\nFor all odd child of <td> tagtd:nth-child(even):hover{\n opacity: 1;\n}\n" }, { "code": null, "e": 1352, "s": 1307, "text": "td:nth-child(odd):hover {\n opacity: 1;\n}\n" }, { "code": null, "e": 1382, "s": 1352, "text": "For all odd child of <td> tag" }, { "code": null, "e": 1427, "s": 1382, "text": "td:nth-child(even):hover{\n opacity: 1;\n}\n" }, { "code": null, "e": 1436, "s": 1427, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>Table Styling</title> <style> h1 { text-align: center; margin-top: 5vw; color: green; } table { margin-left: 25vw; } th { text-align: center; width: 200px; color: white; background-image:linear-gradient( to bottom, #6B8E23, #556B2F); height: 40px; padding: 0px 10px; border-bottom: 3px solid #9ACD32; border-radius: 5px 5px 0px 0px; } td:nth-child(odd):hover { opacity: 1; } td:nth-child(even):hover { opacity: 1; } td { opacity: 0.7; border-radius: 2px; text-align: center; vertical-align: middle; height: 40px; background: rgb(144, 238, 144, 0.3); padding: 0px 10px; } </style></head> <body> <h1>GeeksforGeeks</h1> <table> <tr> <th>Name</th> <th>Age</th> <th>Address</th> </tr> <tr> <td>Name 1</td> <td>Age 1</td> <td>Address 1</td> </tr> <tr> <td>Name 2</td> <td>Age 2</td> <td>Address 2</td> </tr> <tr> <td>Name 3</td> <td>Age 3</td> <td>Address 3</td> </tr> <tr> <td>Name 4</td> <td>Age 4</td> <td>Address 4</td> </tr> </table></body> </html>", "e": 3022, "s": 1436, "text": null }, { "code": null, "e": 3030, "s": 3022, "text": "Output:" }, { "code": null, "e": 3149, "s": 3030, "text": "You can see that when mouse hover over <td> elements, their opacity changes to 1 and they seem more clear and defined." }, { "code": null, "e": 3158, "s": 3149, "text": "CSS-Misc" }, { "code": null, "e": 3168, "s": 3158, "text": "HTML-Misc" }, { "code": null, "e": 3172, "s": 3168, "text": "CSS" }, { "code": null, "e": 3177, "s": 3172, "text": "HTML" }, { "code": null, "e": 3194, "s": 3177, "text": "Web Technologies" }, { "code": null, "e": 3221, "s": 3194, "text": "Web technologies Questions" }, { "code": null, "e": 3226, "s": 3221, "text": "HTML" } ]
Find all angles of a triangle in 3D
21 Jul, 2021 Given coordinates of 3 vertices of a triangle in 3D i.e. A(x1, y1, z1), B(x2, y2, z2), C(x3, y3, z3). The task is to find out all the angles of the triangle formed by above coordinates.Examples: Input: x1 = -1, y1 = 3, z1 = 2 x2 = 2, y2 = 3, z2 = 5 x3 = 3, y3 = 5, z3 = -2 Output: angle A = 90.0 degree angle B = 54.736 degree angle C = 35.264 degree Approach: For finding angle A find out direction ratios of AB and AC : direction ratios of AB = x2-x1, y2-y1, z2-z1 direction ratios of AC = x3-x1, y3-y1, z3-z1 then angle A = For finding angle B find out direction ratios of BA and BC : direction ratios of BA = x1-x2, y1-y2, z1-z2 direction ratios of BC = x3-x2, y3-y2, z3-z2 then angle B = For finding angle C find out direction ratios of CB and CA : direction ratios of CB = x2-x3, y2-y3, z2-z3 direction ratios of CA = x1-x3, y1-y3, z1-z3 then angle C = Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript //CPP program for finding all angles of a triangle#include<bits/stdc++.h>#include<cmath>using namespace std; // function for finding the anglefloat angle_triangle(int x1, int x2, int x3, int y1, int y2, int y3, int z1, int z2, int z3){ int num = (x2-x1)*(x3-x1)+(y2-y1)*(y3-y1)+(z2-z1)*(z3-z1) ; float den = sqrt(pow((x2-x1),2)+pow((y2-y1),2)+pow((z2-z1),2))*\ sqrt(pow((x3-x1),2)+pow((y3-y1),2)+pow((z3-z1),2)) ; float angle = acos(num / den)*(180.0/3.141592653589793238463) ; return angle ;} // Driver codeint main(){int x1 = -1;int y1 = 3;int z1 = 2;int x2 = 2;int y2 = 3;int z2 = 5;int x3 = 3;int y3 = 5;int z3 = -2;float angle_A = angle_triangle(x1, x2, x3, y1, y2, y3, z1, z2, z3);float angle_B = angle_triangle(x2, x3, x1, y2, y3, y1, z2, z3, z1);float angle_C = angle_triangle(x3, x2, x1, y3, y2, y1, z3, z2, z1);cout<<"Angles are :"<<endl;cout<<setprecision(3);cout<<"angle A = "<<angle_A<<" degree"<<endl;cout<<"angle B = "<<angle_B<<" degree"<<endl;cout<<"angle C = "<<angle_C<< " degree"<<endl;} //Java program for finding all angles of a triangle class GFG{// function for finding the anglestatic double angle_triangle(int x1, int x2, int x3, int y1, int y2, int y3, int z1, int z2, int z3){ int num = (x2-x1)*(x3-x1)+(y2-y1)*(y3-y1)+(z2-z1)*(z3-z1) ; double den = Math.sqrt(Math.pow((x2-x1),2)+ Math.pow((y2-y1),2)+Math.pow((z2-z1),2))* Math.sqrt(Math.pow((x3-x1),2)+ Math.pow((y3-y1),2)+Math.pow((z3-z1),2)) ; double angle = Math.acos(num / den)*(180.0/3.141592653589793238463) ; return angle ;} // Driver codepublic static void main(String[] args){int x1 = -1;int y1 = 3;int z1 = 2;int x2 = 2;int y2 = 3;int z2 = 5;int x3 = 3;int y3 = 5;int z3 = -2;double angle_A = angle_triangle(x1, x2, x3, y1, y2, y3, z1, z2, z3);double angle_B = angle_triangle(x2, x3, x1, y2, y3, y1, z2, z3, z1);double angle_C = angle_triangle(x3, x2, x1, y3, y2, y1, z3, z2, z1);System.out.println("Angles are :");System.out.println("angle A = "+angle_A+" degree");System.out.println("angle B = "+angle_B+" degree");System.out.println("angle C = "+angle_C+" degree");}}// This code is contributed by mits # Python Code for finding all angles of a triangleimport math # function for finding the angledef angle_triangle(x1, x2, x3, y1, y2, y3, z1, z2, z3): num = (x2-x1)*(x3-x1)+(y2-y1)*(y3-y1)+(z2-z1)*(z3-z1) den = math.sqrt((x2-x1)**2+(y2-y1)**2+(z2-z1)**2)*\ math.sqrt((x3-x1)**2+(y3-y1)**2+(z3-z1)**2) angle = math.degrees(math.acos(num / den)) return round(angle, 3) # driver code x1 = -1y1 = 3z1 = 2x2 = 2y2 = 3z2 = 5x3 = 3y3 = 5z3 = -2angle_A = angle_triangle(x1, x2, x3, y1, y2, y3, z1, z2, z3)angle_B = angle_triangle(x2, x3, x1, y2, y3, y1, z2, z3, z1)angle_C = angle_triangle(x3, x2, x1, y3, y2, y1, z3, z2, z1)print("Angles are :")print("angle A = ", angle_A, "degree")print("angle B = ", angle_B, "degree")print("angle C = ", angle_C, "degree") // C# program for finding all// angles of a triangleusing System; class GFG{ // function for finding the anglestatic double angle_triangle(int x1, int x2, int x3, int y1, int y2, int y3, int z1, int z2, int z3){ int num = (x2 - x1) * (x3 - x1) + (y2 - y1) * (y3 - y1) + (z2 - z1) * (z3 - z1); double den = Math.Sqrt(Math.Pow((x2 - x1), 2) + Math.Pow((y2 - y1), 2) + Math.Pow((z2 - z1), 2)) * Math.Sqrt(Math.Pow((x3 - x1), 2) + Math.Pow((y3 - y1), 2) + Math.Pow((z3 - z1), 2)); double angle = Math.Acos(num / den) * (180.0/3.141592653589793238463); return angle ;} // Driver codepublic static void Main(){ int x1 = -1, y1 = 3, z1 = 2; int x2 = 2, y2 = 3, z2 = 5; int x3 = 3, y3 = 5, z3 = -2; double angle_A = angle_triangle(x1, x2, x3, y1, y2, y3, z1, z2, z3); double angle_B = angle_triangle(x2, x3, x1, y2, y3, y1, z2, z3, z1); double angle_C = angle_triangle(x3, x2, x1, y3, y2, y1, z3, z2, z1); Console.WriteLine("Angles are :"); Console.WriteLine("angle A = " + angle_A + " degree"); Console.WriteLine("angle B = " + angle_B + " degree"); Console.WriteLine("angle C = " + angle_C + " degree");}} // This code is contributed by 29AjayKumar <?php// PHP program for finding all// angles of a triangle // function for finding the anglefunction angle_triangle($x1, $x2, $x3, $y1, $y2, $y3, $z1, $z2, $z3){ $num = ($x2 - $x1) * ($x3 - $x1) + ($y2 - $y1) * ($y3 - $y1) + ($z2 - $z1) * ($z3 - $z1); $den = sqrt(pow(($x2 - $x1), 2) + pow(($y2 - $y1), 2) + pow(($z2 - $z1), 2)) * sqrt(pow(($x3 - $x1), 2) + pow(($y3 - $y1), 2) + pow(($z3 - $z1), 2)); $angle = acos($num / $den) * (180.0 / 3.141592653589793238463); return $angle ;} // Driver code$x1 = -1; $y1 = 3; $z1 = 2;$x2 = 2; $y2 = 3; $z2 = 5;$x3 = 3; $y3 = 5; $z3 = -2;$angle_A = angle_triangle($x1, $x2, $x3, $y1, $y2, $y3, $z1, $z2, $z3);$angle_B = angle_triangle($x2, $x3, $x1, $y2, $y3, $y1, $z2, $z3, $z1);$angle_C = angle_triangle($x3, $x2, $x1, $y3, $y2, $y1, $z3, $z2, $z1);echo "Angles are :\n";echo "angle A = " . round($angle_A, 3) . " degree\n";echo "angle B = " . round($angle_B, 3) . " degree\n";echo "angle C = " . round($angle_C, 3) . " degree\n"; // This code is contributed by mits?> <script>//Javascript program for finding all angles of a triangle // function for finding the anglefunction angle_triangle(x1,x2,x3,y1,y2,y3,z1,z2,z3){ let num = (x2-x1)*(x3-x1)+(y2-y1)*(y3-y1)+(z2-z1)*(z3-z1) ; let den = Math.sqrt(Math.pow((x2-x1),2)+ Math.pow((y2-y1),2)+Math.pow((z2-z1),2))* Math.sqrt(Math.pow((x3-x1),2)+ Math.pow((y3-y1),2)+Math.pow((z3-z1),2)) ; let angle = Math.acos(num / den)*(180.0/3.141592653589793238463) ; return angle ;} // Driver codelet x1 = -1;let y1 = 3;let z1 = 2;let x2 = 2;let y2 = 3;let z2 = 5;let x3 = 3;let y3 = 5;let z3 = -2;let angle_A = angle_triangle(x1, x2, x3, y1, y2, y3, z1, z2, z3);let angle_B = angle_triangle(x2, x3, x1, y2, y3, y1, z2, z3, z1);let angle_C = angle_triangle(x3, x2, x1, y3, y2, y1, z3, z2, z1);document.write("Angles are :<br>");document.write("angle A = "+angle_A+" degree<br>");document.write("angle B = "+angle_B.toFixed(3)+" degree<br>");document.write("angle C = "+angle_C.toFixed(3)+" degree<br>"); // This code is contributed by rag2127</script> Angles are : angle A = 90.0 degree angle B = 54.736 degree angle C = 35.264 degree SURENDRA_GANGWAR Mithun Kumar 29AjayKumar rag2127 Geometric Mathematical Python Programs Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum Manhattan distance between a distinct pair from N coordinates Area of the largest rectangle possible from given coordinates Total area of two overlapping rectangles Equation of circle when three points on the circle are given Maximum distance between two points in coordinate plane using Rotating Caliper's Method Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jul, 2021" }, { "code": null, "e": 225, "s": 28, "text": "Given coordinates of 3 vertices of a triangle in 3D i.e. A(x1, y1, z1), B(x2, y2, z2), C(x3, y3, z3). The task is to find out all the angles of the triangle formed by above coordinates.Examples: " }, { "code": null, "e": 386, "s": 225, "text": "Input: \nx1 = -1, y1 = 3, z1 = 2\nx2 = 2, y2 = 3, z2 = 5\nx3 = 3, y3 = 5, z3 = -2\n\nOutput:\nangle A = 90.0 degree\nangle B = 54.736 degree\nangle C = 35.264 degree" }, { "code": null, "e": 946, "s": 390, "text": "Approach: For finding angle A find out direction ratios of AB and AC : direction ratios of AB = x2-x1, y2-y1, z2-z1 direction ratios of AC = x3-x1, y3-y1, z3-z1 then angle A = For finding angle B find out direction ratios of BA and BC : direction ratios of BA = x1-x2, y1-y2, z1-z2 direction ratios of BC = x3-x2, y3-y2, z3-z2 then angle B = For finding angle C find out direction ratios of CB and CA : direction ratios of CB = x2-x3, y2-y3, z2-z3 direction ratios of CA = x1-x3, y1-y3, z1-z3 then angle C = Below is the implementation of above approach: " }, { "code": null, "e": 950, "s": 946, "text": "C++" }, { "code": null, "e": 955, "s": 950, "text": "Java" }, { "code": null, "e": 963, "s": 955, "text": "Python3" }, { "code": null, "e": 966, "s": 963, "text": "C#" }, { "code": null, "e": 970, "s": 966, "text": "PHP" }, { "code": null, "e": 981, "s": 970, "text": "Javascript" }, { "code": "//CPP program for finding all angles of a triangle#include<bits/stdc++.h>#include<cmath>using namespace std; // function for finding the anglefloat angle_triangle(int x1, int x2, int x3, int y1, int y2, int y3, int z1, int z2, int z3){ int num = (x2-x1)*(x3-x1)+(y2-y1)*(y3-y1)+(z2-z1)*(z3-z1) ; float den = sqrt(pow((x2-x1),2)+pow((y2-y1),2)+pow((z2-z1),2))*\\ sqrt(pow((x3-x1),2)+pow((y3-y1),2)+pow((z3-z1),2)) ; float angle = acos(num / den)*(180.0/3.141592653589793238463) ; return angle ;} // Driver codeint main(){int x1 = -1;int y1 = 3;int z1 = 2;int x2 = 2;int y2 = 3;int z2 = 5;int x3 = 3;int y3 = 5;int z3 = -2;float angle_A = angle_triangle(x1, x2, x3, y1, y2, y3, z1, z2, z3);float angle_B = angle_triangle(x2, x3, x1, y2, y3, y1, z2, z3, z1);float angle_C = angle_triangle(x3, x2, x1, y3, y2, y1, z3, z2, z1);cout<<\"Angles are :\"<<endl;cout<<setprecision(3);cout<<\"angle A = \"<<angle_A<<\" degree\"<<endl;cout<<\"angle B = \"<<angle_B<<\" degree\"<<endl;cout<<\"angle C = \"<<angle_C<< \" degree\"<<endl;}", "e": 2120, "s": 981, "text": null }, { "code": "//Java program for finding all angles of a triangle class GFG{// function for finding the anglestatic double angle_triangle(int x1, int x2, int x3, int y1, int y2, int y3, int z1, int z2, int z3){ int num = (x2-x1)*(x3-x1)+(y2-y1)*(y3-y1)+(z2-z1)*(z3-z1) ; double den = Math.sqrt(Math.pow((x2-x1),2)+ Math.pow((y2-y1),2)+Math.pow((z2-z1),2))* Math.sqrt(Math.pow((x3-x1),2)+ Math.pow((y3-y1),2)+Math.pow((z3-z1),2)) ; double angle = Math.acos(num / den)*(180.0/3.141592653589793238463) ; return angle ;} // Driver codepublic static void main(String[] args){int x1 = -1;int y1 = 3;int z1 = 2;int x2 = 2;int y2 = 3;int z2 = 5;int x3 = 3;int y3 = 5;int z3 = -2;double angle_A = angle_triangle(x1, x2, x3, y1, y2, y3, z1, z2, z3);double angle_B = angle_triangle(x2, x3, x1, y2, y3, y1, z2, z3, z1);double angle_C = angle_triangle(x3, x2, x1, y3, y2, y1, z3, z2, z1);System.out.println(\"Angles are :\");System.out.println(\"angle A = \"+angle_A+\" degree\");System.out.println(\"angle B = \"+angle_B+\" degree\");System.out.println(\"angle C = \"+angle_C+\" degree\");}}// This code is contributed by mits", "e": 3360, "s": 2120, "text": null }, { "code": "# Python Code for finding all angles of a triangleimport math # function for finding the angledef angle_triangle(x1, x2, x3, y1, y2, y3, z1, z2, z3): num = (x2-x1)*(x3-x1)+(y2-y1)*(y3-y1)+(z2-z1)*(z3-z1) den = math.sqrt((x2-x1)**2+(y2-y1)**2+(z2-z1)**2)*\\ math.sqrt((x3-x1)**2+(y3-y1)**2+(z3-z1)**2) angle = math.degrees(math.acos(num / den)) return round(angle, 3) # driver code x1 = -1y1 = 3z1 = 2x2 = 2y2 = 3z2 = 5x3 = 3y3 = 5z3 = -2angle_A = angle_triangle(x1, x2, x3, y1, y2, y3, z1, z2, z3)angle_B = angle_triangle(x2, x3, x1, y2, y3, y1, z2, z3, z1)angle_C = angle_triangle(x3, x2, x1, y3, y2, y1, z3, z2, z1)print(\"Angles are :\")print(\"angle A = \", angle_A, \"degree\")print(\"angle B = \", angle_B, \"degree\")print(\"angle C = \", angle_C, \"degree\")", "e": 4146, "s": 3360, "text": null }, { "code": "// C# program for finding all// angles of a triangleusing System; class GFG{ // function for finding the anglestatic double angle_triangle(int x1, int x2, int x3, int y1, int y2, int y3, int z1, int z2, int z3){ int num = (x2 - x1) * (x3 - x1) + (y2 - y1) * (y3 - y1) + (z2 - z1) * (z3 - z1); double den = Math.Sqrt(Math.Pow((x2 - x1), 2) + Math.Pow((y2 - y1), 2) + Math.Pow((z2 - z1), 2)) * Math.Sqrt(Math.Pow((x3 - x1), 2) + Math.Pow((y3 - y1), 2) + Math.Pow((z3 - z1), 2)); double angle = Math.Acos(num / den) * (180.0/3.141592653589793238463); return angle ;} // Driver codepublic static void Main(){ int x1 = -1, y1 = 3, z1 = 2; int x2 = 2, y2 = 3, z2 = 5; int x3 = 3, y3 = 5, z3 = -2; double angle_A = angle_triangle(x1, x2, x3, y1, y2, y3, z1, z2, z3); double angle_B = angle_triangle(x2, x3, x1, y2, y3, y1, z2, z3, z1); double angle_C = angle_triangle(x3, x2, x1, y3, y2, y1, z3, z2, z1); Console.WriteLine(\"Angles are :\"); Console.WriteLine(\"angle A = \" + angle_A + \" degree\"); Console.WriteLine(\"angle B = \" + angle_B + \" degree\"); Console.WriteLine(\"angle C = \" + angle_C + \" degree\");}} // This code is contributed by 29AjayKumar", "e": 5891, "s": 4146, "text": null }, { "code": "<?php// PHP program for finding all// angles of a triangle // function for finding the anglefunction angle_triangle($x1, $x2, $x3, $y1, $y2, $y3, $z1, $z2, $z3){ $num = ($x2 - $x1) * ($x3 - $x1) + ($y2 - $y1) * ($y3 - $y1) + ($z2 - $z1) * ($z3 - $z1); $den = sqrt(pow(($x2 - $x1), 2) + pow(($y2 - $y1), 2) + pow(($z2 - $z1), 2)) * sqrt(pow(($x3 - $x1), 2) + pow(($y3 - $y1), 2) + pow(($z3 - $z1), 2)); $angle = acos($num / $den) * (180.0 / 3.141592653589793238463); return $angle ;} // Driver code$x1 = -1; $y1 = 3; $z1 = 2;$x2 = 2; $y2 = 3; $z2 = 5;$x3 = 3; $y3 = 5; $z3 = -2;$angle_A = angle_triangle($x1, $x2, $x3, $y1, $y2, $y3, $z1, $z2, $z3);$angle_B = angle_triangle($x2, $x3, $x1, $y2, $y3, $y1, $z2, $z3, $z1);$angle_C = angle_triangle($x3, $x2, $x1, $y3, $y2, $y1, $z3, $z2, $z1);echo \"Angles are :\\n\";echo \"angle A = \" . round($angle_A, 3) . \" degree\\n\";echo \"angle B = \" . round($angle_B, 3) . \" degree\\n\";echo \"angle C = \" . round($angle_C, 3) . \" degree\\n\"; // This code is contributed by mits?>", "e": 7144, "s": 5891, "text": null }, { "code": "<script>//Javascript program for finding all angles of a triangle // function for finding the anglefunction angle_triangle(x1,x2,x3,y1,y2,y3,z1,z2,z3){ let num = (x2-x1)*(x3-x1)+(y2-y1)*(y3-y1)+(z2-z1)*(z3-z1) ; let den = Math.sqrt(Math.pow((x2-x1),2)+ Math.pow((y2-y1),2)+Math.pow((z2-z1),2))* Math.sqrt(Math.pow((x3-x1),2)+ Math.pow((y3-y1),2)+Math.pow((z3-z1),2)) ; let angle = Math.acos(num / den)*(180.0/3.141592653589793238463) ; return angle ;} // Driver codelet x1 = -1;let y1 = 3;let z1 = 2;let x2 = 2;let y2 = 3;let z2 = 5;let x3 = 3;let y3 = 5;let z3 = -2;let angle_A = angle_triangle(x1, x2, x3, y1, y2, y3, z1, z2, z3);let angle_B = angle_triangle(x2, x3, x1, y2, y3, y1, z2, z3, z1);let angle_C = angle_triangle(x3, x2, x1, y3, y2, y1, z3, z2, z1);document.write(\"Angles are :<br>\");document.write(\"angle A = \"+angle_A+\" degree<br>\");document.write(\"angle B = \"+angle_B.toFixed(3)+\" degree<br>\");document.write(\"angle C = \"+angle_C.toFixed(3)+\" degree<br>\"); // This code is contributed by rag2127</script>", "e": 8312, "s": 7144, "text": null }, { "code": null, "e": 8398, "s": 8312, "text": "Angles are :\nangle A = 90.0 degree\nangle B = 54.736 degree\nangle C = 35.264 degree" }, { "code": null, "e": 8417, "s": 8400, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 8430, "s": 8417, "text": "Mithun Kumar" }, { "code": null, "e": 8442, "s": 8430, "text": "29AjayKumar" }, { "code": null, "e": 8450, "s": 8442, "text": "rag2127" }, { "code": null, "e": 8460, "s": 8450, "text": "Geometric" }, { "code": null, "e": 8473, "s": 8460, "text": "Mathematical" }, { "code": null, "e": 8489, "s": 8473, "text": "Python Programs" }, { "code": null, "e": 8502, "s": 8489, "text": "Mathematical" }, { "code": null, "e": 8512, "s": 8502, "text": "Geometric" }, { "code": null, "e": 8610, "s": 8512, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8680, "s": 8610, "text": "Maximum Manhattan distance between a distinct pair from N coordinates" }, { "code": null, "e": 8742, "s": 8680, "text": "Area of the largest rectangle possible from given coordinates" }, { "code": null, "e": 8783, "s": 8742, "text": "Total area of two overlapping rectangles" }, { "code": null, "e": 8844, "s": 8783, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 8932, "s": 8844, "text": "Maximum distance between two points in coordinate plane using Rotating Caliper's Method" }, { "code": null, "e": 8962, "s": 8932, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 9005, "s": 8962, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 9065, "s": 9005, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 9080, "s": 9065, "text": "C++ Data Types" } ]
SHA3 in Python
14 Sep, 2021 A cryptographic hash function is an exceptional class of hash function that has certain properties that make it appropriate for use in cryptography. It is a numerical algorithm that maps information of self-assertive size to a piece line of a fixed size (a hash function) which is intended to likewise be a one-way output function, that is, a function which is infeasible to revert. To calculate the cryptographic hash value in Python, “hashlib” Module is used. The hashlib gives the following cryptographic hash functions to discover the hash output of a text as follows: sha3_224 – 28 bit Digest-Size sha3_256 – 32 bit Digest-Size sha3_384 – 48 bit Digest-Size sha3_512 – 64 bit Digest-Size This module actualizes a typical interface to various secure hash and message digest calculations. Included are the FIPS secure hash calculations SHA1, SHA224, SHA256, SHA384, and SHA512 just as RSA’s MD5 calculation (characterized in Internet RFC 1321). Earlier calculations were called message digests, but today it is secure hash. Python has a bountiful help for hash code calculations through the library module hashlib. You can utilize the “hashlib.algorithms_available” to get the rundown of all accessible hash calculations in your variant of Python. Hashlib provides the following constant attributes: “hashlib.algorithms_guaranteed” – A set which contains all the hashing algorithms which are guaranteed to be supported by this module on all platforms. “hashlib.algorithms_available” – A set that contains all the names of the hashing algorithms that are currently available in the interpreter. Python3 import hashlib print(hashlib.algorithms_guaranteed)print(hashlib.algorithms_available) Output : {‘blake2b’, ‘shake_256’, ‘sha512’, ‘sha3_224’, ‘sha384’, ‘sha3_512’, ‘sha3_256’, ‘sha3_384’, ‘md5’, ‘sha256’, ‘sha224’, ‘sha1’, ‘blake2s’, ‘shake_128’} {‘SHA512’, ‘md5’, ‘blake2s’, ‘sha512’, ‘DSA-SHA’, ‘whirlpool’, ‘sha224’, ‘sha3_256’, ‘DSA’, ‘blake2b’, ‘MD5’, ‘SHA256’, ‘ecdsa-with-SHA1’, ‘dsaWithSHA’, ‘sha384’, ‘md4’, ‘sha3_384’, ‘MD4’, ‘sha3_512’, ‘sha256’, ‘RIPEMD160’, ‘ripemd160’, ‘shake_256’, ‘SHA’, ‘sha3_224’, ‘dsaEncryption’, ‘SHA224’, ‘sha’, ‘SHA1’, ‘sha1’, ‘shake_128’, ‘SHA384’} hash.digest_size: The size of the subsequent hash in bytes. hash.block_size: The inside square size of the hash calculation in bytes. hash.name: The sanctioned name of this hash, consistently lowercase and always appropriate as a boundary to new() to make another hash of this sort. hash.update(data): Update the hash object with the bytes-like object. hash.digest(): Return the condensation of the information went to the update() method up until now. This is a bytes object of size digest_size and can contain bytes ranging in number from 0 to 255. hash.hexdigest(): Like digest() aside from the digest is returned as a string object of twofold length, containing just hexadecimal digits. hash.copy(): Return a duplicate (“clone”) of the hash object. This can be utilized to effectively figure the overviews of information sharing a typical beginning sub-string. shake.digest(length): Returns the condensation of the information passed to the update() function . This is a bytes object of size which may contain bytes in the entire range from 0 to 255. shake.hexdigest(length): Like overview() aside from the condensation is returned as a string object of twofold length, containing just hexadecimal digits. The Secure Hash Algorithms are a group of cryptographic hash functions proposed by the National Institute of Standards and Technology (NIST) and include: SHA-0: A word applied to the first form of the 160-bit hash function produced in 1993 under the name “SHA”. It was pulled back soon after production because of an undisclosed “noteworthy blemish” and supplanted by the marginally overhauled variant SHA-1. SHA-1: A 160-bit hash function which looks like the prior MD5. This was planned by the National Security Agency (NSA) to be essential for the Digital Signature Algorithm. Cryptographic shortcomings were found in SHA-1, and the standard was not, at this point endorsed for most cryptographic uses after 2010. SHA-2: A group of two comparative hash functions, with various block sizes, known as SHA-256 and SHA-512, they contrast in the word size; SHA-256 utilizations are of 32-byte words where SHA-512’s are of 64-byte words. SHA-3: A hash function, once in the past called Keccak, picked in 2012 after a public rivalry among non-NSA originators. It underpins similar hash lengths as SHA-2, and its inside structure varies altogether from the remainder of the SHA family. Secure Hash Algorithm-3 additionally called Keccak, is a unidirectional method for creating computerized prints of the given length according to the standards as 224, 256, 384, or 512 pieces from input information of any size, created by a gathering of creators drove by Yoan Dimen in 2008 and embraced in 2015 as the new FIPS standard. The calculation works by methods for the blending capacity in with compression to the chose size “cryptographic sponge”. Examples: Input: HelloWorld Output[sha3_224]: c4797897c58a0640df9c4e9a8f30570364d9ed8450c78ed155278ac0 Input: HelloWorldOutput[sha3_256]: 92dad9443e4dd6d70a7f11872101ebff87e21798e4fbb26fa4bf590eb440e71bInput: HelloWorld Output[sha3_384]: dc6104dc2caff3ce2ccecbc927463fc3241c8531901449f1b1f4787394c9b3aa55a9e201d0bb0b1b7d7f8892bc127216 Input: HelloWorld Output[sha3_512]: 938315ec7b0e0bcac648ae6f732f67e00f9c6caa3991627953434a0769b0bbb15474a429177013ed8a7e48990887d1e19533687ed2183fd2b6054c2e8828ca1c The following programs show the implementation of SHA-3 hash in Python-3.8 using different methods: Implementation of sha3_224 using the update method Python3 import sysimport hashlib if sys.version_info < (3, 6): import sha3 # initiating the "s" object to use the# sha3_224 algorithm from the hashlib module.s = hashlib.sha3_224() # will output the name of the hashing algorithm currently in use.print(s.name) # will output the Digest-Size of the hashing algorithm being used.print(s.digest_size) # providing the input to the hashing algorithm.s.update(b"GeeksforGeeks") print(s.hexdigest()) sha3_224 28 11c044e8080ed87b3cf0643bc5880a38ae62dd4562390700000b1191 Implementation of sha3_256 using encode method Python3 # import the library moduleimport sysimport hashlib if sys.version_info < (3, 6): import sha3 # initialize a stringstr = "GeeksforGeeks" # encode the stringencoded_str = str.encode() # create sha3-256 hash objectsobj_sha3_256 = hashlib.sha3_256(encoded_str) # print in hexadecimalprint("\nSHA3-256 Hash: ", obj_sha3_256.hexdigest()) Output: SHA3-256 Hash: b05a48e99c60983b96b5a69efad8bb44e586702d484d43e592ab639ef64641ff Implementation of sha3_384 Python3 # import the library moduleimport sysimport hashlib if sys.version_info < (3, 6): import sha3 # initialize a stringstr = "GeeksforGeeks" # encode the stringencoded_str = str.encode() # create sha3-384 hash objectsobj_sha3_384 = hashlib.sha3_384(encoded_str) # print in hexadecimalprint("\nSHA3-384 Hash: ", obj_sha3_384.hexdigest()) Output: SHA3-384 Hash: b92ecaaafd00472daa6d619b68010b5f66da7c090e32bd4f5a6b60899e8de3e2c859792ec07a33775cfca8d05c64f222 Implementation of sha3_512 using the new method Python3 import sysimport hashlib if sys.version_info < (3, 6): import sha3 str = "GeeksforGeeks" # create a sha3 hash objecthash_sha3_512 = hashlib.new("sha3_512", str.encode()) print("\nSHA3-512 Hash: ", hash_sha3_512.hexdigest()) Output: SHA3-512 Hash: 3706a96a8fa96b3fc5ff30cbca36ce666042e2d07762022a78a2ec82439848fc3695e83336ab71f47dddbc24b96454df2a437e343801a4e13faab89e8d0fda61 Applications of Hashing-Algorithms: Message Digest Password Verification Data Structures(Programming Languages) Compiler Operation Rabin-Karp Algorithm Linking File name and path together singghakshay cryptography python-utility Python cryptography Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python OOPs Concepts Python Classes and Objects Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python - Pandas dataframe.append() Create a directory in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Sep, 2021" }, { "code": null, "e": 437, "s": 54, "text": "A cryptographic hash function is an exceptional class of hash function that has certain properties that make it appropriate for use in cryptography. It is a numerical algorithm that maps information of self-assertive size to a piece line of a fixed size (a hash function) which is intended to likewise be a one-way output function, that is, a function which is infeasible to revert." }, { "code": null, "e": 627, "s": 437, "text": "To calculate the cryptographic hash value in Python, “hashlib” Module is used. The hashlib gives the following cryptographic hash functions to discover the hash output of a text as follows:" }, { "code": null, "e": 657, "s": 627, "text": "sha3_224 – 28 bit Digest-Size" }, { "code": null, "e": 687, "s": 657, "text": "sha3_256 – 32 bit Digest-Size" }, { "code": null, "e": 717, "s": 687, "text": "sha3_384 – 48 bit Digest-Size" }, { "code": null, "e": 747, "s": 717, "text": "sha3_512 – 64 bit Digest-Size" }, { "code": null, "e": 1081, "s": 747, "text": "This module actualizes a typical interface to various secure hash and message digest calculations. Included are the FIPS secure hash calculations SHA1, SHA224, SHA256, SHA384, and SHA512 just as RSA’s MD5 calculation (characterized in Internet RFC 1321). Earlier calculations were called message digests, but today it is secure hash." }, { "code": null, "e": 1305, "s": 1081, "text": "Python has a bountiful help for hash code calculations through the library module hashlib. You can utilize the “hashlib.algorithms_available” to get the rundown of all accessible hash calculations in your variant of Python." }, { "code": null, "e": 1357, "s": 1305, "text": "Hashlib provides the following constant attributes:" }, { "code": null, "e": 1509, "s": 1357, "text": "“hashlib.algorithms_guaranteed” – A set which contains all the hashing algorithms which are guaranteed to be supported by this module on all platforms." }, { "code": null, "e": 1652, "s": 1509, "text": "“hashlib.algorithms_available” – A set that contains all the names of the hashing algorithms that are currently available in the interpreter." }, { "code": null, "e": 1660, "s": 1652, "text": "Python3" }, { "code": "import hashlib print(hashlib.algorithms_guaranteed)print(hashlib.algorithms_available)", "e": 1747, "s": 1660, "text": null }, { "code": null, "e": 1756, "s": 1747, "text": "Output :" }, { "code": null, "e": 1909, "s": 1756, "text": "{‘blake2b’, ‘shake_256’, ‘sha512’, ‘sha3_224’, ‘sha384’, ‘sha3_512’, ‘sha3_256’, ‘sha3_384’, ‘md5’, ‘sha256’, ‘sha224’, ‘sha1’, ‘blake2s’, ‘shake_128’} " }, { "code": null, "e": 2251, "s": 1909, "text": "{‘SHA512’, ‘md5’, ‘blake2s’, ‘sha512’, ‘DSA-SHA’, ‘whirlpool’, ‘sha224’, ‘sha3_256’, ‘DSA’, ‘blake2b’, ‘MD5’, ‘SHA256’, ‘ecdsa-with-SHA1’, ‘dsaWithSHA’, ‘sha384’, ‘md4’, ‘sha3_384’, ‘MD4’, ‘sha3_512’, ‘sha256’, ‘RIPEMD160’, ‘ripemd160’, ‘shake_256’, ‘SHA’, ‘sha3_224’, ‘dsaEncryption’, ‘SHA224’, ‘sha’, ‘SHA1’, ‘sha1’, ‘shake_128’, ‘SHA384’}" }, { "code": null, "e": 2311, "s": 2251, "text": "hash.digest_size: The size of the subsequent hash in bytes." }, { "code": null, "e": 2385, "s": 2311, "text": "hash.block_size: The inside square size of the hash calculation in bytes." }, { "code": null, "e": 2534, "s": 2385, "text": "hash.name: The sanctioned name of this hash, consistently lowercase and always appropriate as a boundary to new() to make another hash of this sort." }, { "code": null, "e": 2604, "s": 2534, "text": "hash.update(data): Update the hash object with the bytes-like object." }, { "code": null, "e": 2802, "s": 2604, "text": "hash.digest(): Return the condensation of the information went to the update() method up until now. This is a bytes object of size digest_size and can contain bytes ranging in number from 0 to 255." }, { "code": null, "e": 2942, "s": 2802, "text": "hash.hexdigest(): Like digest() aside from the digest is returned as a string object of twofold length, containing just hexadecimal digits." }, { "code": null, "e": 3116, "s": 2942, "text": "hash.copy(): Return a duplicate (“clone”) of the hash object. This can be utilized to effectively figure the overviews of information sharing a typical beginning sub-string." }, { "code": null, "e": 3306, "s": 3116, "text": "shake.digest(length): Returns the condensation of the information passed to the update() function . This is a bytes object of size which may contain bytes in the entire range from 0 to 255." }, { "code": null, "e": 3461, "s": 3306, "text": "shake.hexdigest(length): Like overview() aside from the condensation is returned as a string object of twofold length, containing just hexadecimal digits." }, { "code": null, "e": 3615, "s": 3461, "text": "The Secure Hash Algorithms are a group of cryptographic hash functions proposed by the National Institute of Standards and Technology (NIST) and include:" }, { "code": null, "e": 3870, "s": 3615, "text": "SHA-0: A word applied to the first form of the 160-bit hash function produced in 1993 under the name “SHA”. It was pulled back soon after production because of an undisclosed “noteworthy blemish” and supplanted by the marginally overhauled variant SHA-1." }, { "code": null, "e": 4178, "s": 3870, "text": "SHA-1: A 160-bit hash function which looks like the prior MD5. This was planned by the National Security Agency (NSA) to be essential for the Digital Signature Algorithm. Cryptographic shortcomings were found in SHA-1, and the standard was not, at this point endorsed for most cryptographic uses after 2010." }, { "code": null, "e": 4396, "s": 4178, "text": "SHA-2: A group of two comparative hash functions, with various block sizes, known as SHA-256 and SHA-512, they contrast in the word size; SHA-256 utilizations are of 32-byte words where SHA-512’s are of 64-byte words." }, { "code": null, "e": 4642, "s": 4396, "text": "SHA-3: A hash function, once in the past called Keccak, picked in 2012 after a public rivalry among non-NSA originators. It underpins similar hash lengths as SHA-2, and its inside structure varies altogether from the remainder of the SHA family." }, { "code": null, "e": 5100, "s": 4642, "text": "Secure Hash Algorithm-3 additionally called Keccak, is a unidirectional method for creating computerized prints of the given length according to the standards as 224, 256, 384, or 512 pieces from input information of any size, created by a gathering of creators drove by Yoan Dimen in 2008 and embraced in 2015 as the new FIPS standard. The calculation works by methods for the blending capacity in with compression to the chose size “cryptographic sponge”." }, { "code": null, "e": 5110, "s": 5100, "text": "Examples:" }, { "code": null, "e": 5128, "s": 5110, "text": "Input: HelloWorld" }, { "code": null, "e": 5203, "s": 5128, "text": "Output[sha3_224]: c4797897c58a0640df9c4e9a8f30570364d9ed8450c78ed155278ac0" }, { "code": null, "e": 5320, "s": 5203, "text": "Input: HelloWorldOutput[sha3_256]: 92dad9443e4dd6d70a7f11872101ebff87e21798e4fbb26fa4bf590eb440e71bInput: HelloWorld" }, { "code": null, "e": 5435, "s": 5320, "text": "Output[sha3_384]: dc6104dc2caff3ce2ccecbc927463fc3241c8531901449f1b1f4787394c9b3aa55a9e201d0bb0b1b7d7f8892bc127216" }, { "code": null, "e": 5453, "s": 5435, "text": "Input: HelloWorld" }, { "code": null, "e": 5601, "s": 5453, "text": "Output[sha3_512]: 938315ec7b0e0bcac648ae6f732f67e00f9c6caa3991627953434a0769b0bbb15474a429177013ed8a7e48990887d1e19533687ed2183fd2b6054c2e8828ca1c " }, { "code": null, "e": 5752, "s": 5601, "text": "The following programs show the implementation of SHA-3 hash in Python-3.8 using different methods: Implementation of sha3_224 using the update method" }, { "code": null, "e": 5760, "s": 5752, "text": "Python3" }, { "code": "import sysimport hashlib if sys.version_info < (3, 6): import sha3 # initiating the \"s\" object to use the# sha3_224 algorithm from the hashlib module.s = hashlib.sha3_224() # will output the name of the hashing algorithm currently in use.print(s.name) # will output the Digest-Size of the hashing algorithm being used.print(s.digest_size) # providing the input to the hashing algorithm.s.update(b\"GeeksforGeeks\") print(s.hexdigest())", "e": 6197, "s": 5760, "text": null }, { "code": null, "e": 6266, "s": 6197, "text": "sha3_224\n28\n11c044e8080ed87b3cf0643bc5880a38ae62dd4562390700000b1191" }, { "code": null, "e": 6313, "s": 6266, "text": "Implementation of sha3_256 using encode method" }, { "code": null, "e": 6321, "s": 6313, "text": "Python3" }, { "code": "# import the library moduleimport sysimport hashlib if sys.version_info < (3, 6): import sha3 # initialize a stringstr = \"GeeksforGeeks\" # encode the stringencoded_str = str.encode() # create sha3-256 hash objectsobj_sha3_256 = hashlib.sha3_256(encoded_str) # print in hexadecimalprint(\"\\nSHA3-256 Hash: \", obj_sha3_256.hexdigest())", "e": 6657, "s": 6321, "text": null }, { "code": null, "e": 6665, "s": 6657, "text": "Output:" }, { "code": null, "e": 6746, "s": 6665, "text": "SHA3-256 Hash: b05a48e99c60983b96b5a69efad8bb44e586702d484d43e592ab639ef64641ff" }, { "code": null, "e": 6773, "s": 6746, "text": "Implementation of sha3_384" }, { "code": null, "e": 6781, "s": 6773, "text": "Python3" }, { "code": "# import the library moduleimport sysimport hashlib if sys.version_info < (3, 6): import sha3 # initialize a stringstr = \"GeeksforGeeks\" # encode the stringencoded_str = str.encode() # create sha3-384 hash objectsobj_sha3_384 = hashlib.sha3_384(encoded_str) # print in hexadecimalprint(\"\\nSHA3-384 Hash: \", obj_sha3_384.hexdigest())", "e": 7117, "s": 6781, "text": null }, { "code": null, "e": 7125, "s": 7117, "text": "Output:" }, { "code": null, "e": 7238, "s": 7125, "text": "SHA3-384 Hash: b92ecaaafd00472daa6d619b68010b5f66da7c090e32bd4f5a6b60899e8de3e2c859792ec07a33775cfca8d05c64f222" }, { "code": null, "e": 7286, "s": 7238, "text": "Implementation of sha3_512 using the new method" }, { "code": null, "e": 7294, "s": 7286, "text": "Python3" }, { "code": "import sysimport hashlib if sys.version_info < (3, 6): import sha3 str = \"GeeksforGeeks\" # create a sha3 hash objecthash_sha3_512 = hashlib.new(\"sha3_512\", str.encode()) print(\"\\nSHA3-512 Hash: \", hash_sha3_512.hexdigest())", "e": 7521, "s": 7294, "text": null }, { "code": null, "e": 7529, "s": 7521, "text": "Output:" }, { "code": null, "e": 7674, "s": 7529, "text": "SHA3-512 Hash: 3706a96a8fa96b3fc5ff30cbca36ce666042e2d07762022a78a2ec82439848fc3695e83336ab71f47dddbc24b96454df2a437e343801a4e13faab89e8d0fda61" }, { "code": null, "e": 7710, "s": 7674, "text": "Applications of Hashing-Algorithms:" }, { "code": null, "e": 7725, "s": 7710, "text": "Message Digest" }, { "code": null, "e": 7747, "s": 7725, "text": "Password Verification" }, { "code": null, "e": 7786, "s": 7747, "text": "Data Structures(Programming Languages)" }, { "code": null, "e": 7805, "s": 7786, "text": "Compiler Operation" }, { "code": null, "e": 7826, "s": 7805, "text": "Rabin-Karp Algorithm" }, { "code": null, "e": 7862, "s": 7826, "text": "Linking File name and path together" }, { "code": null, "e": 7875, "s": 7862, "text": "singghakshay" }, { "code": null, "e": 7888, "s": 7875, "text": "cryptography" }, { "code": null, "e": 7903, "s": 7888, "text": "python-utility" }, { "code": null, "e": 7910, "s": 7903, "text": "Python" }, { "code": null, "e": 7923, "s": 7910, "text": "cryptography" }, { "code": null, "e": 8021, "s": 7923, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8053, "s": 8021, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 8074, "s": 8053, "text": "Python OOPs Concepts" }, { "code": null, "e": 8101, "s": 8074, "text": "Python Classes and Objects" }, { "code": null, "e": 8124, "s": 8101, "text": "Introduction To PYTHON" }, { "code": null, "e": 8155, "s": 8124, "text": "Python | os.path.join() method" }, { "code": null, "e": 8211, "s": 8155, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 8253, "s": 8211, "text": "Check if element exists in list in Python" }, { "code": null, "e": 8295, "s": 8253, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 8330, "s": 8295, "text": "Python - Pandas dataframe.append()" } ]
ByteBuffer toString() method in Java with Examples
06 Aug, 2021 The toString() method of ByteBuffer class is the inbuilt method used to returns a string representing the data contained by ByteBuffer Object. A new String object is created and initialized to get the character sequence from this ByteBuffer object and then String is returned by toString(). Subsequent changes to this sequence contained by Object do not affect the contents of the String.Syntax: public abstract String toString() Return Value: This method returns the String representing the data contained by ByteBuffer Object.Below programs illustrate the ByteBuffer.toString() method:Example 1: Java // Java program to demonstrate// toString() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 5; // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb1 = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer bb1.put((byte)10); bb1.put((byte)20); // print the ByteBuffer System.out.println("Original ByteBuffer: " + Arrays.toString(bb1.array())); // Creating a shared subsequence buffer of given ByteBuffer // using toString() method String value = bb1.toString(); // print the ByteBuffer System.out.println("\nstring representation of ByteBuffer: " + value); }} Original ByteBuffer: [10, 20, 0, 0, 0] string representation of ByteBuffer: java.nio.HeapByteBuffer[pos=2 lim=5 cap=5] Example 2: Java // Java program to demonstrate// toString() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 4; // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb1 = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer bb1.put((byte)10) .put((byte)20) .put((byte)30) .put((byte)40); // print the ByteBuffer System.out.println("Original ByteBuffer: " + Arrays.toString(bb1.array())); // Creating a shared subsequence buffer of given ByteBuffer // using toString() method String value = bb1.toString(); // print the ByteBuffer System.out.println("\nstring representation of ByteBuffer: " + value); }} Original ByteBuffer: [10, 20, 30, 40] string representation of ByteBuffer: java.nio.HeapByteBuffer[pos=4 lim=4 cap=4] Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#toString– ruhelaa48 Java-ByteBuffer Java-Functions Java-NIO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Aug, 2021" }, { "code": null, "e": 425, "s": 28, "text": "The toString() method of ByteBuffer class is the inbuilt method used to returns a string representing the data contained by ByteBuffer Object. A new String object is created and initialized to get the character sequence from this ByteBuffer object and then String is returned by toString(). Subsequent changes to this sequence contained by Object do not affect the contents of the String.Syntax: " }, { "code": null, "e": 459, "s": 425, "text": "public abstract String toString()" }, { "code": null, "e": 628, "s": 459, "text": "Return Value: This method returns the String representing the data contained by ByteBuffer Object.Below programs illustrate the ByteBuffer.toString() method:Example 1: " }, { "code": null, "e": 633, "s": 628, "text": "Java" }, { "code": "// Java program to demonstrate// toString() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 5; // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb1 = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer bb1.put((byte)10); bb1.put((byte)20); // print the ByteBuffer System.out.println(\"Original ByteBuffer: \" + Arrays.toString(bb1.array())); // Creating a shared subsequence buffer of given ByteBuffer // using toString() method String value = bb1.toString(); // print the ByteBuffer System.out.println(\"\\nstring representation of ByteBuffer: \" + value); }}", "e": 1520, "s": 633, "text": null }, { "code": null, "e": 1641, "s": 1520, "text": "Original ByteBuffer: [10, 20, 0, 0, 0]\n\nstring representation of ByteBuffer: java.nio.HeapByteBuffer[pos=2 lim=5 cap=5]" }, { "code": null, "e": 1654, "s": 1643, "text": "Example 2:" }, { "code": null, "e": 1659, "s": 1654, "text": "Java" }, { "code": "// Java program to demonstrate// toString() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 4; // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb1 = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer bb1.put((byte)10) .put((byte)20) .put((byte)30) .put((byte)40); // print the ByteBuffer System.out.println(\"Original ByteBuffer: \" + Arrays.toString(bb1.array())); // Creating a shared subsequence buffer of given ByteBuffer // using toString() method String value = bb1.toString(); // print the ByteBuffer System.out.println(\"\\nstring representation of ByteBuffer: \" + value); }}", "e": 2598, "s": 1659, "text": null }, { "code": null, "e": 2718, "s": 2598, "text": "Original ByteBuffer: [10, 20, 30, 40]\n\nstring representation of ByteBuffer: java.nio.HeapByteBuffer[pos=4 lim=4 cap=4]" }, { "code": null, "e": 2809, "s": 2720, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#toString– " }, { "code": null, "e": 2819, "s": 2809, "text": "ruhelaa48" }, { "code": null, "e": 2835, "s": 2819, "text": "Java-ByteBuffer" }, { "code": null, "e": 2850, "s": 2835, "text": "Java-Functions" }, { "code": null, "e": 2867, "s": 2850, "text": "Java-NIO package" }, { "code": null, "e": 2872, "s": 2867, "text": "Java" }, { "code": null, "e": 2877, "s": 2872, "text": "Java" } ]
Python | math.ceil() function
11 Mar, 2019 In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.ceil() function returns the smallest integral value greater than the number. If number is already integer, same number is returned. Syntax: math.ceil(x) Parameter: x: This is a numeric expression. Returns: Smallest integer not less than x. Code #1: # Python code to demonstrate the working of ceil() # importing "math" for mathematical operations import math x = 33.7 # returning the ceil of 33.7print ("The ceil of 33.7 is : ", end ="") print (math.ceil(x)) The ceil of 33.7 is : 34 Code #2: # Python code to demonstrate the working of ceil() # importing "math" for mathematical operations import math # prints the ceil using ceil() method print ("math.ceil(-13.1) : ", math.ceil(-13.1))print ("math.ceil(101.96) : ", math.ceil(101.96)) math.ceil(-13.1) : -13 math.ceil(101.96) : 102 Python math-library-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": "\n11 Mar, 2019" }, { "code": null, "e": 285, "s": 28, "text": "In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.ceil() function returns the smallest integral value greater than the number. If number is already integer, same number is returned." }, { "code": null, "e": 396, "s": 285, "text": "Syntax: math.ceil(x)\n\nParameter:\nx: This is a numeric expression.\n\nReturns: Smallest integer not less than x." }, { "code": null, "e": 405, "s": 396, "text": "Code #1:" }, { "code": "# Python code to demonstrate the working of ceil() # importing \"math\" for mathematical operations import math x = 33.7 # returning the ceil of 33.7print (\"The ceil of 33.7 is : \", end =\"\") print (math.ceil(x))", "e": 625, "s": 405, "text": null }, { "code": null, "e": 651, "s": 625, "text": "The ceil of 33.7 is : 34\n" }, { "code": null, "e": 661, "s": 651, "text": " Code #2:" }, { "code": "# Python code to demonstrate the working of ceil() # importing \"math\" for mathematical operations import math # prints the ceil using ceil() method print (\"math.ceil(-13.1) : \", math.ceil(-13.1))print (\"math.ceil(101.96) : \", math.ceil(101.96))", "e": 913, "s": 661, "text": null }, { "code": null, "e": 963, "s": 913, "text": "math.ceil(-13.1) : -13\nmath.ceil(101.96) : 102\n" }, { "code": null, "e": 993, "s": 963, "text": "Python math-library-functions" }, { "code": null, "e": 1000, "s": 993, "text": "Python" } ]
Subtract 1 without arithmetic operators
24 Jun, 2022 Write a program to subtract one from a given number. The use of operators like ‘+’, ‘-‘, ‘*’, ‘/’, ‘++’, ‘–‘ ...etc are not allowed. Examples: Input: 12 Output: 11 Input: 6 Output: 5 Method 1 To subtract 1 from a number x (say 0011001000), flip all the bits after the rightmost 1 bit (we get 0011001111). Finally, flip the rightmost 1 bit also (we get 0011000111) to get the answer. C++ C Java Python3 C# PHP Javascript // C++ code to subtract// one from a given number#include <iostream>using namespace std; int subtractOne(int x){ int m = 1; // Flip all the set bits // until we find a 1 while (!(x & m)) { x = x ^ m; m <<= 1; } // Flip the rightmost 1 bit x = x ^ m; return x;} // Driver codeint main(){ cout << subtractOne(13) << endl; return 0;} // This code is contributed by noob2000 // C code to subtract// one from a given number#include <stdio.h> int subtractOne(int x){ int m = 1; // Flip all the set bits // until we find a 1 while (!(x & m)) { x = x ^ m; m <<= 1; } // flip the rightmost 1 bit x = x ^ m; return x;} /* Driver program to test above functions*/int main(){ printf("%d", subtractOne(13)); return 0;} // Java code to subtract// one from a given numberimport java.io.*; class GFG{static int subtractOne(int x){ int m = 1; // Flip all the set bits // until we find a 1 while (!((x & m) > 0)) { x = x ^ m; m <<= 1; } // flip the rightmost // 1 bit x = x ^ m; return x;} // Driver Codepublic static void main (String[] args){ System.out.println(subtractOne(13));}} // This code is contributed// by anuj_67. # Python 3 code to subtract one from# a given numberdef subtractOne(x): m = 1 # Flip all the set bits # until we find a 1 while ((x & m) == False): x = x ^ m m = m << 1 # flip the rightmost 1 bit x = x ^ m return x # Driver Codeif __name__ == '__main__': print(subtractOne(13)) # This code is contributed by# Surendra_Gangwar // C# code to subtract// one from a given numberusing System; class GFG{static int subtractOne(int x){ int m = 1; // Flip all the set bits // until we find a 1 while (!((x & m) > 0)) { x = x ^ m; m <<= 1; } // flip the rightmost // 1 bit x = x ^ m; return x;} // Driver Codepublic static void Main (){ Console.WriteLine(subtractOne(13));}} // This code is contributed// by anuj_67. <?php// PHP code to subtract// one from a given number function subtractOne($x){ $m = 1; // Flip all the set bits // until we find a 1 while (!($x & $m)) { $x = $x ^ $m; $m <<= 1; } // flip the // rightmost 1 bit $x = $x ^ $m; return $x;} // Driver Code echo subtractOne(13); // This code is contributed// by anuj_67.?> <script> // JavaScript code to subtract// one from a given number function subtractOne(x){ let m = 1; // Flip all the set bits // until we find a 1 while (!(x & m)) { x = x ^ m; m <<= 1; } // flip the rightmost 1 bit x = x ^ m; return x;} /* Driver program to test above functions*/ document.write(subtractOne(13)); // This code is contributed by Surbhi Tyagi. </script> 12 Method 2 (If + is allowed) We know that the negative number is represented in 2’s complement form on most of the architectures. We have the following lemma hold for 2’s complement representation of signed numbers.Say, x is numerical value of a number, then~x = -(x+1) [ ~ is for bitwise complement ]Adding 2x on both the sides, 2x + ~x = x – 1To obtain 2x, left shift x once. C++ C Java Python3 C# PHP Javascript #include <bits/stdc++.h>using namespace std; int subtractOne(int x) { return ((x << 1) + (~x)); } /* Driver program to test above functions*/int main(){ cout<< subtractOne(13); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) #include <stdio.h> int subtractOne(int x) { return ((x << 1) + (~x)); } /* Driver program to test above functions*/int main(){ printf("%d", subtractOne(13)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) class GFG{ static int subtractOne(int x) { return ((x << 1) + (~x)); } /* Driver code*/ public static void main(String[] args) { System.out.printf("%d", subtractOne(13)); }} // This code has been contributed by 29AjayKumar def subtractOne(x): return ((x << 1) + (~x)); # Driver codeprint(subtractOne(13)); # This code is contributed by mits using System; class GFG{ static int subtractOne(int x) { return ((x << 1) + (~x)); } /* Driver code*/ public static void Main(String[] args) { Console.Write("{0}", subtractOne(13)); }} // This code contributed by Rajput-Ji <?phpfunction subtractOne($x){ return (($x << 1) + (~$x));} /* Driver code*/ print(subtractOne(13)); // This code has been contributed by mits?> <script> function subtractOne(x){ return ((x << 1) + (~x));} /* Driver program to test above functions*/ document.write((subtractOne(13))); // This is code is contributed by Mayank Tyagi </script> 12 vt_m SURENDRA_GANGWAR 29AjayKumar Rajput-Ji Mithun Kumar surbhityagi15 mayanktyagi1709 noob2000 adityakumar129 programming-puzzle Bit Magic Mathematical Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Jun, 2022" }, { "code": null, "e": 186, "s": 52, "text": "Write a program to subtract one from a given number. The use of operators like ‘+’, ‘-‘, ‘*’, ‘/’, ‘++’, ‘–‘ ...etc are not allowed. " }, { "code": null, "e": 197, "s": 186, "text": "Examples: " }, { "code": null, "e": 240, "s": 197, "text": "Input: 12\nOutput: 11\n\nInput: 6\nOutput: 5" }, { "code": null, "e": 440, "s": 240, "text": "Method 1 To subtract 1 from a number x (say 0011001000), flip all the bits after the rightmost 1 bit (we get 0011001111). Finally, flip the rightmost 1 bit also (we get 0011000111) to get the answer." }, { "code": null, "e": 444, "s": 440, "text": "C++" }, { "code": null, "e": 446, "s": 444, "text": "C" }, { "code": null, "e": 451, "s": 446, "text": "Java" }, { "code": null, "e": 459, "s": 451, "text": "Python3" }, { "code": null, "e": 462, "s": 459, "text": "C#" }, { "code": null, "e": 466, "s": 462, "text": "PHP" }, { "code": null, "e": 477, "s": 466, "text": "Javascript" }, { "code": "// C++ code to subtract// one from a given number#include <iostream>using namespace std; int subtractOne(int x){ int m = 1; // Flip all the set bits // until we find a 1 while (!(x & m)) { x = x ^ m; m <<= 1; } // Flip the rightmost 1 bit x = x ^ m; return x;} // Driver codeint main(){ cout << subtractOne(13) << endl; return 0;} // This code is contributed by noob2000", "e": 897, "s": 477, "text": null }, { "code": "// C code to subtract// one from a given number#include <stdio.h> int subtractOne(int x){ int m = 1; // Flip all the set bits // until we find a 1 while (!(x & m)) { x = x ^ m; m <<= 1; } // flip the rightmost 1 bit x = x ^ m; return x;} /* Driver program to test above functions*/int main(){ printf(\"%d\", subtractOne(13)); return 0;}", "e": 1278, "s": 897, "text": null }, { "code": "// Java code to subtract// one from a given numberimport java.io.*; class GFG{static int subtractOne(int x){ int m = 1; // Flip all the set bits // until we find a 1 while (!((x & m) > 0)) { x = x ^ m; m <<= 1; } // flip the rightmost // 1 bit x = x ^ m; return x;} // Driver Codepublic static void main (String[] args){ System.out.println(subtractOne(13));}} // This code is contributed// by anuj_67.", "e": 1729, "s": 1278, "text": null }, { "code": "# Python 3 code to subtract one from# a given numberdef subtractOne(x): m = 1 # Flip all the set bits # until we find a 1 while ((x & m) == False): x = x ^ m m = m << 1 # flip the rightmost 1 bit x = x ^ m return x # Driver Codeif __name__ == '__main__': print(subtractOne(13)) # This code is contributed by# Surendra_Gangwar", "e": 2103, "s": 1729, "text": null }, { "code": "// C# code to subtract// one from a given numberusing System; class GFG{static int subtractOne(int x){ int m = 1; // Flip all the set bits // until we find a 1 while (!((x & m) > 0)) { x = x ^ m; m <<= 1; } // flip the rightmost // 1 bit x = x ^ m; return x;} // Driver Codepublic static void Main (){ Console.WriteLine(subtractOne(13));}} // This code is contributed// by anuj_67.", "e": 2534, "s": 2103, "text": null }, { "code": "<?php// PHP code to subtract// one from a given number function subtractOne($x){ $m = 1; // Flip all the set bits // until we find a 1 while (!($x & $m)) { $x = $x ^ $m; $m <<= 1; } // flip the // rightmost 1 bit $x = $x ^ $m; return $x;} // Driver Code echo subtractOne(13); // This code is contributed// by anuj_67.?>", "e": 2907, "s": 2534, "text": null }, { "code": "<script> // JavaScript code to subtract// one from a given number function subtractOne(x){ let m = 1; // Flip all the set bits // until we find a 1 while (!(x & m)) { x = x ^ m; m <<= 1; } // flip the rightmost 1 bit x = x ^ m; return x;} /* Driver program to test above functions*/ document.write(subtractOne(13)); // This code is contributed by Surbhi Tyagi. </script>", "e": 3323, "s": 2907, "text": null }, { "code": null, "e": 3326, "s": 3323, "text": "12" }, { "code": null, "e": 3705, "s": 3328, "text": "Method 2 (If + is allowed) We know that the negative number is represented in 2’s complement form on most of the architectures. We have the following lemma hold for 2’s complement representation of signed numbers.Say, x is numerical value of a number, then~x = -(x+1) [ ~ is for bitwise complement ]Adding 2x on both the sides, 2x + ~x = x – 1To obtain 2x, left shift x once. " }, { "code": null, "e": 3709, "s": 3705, "text": "C++" }, { "code": null, "e": 3711, "s": 3709, "text": "C" }, { "code": null, "e": 3716, "s": 3711, "text": "Java" }, { "code": null, "e": 3724, "s": 3716, "text": "Python3" }, { "code": null, "e": 3727, "s": 3724, "text": "C#" }, { "code": null, "e": 3731, "s": 3727, "text": "PHP" }, { "code": null, "e": 3742, "s": 3731, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; int subtractOne(int x) { return ((x << 1) + (~x)); } /* Driver program to test above functions*/int main(){ cout<< subtractOne(13); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 3997, "s": 3742, "text": null }, { "code": "#include <stdio.h> int subtractOne(int x) { return ((x << 1) + (~x)); } /* Driver program to test above functions*/int main(){ printf(\"%d\", subtractOne(13)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 4233, "s": 3997, "text": null }, { "code": "class GFG{ static int subtractOne(int x) { return ((x << 1) + (~x)); } /* Driver code*/ public static void main(String[] args) { System.out.printf(\"%d\", subtractOne(13)); }} // This code has been contributed by 29AjayKumar", "e": 4493, "s": 4233, "text": null }, { "code": "def subtractOne(x): return ((x << 1) + (~x)); # Driver codeprint(subtractOne(13)); # This code is contributed by mits", "e": 4615, "s": 4493, "text": null }, { "code": "using System; class GFG{ static int subtractOne(int x) { return ((x << 1) + (~x)); } /* Driver code*/ public static void Main(String[] args) { Console.Write(\"{0}\", subtractOne(13)); }} // This code contributed by Rajput-Ji", "e": 4879, "s": 4615, "text": null }, { "code": "<?phpfunction subtractOne($x){ return (($x << 1) + (~$x));} /* Driver code*/ print(subtractOne(13)); // This code has been contributed by mits?>", "e": 5027, "s": 4879, "text": null }, { "code": "<script> function subtractOne(x){ return ((x << 1) + (~x));} /* Driver program to test above functions*/ document.write((subtractOne(13))); // This is code is contributed by Mayank Tyagi </script>", "e": 5231, "s": 5027, "text": null }, { "code": null, "e": 5234, "s": 5231, "text": "12" }, { "code": null, "e": 5241, "s": 5236, "text": "vt_m" }, { "code": null, "e": 5258, "s": 5241, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 5270, "s": 5258, "text": "29AjayKumar" }, { "code": null, "e": 5280, "s": 5270, "text": "Rajput-Ji" }, { "code": null, "e": 5293, "s": 5280, "text": "Mithun Kumar" }, { "code": null, "e": 5307, "s": 5293, "text": "surbhityagi15" }, { "code": null, "e": 5323, "s": 5307, "text": "mayanktyagi1709" }, { "code": null, "e": 5332, "s": 5323, "text": "noob2000" }, { "code": null, "e": 5347, "s": 5332, "text": "adityakumar129" }, { "code": null, "e": 5366, "s": 5347, "text": "programming-puzzle" }, { "code": null, "e": 5376, "s": 5366, "text": "Bit Magic" }, { "code": null, "e": 5389, "s": 5376, "text": "Mathematical" }, { "code": null, "e": 5402, "s": 5389, "text": "Mathematical" }, { "code": null, "e": 5412, "s": 5402, "text": "Bit Magic" } ]
Python | Pandas dataframe.melt()
09 Dec, 2021 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.melt() function unpivots a DataFrame from wide format to long format, optionally leaving identifier variables set. This function is useful to message a DataFrame into a format where one or more columns are identifier variables (id_vars), while all other columns, considered measured variables (value_vars), are “unpivoted” to the row axis, leaving just two non-identifier columns, ‘variable’ and ‘value’. Syntax:DataFrame.melt(id_vars=None, value_vars=None, var_name=None, value_name=’value’, col_level=None)Parameters :frame : DataFrameid_vars : Column(s) to use as identifier variablesvalue_vars : Column(s) to unpivot. If not specified, uses all columns that are not set as id_vars.var_name : Name to use for the ‘variable’ column. If None it uses frame.columns.name or ‘variable’.value_name : Name to use for the ‘value’ columncol_level : If columns are a MultiIndex then use this level to melt. Returns: DataFrame into a format where one or more columns are identifier variables Example #1: Use melt() function to set column “A” as the identifier variable and column “B” as value variable. Python3 # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[12, 4, 5, 44, 1], "B":[5, 2, 54, 3, 2], "C":[20, 16, 7, 3, 8], "D":[14, 3, 17, 2, 6]}) # Print the dataframedf Lets use the dataframe.melt() function to set column “A” as identifier variable and column “B” as the value variable. Python3 # function to unpivot the dataframedf.melt(id_vars =['A'], value_vars =['B']) Output : Example #2: Use melt() function to set column “A” as the identifier variable and column “B” and “C” as value variable. Also customize the names of both the value and variable column. Python3 # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[12, 4, 5, 44, 1], "B":[5, 2, 54, 3, 2], "C":[20, 16, 7, 3, 8], "D":[14, 3, 17, 2, 6]}) # Print the dataframedf Lets use the dataframe.melt() function to set column “A” as identifier variable and column “B” and “C” as the value variable. Python3 # function to unpivot the dataframe# We will also provide a customized name to the value and variable column df.melt(id_vars =['A'], value_vars =['B', 'C'], var_name ='Variable_column', value_name ='Value_column') Output : surindertarika1234 Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Dec, 2021" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 664, "s": 242, "text": "Pandas dataframe.melt() function unpivots a DataFrame from wide format to long format, optionally leaving identifier variables set. This function is useful to message a DataFrame into a format where one or more columns are identifier variables (id_vars), while all other columns, considered measured variables (value_vars), are “unpivoted” to the row axis, leaving just two non-identifier columns, ‘variable’ and ‘value’." }, { "code": null, "e": 1159, "s": 664, "text": "Syntax:DataFrame.melt(id_vars=None, value_vars=None, var_name=None, value_name=’value’, col_level=None)Parameters :frame : DataFrameid_vars : Column(s) to use as identifier variablesvalue_vars : Column(s) to unpivot. If not specified, uses all columns that are not set as id_vars.var_name : Name to use for the ‘variable’ column. If None it uses frame.columns.name or ‘variable’.value_name : Name to use for the ‘value’ columncol_level : If columns are a MultiIndex then use this level to melt." }, { "code": null, "e": 1243, "s": 1159, "text": "Returns: DataFrame into a format where one or more columns are identifier variables" }, { "code": null, "e": 1354, "s": 1243, "text": "Example #1: Use melt() function to set column “A” as the identifier variable and column “B” as value variable." }, { "code": null, "e": 1362, "s": 1354, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[12, 4, 5, 44, 1], \"B\":[5, 2, 54, 3, 2], \"C\":[20, 16, 7, 3, 8], \"D\":[14, 3, 17, 2, 6]}) # Print the dataframedf", "e": 1625, "s": 1362, "text": null }, { "code": null, "e": 1743, "s": 1625, "text": "Lets use the dataframe.melt() function to set column “A” as identifier variable and column “B” as the value variable." }, { "code": null, "e": 1751, "s": 1743, "text": "Python3" }, { "code": "# function to unpivot the dataframedf.melt(id_vars =['A'], value_vars =['B'])", "e": 1829, "s": 1751, "text": null }, { "code": null, "e": 2021, "s": 1829, "text": "Output : Example #2: Use melt() function to set column “A” as the identifier variable and column “B” and “C” as value variable. Also customize the names of both the value and variable column." }, { "code": null, "e": 2029, "s": 2021, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[12, 4, 5, 44, 1], \"B\":[5, 2, 54, 3, 2], \"C\":[20, 16, 7, 3, 8], \"D\":[14, 3, 17, 2, 6]}) # Print the dataframedf", "e": 2291, "s": 2029, "text": null }, { "code": null, "e": 2417, "s": 2291, "text": "Lets use the dataframe.melt() function to set column “A” as identifier variable and column “B” and “C” as the value variable." }, { "code": null, "e": 2425, "s": 2417, "text": "Python3" }, { "code": "# function to unpivot the dataframe# We will also provide a customized name to the value and variable column df.melt(id_vars =['A'], value_vars =['B', 'C'], var_name ='Variable_column', value_name ='Value_column')", "e": 2648, "s": 2425, "text": null }, { "code": null, "e": 2657, "s": 2648, "text": "Output :" }, { "code": null, "e": 2676, "s": 2657, "text": "surindertarika1234" }, { "code": null, "e": 2700, "s": 2676, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2732, "s": 2700, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 2746, "s": 2732, "text": "Python-pandas" }, { "code": null, "e": 2753, "s": 2746, "text": "Python" } ]
Text Detection and Extraction using OpenCV and OCR
16 Sep, 2021 OpenCV (Open source computer vision) is a library of programming functions mainly aimed at real-time computer vision. OpenCV in python helps to process an image and apply various functions like resizing image, pixel manipulations, object detection, etc. In this article, we will learn how to use contours to detect the text in an image and save it to a text file.Required Installations: pip install opencv-python pip install pytesseract OpenCV package is used to read an image and perform certain image processing techniques. Python-tesseract is a wrapper for Google’s Tesseract-OCR Engine which is used to recognize text from images.Download the tesseract executable file from this link.Approach: After the necessary imports, a sample image is read using the imread function of opencv. The colorspace of the image is first changed and stored in a variable. For color conversion we use the function cv2.cvtColor(input_image, flag). The second parameter flag determines the type of conversion. We can chose among cv2.COLOR_BGR2GRAY and cv2.COLOR_BGR2HSV. cv2.COLOR_BGR2GRAY helps us to convert an RGB image to gray scale image and cv2.COLOR_BGR2HSV is used to convert an RGB image to HSV (Hue, Saturation, Value) color-space image. Here, we use cv2.COLOR_BGR2GRAY. A threshold is applied to the converted image using cv2.threshold function. There are 3 types of thresholding: Simple ThresholdingAdaptive ThresholdingOtsu’s Binarization Simple Thresholding Adaptive Thresholding Otsu’s Binarization For more information on thresholding, refer Thresholding techniques using OpenCV.cv2.threshold() has 4 parameters, first parameter being the color-space changed image, followed by the minimum threshold value, the maximum threshold value and the type of thresholding that needs to be applied. cv2.getStructuringElement() is used to define a structural element like elliptical, circular, rectangular etc. Here, we use the rectangular structural element (cv2.MORPH_RECT). cv2.getStructuringElement takes an extra size of the kernel parameter. A bigger kernel would make group larger blocks of texts together. After choosing the correct kernel, dilation is applied to the image with cv2.dilate function. Dilation makes the groups of text to be detected more accurately since it dilates (expands) a text block. cv2.findContours() is used to find contours in the dilated image. There are three arguments in cv.findContours(): the source image, the contour retrieval mode and the contour approximation method. This function returns contours and hierarchy. Contours is a python list of all the contours in the image. Each contour is a Numpy array of (x, y) coordinates of boundary points in the object. Contours are typically used to find a white object from a black background. All the above image processing techniques are applied so that the Contours can detect the boundary edges of the blocks of text of the image. A text file is opened in write mode and flushed. This text file is opened to save the text from the output of the OCR. Loop through each contour and take the x and y coordinates and the width and height using the function cv2.boundingRect(). Then draw a rectangle in the image using the function cv2.rectangle() with the help of obtained x and y coordinates and the width and height. There are 5 parameters in the cv2.rectangle(), the first parameter specifies the input image, followed by the x and y coordinates (starting coordinates of the rectangle), the ending coordinates of the rectangle which is (x+w, y+h), the boundary color for the rectangle in RGB value and the size of the boundary. Now crop the rectangular region and then pass it to the tesseract to extract the text from the image. Then we open the created text file in append mode to append the obtained text and close the file.Sample image used for the code: Python3 # Import required packagesimport cv2import pytesseract # Mention the installed location of Tesseract-OCR in your systempytesseract.pytesseract.tesseract_cmd = 'System_path_to_tesseract.exe' # Read image from which text needs to be extractedimg = cv2.imread("sample.jpg") # Preprocessing the image starts # Convert the image to gray scalegray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Performing OTSU thresholdret, thresh1 = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU | cv2.THRESH_BINARY_INV) # Specify structure shape and kernel size.# Kernel size increases or decreases the area# of the rectangle to be detected.# A smaller value like (10, 10) will detect# each word instead of a sentence.rect_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (18, 18)) # Applying dilation on the threshold imagedilation = cv2.dilate(thresh1, rect_kernel, iterations = 1) # Finding contourscontours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # Creating a copy of imageim2 = img.copy() # A text file is created and flushedfile = open("recognized.txt", "w+")file.write("")file.close() # Looping through the identified contours# Then rectangular part is cropped and passed on# to pytesseract for extracting text from it# Extracted text is then written into the text filefor cnt in contours: x, y, w, h = cv2.boundingRect(cnt) # Drawing a rectangle on copied image rect = cv2.rectangle(im2, (x, y), (x + w, y + h), (0, 255, 0), 2) # Cropping the text block for giving input to OCR cropped = im2[y:y + h, x:x + w] # Open the file in append mode file = open("recognized.txt", "a") # Apply OCR on the cropped image text = pytesseract.image_to_string(cropped) # Appending the text into file file.write(text) file.write("\n") # Close the file file.close Output: Final text file: Blocks of text detected: surindertarika1234 Image-Processing OpenCV Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Sep, 2021" }, { "code": null, "e": 440, "s": 52, "text": "OpenCV (Open source computer vision) is a library of programming functions mainly aimed at real-time computer vision. OpenCV in python helps to process an image and apply various functions like resizing image, pixel manipulations, object detection, etc. In this article, we will learn how to use contours to detect the text in an image and save it to a text file.Required Installations: " }, { "code": null, "e": 490, "s": 440, "text": "pip install opencv-python\npip install pytesseract" }, { "code": null, "e": 841, "s": 490, "text": "OpenCV package is used to read an image and perform certain image processing techniques. Python-tesseract is a wrapper for Google’s Tesseract-OCR Engine which is used to recognize text from images.Download the tesseract executable file from this link.Approach: After the necessary imports, a sample image is read using the imread function of opencv. " }, { "code": null, "e": 1431, "s": 841, "text": "The colorspace of the image is first changed and stored in a variable. For color conversion we use the function cv2.cvtColor(input_image, flag). The second parameter flag determines the type of conversion. We can chose among cv2.COLOR_BGR2GRAY and cv2.COLOR_BGR2HSV. cv2.COLOR_BGR2GRAY helps us to convert an RGB image to gray scale image and cv2.COLOR_BGR2HSV is used to convert an RGB image to HSV (Hue, Saturation, Value) color-space image. Here, we use cv2.COLOR_BGR2GRAY. A threshold is applied to the converted image using cv2.threshold function. There are 3 types of thresholding: " }, { "code": null, "e": 1491, "s": 1431, "text": "Simple ThresholdingAdaptive ThresholdingOtsu’s Binarization" }, { "code": null, "e": 1511, "s": 1491, "text": "Simple Thresholding" }, { "code": null, "e": 1533, "s": 1511, "text": "Adaptive Thresholding" }, { "code": null, "e": 1553, "s": 1533, "text": "Otsu’s Binarization" }, { "code": null, "e": 1846, "s": 1553, "text": "For more information on thresholding, refer Thresholding techniques using OpenCV.cv2.threshold() has 4 parameters, first parameter being the color-space changed image, followed by the minimum threshold value, the maximum threshold value and the type of thresholding that needs to be applied. " }, { "code": null, "e": 2361, "s": 1846, "text": "cv2.getStructuringElement() is used to define a structural element like elliptical, circular, rectangular etc. Here, we use the rectangular structural element (cv2.MORPH_RECT). cv2.getStructuringElement takes an extra size of the kernel parameter. A bigger kernel would make group larger blocks of texts together. After choosing the correct kernel, dilation is applied to the image with cv2.dilate function. Dilation makes the groups of text to be detected more accurately since it dilates (expands) a text block. " }, { "code": null, "e": 3087, "s": 2361, "text": "cv2.findContours() is used to find contours in the dilated image. There are three arguments in cv.findContours(): the source image, the contour retrieval mode and the contour approximation method. This function returns contours and hierarchy. Contours is a python list of all the contours in the image. Each contour is a Numpy array of (x, y) coordinates of boundary points in the object. Contours are typically used to find a white object from a black background. All the above image processing techniques are applied so that the Contours can detect the boundary edges of the blocks of text of the image. A text file is opened in write mode and flushed. This text file is opened to save the text from the output of the OCR. " }, { "code": null, "e": 3897, "s": 3087, "text": "Loop through each contour and take the x and y coordinates and the width and height using the function cv2.boundingRect(). Then draw a rectangle in the image using the function cv2.rectangle() with the help of obtained x and y coordinates and the width and height. There are 5 parameters in the cv2.rectangle(), the first parameter specifies the input image, followed by the x and y coordinates (starting coordinates of the rectangle), the ending coordinates of the rectangle which is (x+w, y+h), the boundary color for the rectangle in RGB value and the size of the boundary. Now crop the rectangular region and then pass it to the tesseract to extract the text from the image. Then we open the created text file in append mode to append the obtained text and close the file.Sample image used for the code: " }, { "code": null, "e": 3907, "s": 3899, "text": "Python3" }, { "code": "# Import required packagesimport cv2import pytesseract # Mention the installed location of Tesseract-OCR in your systempytesseract.pytesseract.tesseract_cmd = 'System_path_to_tesseract.exe' # Read image from which text needs to be extractedimg = cv2.imread(\"sample.jpg\") # Preprocessing the image starts # Convert the image to gray scalegray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Performing OTSU thresholdret, thresh1 = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU | cv2.THRESH_BINARY_INV) # Specify structure shape and kernel size.# Kernel size increases or decreases the area# of the rectangle to be detected.# A smaller value like (10, 10) will detect# each word instead of a sentence.rect_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (18, 18)) # Applying dilation on the threshold imagedilation = cv2.dilate(thresh1, rect_kernel, iterations = 1) # Finding contourscontours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # Creating a copy of imageim2 = img.copy() # A text file is created and flushedfile = open(\"recognized.txt\", \"w+\")file.write(\"\")file.close() # Looping through the identified contours# Then rectangular part is cropped and passed on# to pytesseract for extracting text from it# Extracted text is then written into the text filefor cnt in contours: x, y, w, h = cv2.boundingRect(cnt) # Drawing a rectangle on copied image rect = cv2.rectangle(im2, (x, y), (x + w, y + h), (0, 255, 0), 2) # Cropping the text block for giving input to OCR cropped = im2[y:y + h, x:x + w] # Open the file in append mode file = open(\"recognized.txt\", \"a\") # Apply OCR on the cropped image text = pytesseract.image_to_string(cropped) # Appending the text into file file.write(text) file.write(\"\\n\") # Close the file file.close", "e": 5798, "s": 3907, "text": null }, { "code": null, "e": 5825, "s": 5798, "text": "Output: Final text file: " }, { "code": null, "e": 5852, "s": 5825, "text": "Blocks of text detected: " }, { "code": null, "e": 5873, "s": 5854, "text": "surindertarika1234" }, { "code": null, "e": 5890, "s": 5873, "text": "Image-Processing" }, { "code": null, "e": 5897, "s": 5890, "text": "OpenCV" }, { "code": null, "e": 5911, "s": 5897, "text": "Python-OpenCV" }, { "code": null, "e": 5918, "s": 5911, "text": "Python" } ]
Formatting Dates in Python
06 Feb, 2020 In different regions of the world, different types of date formats are used and for that reason usually, programming languages provide a number of date formats for the developed to deal with. In Python, it is dealt with by using liberty called datetime. It consists of class and methods that can be used to work with data and time values. To use it, first import datetime library by: import datetime We can have the following components in datetime: The time classTime values can be represented using the time class. The attributes for the time class include the hour, minute, second and microsecond. One Example of time is given as follows:Syntax:time(hour, minute, second, microsecond) Example:import datetime tm = datetime.time(2, 25, 50, 13)print(tm)Output02:25:50.000013 There are ranges for the time attributes i.e for seconds we have the range between 0 to 59 and for nanosecond range is between 0 to 999999. If the range exceeds, the compiler shown a ValueError.The instance of time class consists of three instance attributes namely hour, minute, second and microsecond. These are used to get specific information about the time.Example:import datetime tm = datetime.time(1, 50, 20, 133257) print('Time tm is ', tm.hour, ' hours ', tm.minute, ' minutes ', tm.second, ' seconds and ', tm.microsecond, ' microseconds' )OutputTime tm is 1 hours 50 minutes 20 seconds and 133257 microseconds Time values can be represented using the time class. The attributes for the time class include the hour, minute, second and microsecond. One Example of time is given as follows: Syntax: time(hour, minute, second, microsecond) Example: import datetime tm = datetime.time(2, 25, 50, 13)print(tm) Output 02:25:50.000013 There are ranges for the time attributes i.e for seconds we have the range between 0 to 59 and for nanosecond range is between 0 to 999999. If the range exceeds, the compiler shown a ValueError. The instance of time class consists of three instance attributes namely hour, minute, second and microsecond. These are used to get specific information about the time. Example: import datetime tm = datetime.time(1, 50, 20, 133257) print('Time tm is ', tm.hour, ' hours ', tm.minute, ' minutes ', tm.second, ' seconds and ', tm.microsecond, ' microseconds' ) Output Time tm is 1 hours 50 minutes 20 seconds and 133257 microseconds The date classThe values for the calendar date can be represented via the date class. The date instance consists of attributes for the year, month, and day.Syntax:date(yyyy, mm, dd) Example:import datetime date = datetime.date(2018, 5, 12)print('Date date is ', date.day, ' day of ', date.month, ' of the year ', date.year)OutputDate date is 12 day of 5 of the year 2018 To get the today’s date names a method called today() is used and to get all the information in one object (today’s information) ctime() method is used.Example:import datetime tday = datetime.date.today()daytoday = tday.ctime() print("The date today is ", tday)print("The date info. is ", daytoday)OutputThe date today is 2020-01-30 The date info. is Thu Jan 30 00:00:00 2020 The values for the calendar date can be represented via the date class. The date instance consists of attributes for the year, month, and day. Syntax: date(yyyy, mm, dd) Example: import datetime date = datetime.date(2018, 5, 12)print('Date date is ', date.day, ' day of ', date.month, ' of the year ', date.year) Output Date date is 12 day of 5 of the year 2018 To get the today’s date names a method called today() is used and to get all the information in one object (today’s information) ctime() method is used. Example: import datetime tday = datetime.date.today()daytoday = tday.ctime() print("The date today is ", tday)print("The date info. is ", daytoday) Output The date today is 2020-01-30 The date info. is Thu Jan 30 00:00:00 2020 Date and time are different from strings and thus many times it is important to convert the datetime to string. For this we use strftime() method. Syntax: time.strftime(format, t) Parameters: format – This is of string type. i.e. the directives can be embedded in the format string. t – the time to be formatted. Example: import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13) print(x.strftime("%b %d %Y %H:%M:%S")) Output May 12 2018 02:25:50 The same example can also be written as a different place by setting up the print() method. import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13) print(x.strftime("%H:%M:%S %b %d %Y")) Output 02:25:50 May 12 2018 %H, %M and %S displays the hour, minutes and seconds respectively. %b, %d and %Y displays 3 characters of the month, day and year respectively. Other than the above example the frequently used character code List along with its functionality are: %a: Displays three characters of the weekday, e.g. Wed.import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%a"))OutputSat import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%a")) Output Sat %A: Displays name of the weekday, e.g. Wednesday.import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%A"))OutputSaturday import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%A")) Output Saturday %B: Displays the month, e.g. May.import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%B"))OutputMay import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%B")) Output May %w: Displays the weekday as a number, from 0 to 6, with Sunday being 0.import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%w"))Output6 import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%w")) Output 6 %m: Displays month as a number, from 01 to 12.import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%m"))Output5 import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%m")) Output 5 %p: Define AM/PM for time.import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%p"))OutputPM import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%p")) Output PM %y: Displays year in two-digit format, i.e “20” in place of “2020”.import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("% y"))Output18 import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("% y")) Output 18 %f: Displays microsecond from 000000 to 999999.import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("% f"))Output000013 import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("% f")) Output 000013 %j: Displays number of the day in the year, from 001 to 366.import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%f"))Output132 import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%f")) Output 132 Conversion from string to date Conversion from string to date is many times needed while working with imported data sets from a csv or when we take inputs from website forms. To do this, python provides a method called strptime(). Syntax: datetime.strptime(string, format) Parameters: string – The input string. format – This is of string type. i.e. the directives can be embedded in the format string. Example: from datetime import datetime print(datetime.strptime('5/5/2019', '%d/%m/%Y')) Output 2019-05-05 00:00:00 Python-datetime Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Feb, 2020" }, { "code": null, "e": 367, "s": 28, "text": "In different regions of the world, different types of date formats are used and for that reason usually, programming languages provide a number of date formats for the developed to deal with. In Python, it is dealt with by using liberty called datetime. It consists of class and methods that can be used to work with data and time values." }, { "code": null, "e": 412, "s": 367, "text": "To use it, first import datetime library by:" }, { "code": null, "e": 428, "s": 412, "text": "import datetime" }, { "code": null, "e": 478, "s": 428, "text": "We can have the following components in datetime:" }, { "code": null, "e": 1452, "s": 478, "text": "The time classTime values can be represented using the time class. The attributes for the time class include the hour, minute, second and microsecond. One Example of time is given as follows:Syntax:time(hour, minute, second, microsecond)\nExample:import datetime tm = datetime.time(2, 25, 50, 13)print(tm)Output02:25:50.000013\nThere are ranges for the time attributes i.e for seconds we have the range between 0 to 59 and for nanosecond range is between 0 to 999999. If the range exceeds, the compiler shown a ValueError.The instance of time class consists of three instance attributes namely hour, minute, second and microsecond. These are used to get specific information about the time.Example:import datetime tm = datetime.time(1, 50, 20, 133257) print('Time tm is ', tm.hour, ' hours ', tm.minute, ' minutes ', tm.second, ' seconds and ', tm.microsecond, ' microseconds' )OutputTime tm is 1 hours 50 minutes 20 seconds and 133257 microseconds" }, { "code": null, "e": 1630, "s": 1452, "text": "Time values can be represented using the time class. The attributes for the time class include the hour, minute, second and microsecond. One Example of time is given as follows:" }, { "code": null, "e": 1638, "s": 1630, "text": "Syntax:" }, { "code": null, "e": 1679, "s": 1638, "text": "time(hour, minute, second, microsecond)\n" }, { "code": null, "e": 1688, "s": 1679, "text": "Example:" }, { "code": "import datetime tm = datetime.time(2, 25, 50, 13)print(tm)", "e": 1750, "s": 1688, "text": null }, { "code": null, "e": 1757, "s": 1750, "text": "Output" }, { "code": null, "e": 1774, "s": 1757, "text": "02:25:50.000013\n" }, { "code": null, "e": 1969, "s": 1774, "text": "There are ranges for the time attributes i.e for seconds we have the range between 0 to 59 and for nanosecond range is between 0 to 999999. If the range exceeds, the compiler shown a ValueError." }, { "code": null, "e": 2138, "s": 1969, "text": "The instance of time class consists of three instance attributes namely hour, minute, second and microsecond. These are used to get specific information about the time." }, { "code": null, "e": 2147, "s": 2138, "text": "Example:" }, { "code": "import datetime tm = datetime.time(1, 50, 20, 133257) print('Time tm is ', tm.hour, ' hours ', tm.minute, ' minutes ', tm.second, ' seconds and ', tm.microsecond, ' microseconds' )", "e": 2352, "s": 2147, "text": null }, { "code": null, "e": 2359, "s": 2352, "text": "Output" }, { "code": null, "e": 2424, "s": 2359, "text": "Time tm is 1 hours 50 minutes 20 seconds and 133257 microseconds" }, { "code": null, "e": 3196, "s": 2424, "text": "The date classThe values for the calendar date can be represented via the date class. The date instance consists of attributes for the year, month, and day.Syntax:date(yyyy, mm, dd)\nExample:import datetime date = datetime.date(2018, 5, 12)print('Date date is ', date.day, ' day of ', date.month, ' of the year ', date.year)OutputDate date is 12 day of 5 of the year 2018\nTo get the today’s date names a method called today() is used and to get all the information in one object (today’s information) ctime() method is used.Example:import datetime tday = datetime.date.today()daytoday = tday.ctime() print(\"The date today is \", tday)print(\"The date info. is \", daytoday)OutputThe date today is 2020-01-30\nThe date info. is Thu Jan 30 00:00:00 2020\n" }, { "code": null, "e": 3339, "s": 3196, "text": "The values for the calendar date can be represented via the date class. The date instance consists of attributes for the year, month, and day." }, { "code": null, "e": 3347, "s": 3339, "text": "Syntax:" }, { "code": null, "e": 3367, "s": 3347, "text": "date(yyyy, mm, dd)\n" }, { "code": null, "e": 3376, "s": 3367, "text": "Example:" }, { "code": "import datetime date = datetime.date(2018, 5, 12)print('Date date is ', date.day, ' day of ', date.month, ' of the year ', date.year)", "e": 3523, "s": 3376, "text": null }, { "code": null, "e": 3530, "s": 3523, "text": "Output" }, { "code": null, "e": 3578, "s": 3530, "text": "Date date is 12 day of 5 of the year 2018\n" }, { "code": null, "e": 3731, "s": 3578, "text": "To get the today’s date names a method called today() is used and to get all the information in one object (today’s information) ctime() method is used." }, { "code": null, "e": 3740, "s": 3731, "text": "Example:" }, { "code": "import datetime tday = datetime.date.today()daytoday = tday.ctime() print(\"The date today is \", tday)print(\"The date info. is \", daytoday)", "e": 3883, "s": 3740, "text": null }, { "code": null, "e": 3890, "s": 3883, "text": "Output" }, { "code": null, "e": 3965, "s": 3890, "text": "The date today is 2020-01-30\nThe date info. is Thu Jan 30 00:00:00 2020\n" }, { "code": null, "e": 4112, "s": 3965, "text": "Date and time are different from strings and thus many times it is important to convert the datetime to string. For this we use strftime() method." }, { "code": null, "e": 4120, "s": 4112, "text": "Syntax:" }, { "code": null, "e": 4146, "s": 4120, "text": "time.strftime(format, t)\n" }, { "code": null, "e": 4158, "s": 4146, "text": "Parameters:" }, { "code": null, "e": 4249, "s": 4158, "text": "format – This is of string type. i.e. the directives can be embedded in the format string." }, { "code": null, "e": 4279, "s": 4249, "text": "t – the time to be formatted." }, { "code": null, "e": 4288, "s": 4279, "text": "Example:" }, { "code": "import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13) print(x.strftime(\"%b %d %Y %H:%M:%S\"))", "e": 4397, "s": 4288, "text": null }, { "code": null, "e": 4404, "s": 4397, "text": "Output" }, { "code": null, "e": 4425, "s": 4404, "text": "May 12 2018 02:25:50" }, { "code": null, "e": 4517, "s": 4425, "text": "The same example can also be written as a different place by setting up the print() method." }, { "code": "import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13) print(x.strftime(\"%H:%M:%S %b %d %Y\"))", "e": 4626, "s": 4517, "text": null }, { "code": null, "e": 4633, "s": 4626, "text": "Output" }, { "code": null, "e": 4655, "s": 4633, "text": "02:25:50 May 12 2018 " }, { "code": null, "e": 4799, "s": 4655, "text": "%H, %M and %S displays the hour, minutes and seconds respectively. %b, %d and %Y displays 3 characters of the month, day and year respectively." }, { "code": null, "e": 4902, "s": 4799, "text": "Other than the above example the frequently used character code List along with its functionality are:" }, { "code": null, "e": 5059, "s": 4902, "text": "%a: Displays three characters of the weekday, e.g. Wed.import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime(\"%a\"))OutputSat\n" }, { "code": "import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime(\"%a\"))", "e": 5151, "s": 5059, "text": null }, { "code": null, "e": 5158, "s": 5151, "text": "Output" }, { "code": null, "e": 5163, "s": 5158, "text": "Sat\n" }, { "code": null, "e": 5319, "s": 5163, "text": "%A: Displays name of the weekday, e.g. Wednesday.import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime(\"%A\"))OutputSaturday\n" }, { "code": "import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime(\"%A\"))", "e": 5411, "s": 5319, "text": null }, { "code": null, "e": 5418, "s": 5411, "text": "Output" }, { "code": null, "e": 5428, "s": 5418, "text": "Saturday\n" }, { "code": null, "e": 5563, "s": 5428, "text": "%B: Displays the month, e.g. May.import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime(\"%B\"))OutputMay\n" }, { "code": "import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime(\"%B\"))", "e": 5655, "s": 5563, "text": null }, { "code": null, "e": 5662, "s": 5655, "text": "Output" }, { "code": null, "e": 5667, "s": 5662, "text": "May\n" }, { "code": null, "e": 5838, "s": 5667, "text": "%w: Displays the weekday as a number, from 0 to 6, with Sunday being 0.import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime(\"%w\"))Output6\n" }, { "code": "import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime(\"%w\"))", "e": 5930, "s": 5838, "text": null }, { "code": null, "e": 5937, "s": 5930, "text": "Output" }, { "code": null, "e": 5940, "s": 5937, "text": "6\n" }, { "code": null, "e": 6086, "s": 5940, "text": "%m: Displays month as a number, from 01 to 12.import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime(\"%m\"))Output5\n" }, { "code": "import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime(\"%m\"))", "e": 6178, "s": 6086, "text": null }, { "code": null, "e": 6185, "s": 6178, "text": "Output" }, { "code": null, "e": 6188, "s": 6185, "text": "5\n" }, { "code": null, "e": 6315, "s": 6188, "text": "%p: Define AM/PM for time.import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime(\"%p\"))OutputPM\n" }, { "code": "import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime(\"%p\"))", "e": 6407, "s": 6315, "text": null }, { "code": null, "e": 6414, "s": 6407, "text": "Output" }, { "code": null, "e": 6418, "s": 6414, "text": "PM\n" }, { "code": null, "e": 6587, "s": 6418, "text": "%y: Displays year in two-digit format, i.e “20” in place of “2020”.import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime(\"% y\"))Output18\n" }, { "code": "import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime(\"% y\"))", "e": 6680, "s": 6587, "text": null }, { "code": null, "e": 6687, "s": 6680, "text": "Output" }, { "code": null, "e": 6691, "s": 6687, "text": "18\n" }, { "code": null, "e": 6844, "s": 6691, "text": "%f: Displays microsecond from 000000 to 999999.import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime(\"% f\"))Output000013\n" }, { "code": "import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime(\"% f\"))", "e": 6937, "s": 6844, "text": null }, { "code": null, "e": 6944, "s": 6937, "text": "Output" }, { "code": null, "e": 6952, "s": 6944, "text": "000013\n" }, { "code": null, "e": 7114, "s": 6952, "text": "%j: Displays number of the day in the year, from 001 to 366.import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime(\"%f\"))Output132\n" }, { "code": "import datetime x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime(\"%f\"))", "e": 7206, "s": 7114, "text": null }, { "code": null, "e": 7213, "s": 7206, "text": "Output" }, { "code": null, "e": 7218, "s": 7213, "text": "132\n" }, { "code": null, "e": 7249, "s": 7218, "text": "Conversion from string to date" }, { "code": null, "e": 7449, "s": 7249, "text": "Conversion from string to date is many times needed while working with imported data sets from a csv or when we take inputs from website forms. To do this, python provides a method called strptime()." }, { "code": null, "e": 7457, "s": 7449, "text": "Syntax:" }, { "code": null, "e": 7492, "s": 7457, "text": "datetime.strptime(string, format)\n" }, { "code": null, "e": 7504, "s": 7492, "text": "Parameters:" }, { "code": null, "e": 7531, "s": 7504, "text": "string – The input string." }, { "code": null, "e": 7622, "s": 7531, "text": "format – This is of string type. i.e. the directives can be embedded in the format string." }, { "code": null, "e": 7631, "s": 7622, "text": "Example:" }, { "code": "from datetime import datetime print(datetime.strptime('5/5/2019', '%d/%m/%Y'))", "e": 7736, "s": 7631, "text": null }, { "code": null, "e": 7743, "s": 7736, "text": "Output" }, { "code": null, "e": 7764, "s": 7743, "text": "2019-05-05 00:00:00\n" }, { "code": null, "e": 7780, "s": 7764, "text": "Python-datetime" }, { "code": null, "e": 7787, "s": 7780, "text": "Python" } ]
PyQt5 - Tri-state Check Box - GeeksforGeeks
22 Apr, 2020 When we create a check box, by default there are two state which are either checked i.e True and other is False. But we can add third state to it which is neither True or False with the help of setTristate method. Below is how all three states looks like. Syntax : checkbox.setTristate(True) Argument : It takes bool as argument. Action performed : It will add third state to the check box. Below is the implementation. # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating the check-box checkbox = QCheckBox('Check Box', self) # setting geometry of check box checkbox.setGeometry(200, 150, 100, 30) # creating the third state checkbox.setTristate(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python
[ { "code": null, "e": 25739, "s": 25711, "text": "\n22 Apr, 2020" }, { "code": null, "e": 25953, "s": 25739, "text": "When we create a check box, by default there are two state which are either checked i.e True and other is False. But we can add third state to it which is neither True or False with the help of setTristate method." }, { "code": null, "e": 25995, "s": 25953, "text": "Below is how all three states looks like." }, { "code": null, "e": 26031, "s": 25995, "text": "Syntax : checkbox.setTristate(True)" }, { "code": null, "e": 26069, "s": 26031, "text": "Argument : It takes bool as argument." }, { "code": null, "e": 26130, "s": 26069, "text": "Action performed : It will add third state to the check box." }, { "code": null, "e": 26159, "s": 26130, "text": "Below is the implementation." }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating the check-box checkbox = QCheckBox('Check Box', self) # setting geometry of check box checkbox.setGeometry(200, 150, 100, 30) # creating the third state checkbox.setTristate(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 27061, "s": 26159, "text": null }, { "code": null, "e": 27070, "s": 27061, "text": "Output :" }, { "code": null, "e": 27081, "s": 27070, "text": "Python-gui" }, { "code": null, "e": 27093, "s": 27081, "text": "Python-PyQt" }, { "code": null, "e": 27100, "s": 27093, "text": "Python" }, { "code": null, "e": 27198, "s": 27100, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27216, "s": 27198, "text": "Python Dictionary" }, { "code": null, "e": 27251, "s": 27216, "text": "Read a file line by line in Python" }, { "code": null, "e": 27283, "s": 27251, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27325, "s": 27283, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27355, "s": 27325, "text": "Iterate over a list in Python" }, { "code": null, "e": 27381, "s": 27355, "text": "Python String | replace()" }, { "code": null, "e": 27410, "s": 27381, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27454, "s": 27410, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27491, "s": 27454, "text": "Create a Pandas DataFrame from Lists" } ]
Difference between a Static Queue and a Singly Linked List - GeeksforGeeks
27 May, 2021 Static Queue: A queue is an ordered list of elements. It always works in first in first out(FIFO) fashion. All the elements get inserted at the REAR and removed from the FRONT of the queue. In implementation of the static Queue, an array will be used so all operation of queue are index based which makes it faster for all operations except deletion because deletion requires shifting of all the remaining elements to the front by one position.A Static Queue is a queue of fixed size implemented using array. Singly Linked List: A linked list is also an ordered list of elements. You can add an element anywhere in the list, change an element anywhere in the list, or remove an element from any position in the list. Each node in the list stores the content and a pointer or reference to the next node in the list. To store a single linked list, only the reference or pointer to the first node in that list must be stored. The last node in a single linked list points to nothing (or null). Here are some of the major differences between a Static Queue and a Singly Linked List Below is the implementation of a Static Queue: Java C# // Java program to implement a queue using an arrayclass Queue { private static int front, rear, capacity; private static int queue[]; Queue(int c) { front = rear = 0; capacity = c; queue = new int[capacity]; } // function to insert an element // at the rear of the queue static void queueEnqueue(int data) { // check queue is full or not if (capacity == rear) { System.out.printf("\nQueue is full\n"); return; } // insert element at the rear else { queue[rear] = data; rear++; } return; } // function to delete an element // from the front of the queue static void queueDequeue() { // if queue is empty if (front == rear) { System.out.printf("\nQueue is empty\n"); return; } // shift all the elements from index 2 till rear // to the right by one else { for (int i = 0; i < rear - 1; i++) { queue[i] = queue[i + 1]; } // store 0 at rear indicating there's no element if (rear < capacity) queue[rear] = 0; // decrement rear rear--; } return; } // print queue elements static void queueDisplay() { int i; if (front == rear) { System.out.printf("\nQueue is Empty\n"); return; } // traverse front to rear and print elements for (i = front; i < rear; i++) { System.out.printf(" %d <-- ", queue[i]); } return; } // print front of queue static void queueFront() { if (front == rear) { System.out.printf("\nQueue is Empty\n"); return; } System.out.printf("\nFront Element is: %d", queue[front]); return; }} public class StaticQueueinjava { // Driver code public static void main(String[] args) { // Create a queue of capacity 4 Queue q = new Queue(4); // print Queue elements q.queueDisplay(); // inserting elements in the queue q.queueEnqueue(20); q.queueEnqueue(30); q.queueEnqueue(40); q.queueEnqueue(50); // print Queue elements q.queueDisplay(); // insert element in the queue q.queueEnqueue(60); // print Queue elements q.queueDisplay(); q.queueDequeue(); q.queueDequeue(); System.out.printf("\n\nafter two node deletion\n\n"); // print Queue elements q.queueDisplay(); // print front of the queue q.queueFront(); }} // C# program to implement a queue using an arrayusing System; public class Queue{ private static int front, rear, capacity; private static int []queue; public Queue(int c) { front = rear = 0; capacity = c; queue = new int[capacity]; } // function to insert an element // at the rear of the queue public void queueEnqueue(int data) { // check queue is full or not if (capacity == rear) { Console.Write("\nQueue is full\n"); return; } // insert element at the rear else { queue[rear] = data; rear++; } return; } // function to delete an element // from the front of the queue public void queueDequeue() { // if queue is empty if (front == rear) { Console.Write("\nQueue is empty\n"); return; } // shift all the elements from index 2 till rear // to the right by one else { for (int i = 0; i < rear - 1; i++) { queue[i] = queue[i + 1]; } // store 0 at rear indicating there's no element if (rear < capacity) queue[rear] = 0; // decrement rear rear--; } return; } // print queue elements public void queueDisplay() { int i; if (front == rear) { Console.Write("\nQueue is Empty\n"); return; } // traverse front to rear and print elements for (i = front; i < rear; i++) { Console.Write(" {0} <-- ", queue[i]); } return; } // print front of queue public void queueFront() { if (front == rear) { Console.Write("\nQueue is Empty\n"); return; } Console.Write("\nFront Element is: {0}", queue[front]); return; }} public class StaticQueueinjava{ // Driver code public static void Main(String[] args) { // Create a queue of capacity 4 Queue q = new Queue(4); // print Queue elements q.queueDisplay(); // inserting elements in the queue q.queueEnqueue(20); q.queueEnqueue(30); q.queueEnqueue(40); q.queueEnqueue(50); // print Queue elements q.queueDisplay(); // insert element in the queue q.queueEnqueue(60); // print Queue elements q.queueDisplay(); q.queueDequeue(); q.queueDequeue(); Console.Write("\n\nafter two node deletion\n\n"); // print Queue elements q.queueDisplay(); // print front of the queue q.queueFront(); }} /* This code contributed by PrinciRaj1992 */ Queue is Empty 20 <-- 30 <-- 40 <-- 50 <-- Queue is full 20 <-- 30 <-- 40 <-- 50 <-- after two node deletion 40 <-- 50 <-- Front Element is: 40 Below is the implementation of a Singly Linked List: Java C# Javascript // Java program to implement singly linked listclass SinglyLList { class Node { // node variables int data; Node next; public Node(int data) { this.data = data; this.next = null; } } // create reference variable of Node Node head; // function to insert a node // at the beginning of the list void InsertAtStart(int data) { // create a node Node new_node = new Node(data); new_node.next = head; head = new_node; } // function to insert node // at the end of the list void InsertAtLast(int data) { Node new_node = new Node(data); if (head == null) { head = new_node; return; } new_node.next = null; Node last = head; while (last.next != null) { last = last.next; } last.next = new_node; } // function to delete a node // at the beginning of the list void DeleteAtStart() { if (head == null) { System.out.println("List is empty"); return; } head = head.next; } // function to delete a node at // a given position in the list void DeleteAtPos(int pos) throws Exception { int position = 0; if (pos > Count() || pos < 0) { throw new Exception("Incorrect position exception"); } Node temp = head; while (position != pos - 1) { temp = temp.next; position++; } temp.next = temp.next.next; } // function to delete a node // from the end of the list void DeleteAtLast() { Node delete = head; while (delete.next != null && delete.next.next != null) { delete = delete.next; } delete.next = null; } // function to display all the nodes of the list void Display() { Node disp = head; while (disp != null) { System.out.print(disp.data + "->"); disp = disp.next; } } // function to return the total nodes in the list int Count() { int elements = 0; Node count = head; while (count != null) { count = count.next; elements++; } return elements; }} public class GFG { // Driver code public static void main(String[] args) throws Exception { // create object of class singlyList SinglyLList list = new SinglyLList(); // insert elements of singly linked list // at beginning list.InsertAtStart(3); list.InsertAtStart(2); list.InsertAtStart(1); // print linked list elements list.Display(); // insert element at the end of list list.InsertAtLast(1); System.out.println("\nafter inserting node at the end\n "); // print linked list elements list.Display(); // delete an element at the given position list.DeleteAtPos(1); // delete starting element list.DeleteAtStart(); // delete last element list.DeleteAtLast(); System.out.println("\nafter deleting node: second, first and last\n "); // print linked list elements list.Display(); }} // C# program to implement singly linked listusing System; public class SinglyLList{ public class Node { // node variables public int data; public Node next; public Node(int data) { this.data = data; this.next = null; } } // create reference variable of Node public Node head; // function to insert a node // at the beginning of the list public void InsertAtStart(int data) { // create a node Node new_node = new Node(data); new_node.next = head; head = new_node; } // function to insert node // at the end of the list public void InsertAtLast(int data) { Node new_node = new Node(data); if (head == null) { head = new_node; return; } new_node.next = null; Node last = head; while (last.next != null) { last = last.next; } last.next = new_node; } // function to delete a node // at the beginning of the list public void DeleteAtStart() { if (head == null) { Console.WriteLine("List is empty"); return; } head = head.next; } // function to delete a node at // a given position in the list public void DeleteAtPos(int pos) { int position = 0; if (pos > Count() || pos < 0) { throw new Exception("Incorrect position exception"); } Node temp = head; while (position != pos - 1) { temp = temp.next; position++; } temp.next = temp.next.next; } // function to delete a node // from the end of the list public void DeleteAtLast() { Node delete = head; while (delete.next != null && delete.next.next != null) { delete = delete.next; } delete.next = null; } // function to display all the nodes of the list public void Display() { Node disp = head; while (disp != null) { Console.Write(disp.data + "->"); disp = disp.next; } } // function to return the total nodes in the list public int Count() { int elements = 0; Node count = head; while (count != null) { count = count.next; elements++; } return elements; }} class GFG{ // Driver code public static void Main(String[] args) { // create object of class singlyList SinglyLList list = new SinglyLList(); // insert elements of singly linked list // at beginning list.InsertAtStart(3); list.InsertAtStart(2); list.InsertAtStart(1); // print linked list elements list.Display(); // insert element at the end of list list.InsertAtLast(1); Console.WriteLine("\nafter inserting node at the end\n "); // print linked list elements list.Display(); // delete an element at the given position list.DeleteAtPos(1); // delete starting element list.DeleteAtStart(); // delete last element list.DeleteAtLast(); Console.WriteLine("\nafter deleting node: second, first and last\n "); // print linked list elements list.Display(); }} // This code has been contributed by 29AjayKumar <script> // JavaScript program to implement// singly linked list class Node { constructor(val) { this.data = val; this.next = null; } } // create reference variable of Node var head; // function to insert a node // at the beginning of the list function InsertAtStart(data) { // create a node var new_node = new Node(data); new_node.next = head; head = new_node; } // function to insert node // at the end of the list function InsertAtLast(data) { var new_node = new Node(data); if (head == null) { head = new_node; return; } new_node.next = null; var last = head; while (last.next != null) { last = last.next; } last.next = new_node; } // function to delete a node // at the beginning of the list function DeleteAtStart() { if (head == null) { document.write("List is empty"); return; } head = head.next; } // function to delete a node at // a given position in the list function DeleteAtPos(pos) { var position = 0; if (pos > Count() || pos < 0) { } var temp = head; while (position != pos - 1) { temp = temp.next; position++; } temp.next = temp.next.next; } // function to delete a node // from the end of the list function DeleteAtLast() { var deletenode = head; while (deletenode.next != null && deletenode.next.next != null) { deletenode = deletenode.next; } deletenode.next = null; } // function to display all the nodes of the list function Display() { var disp = head; while (disp != null) { document.write(disp.data + "->"); disp = disp.next; } } // function to return the total nodes in the list function Count() { var elements = 0; var count = head; while (count != null) { count = count.next; elements++; } return elements; } // Driver code // create object of class singlyList // insert elements of singly linked list // at beginning InsertAtStart(3); InsertAtStart(2); InsertAtStart(1); // print linked list elements Display(); // insert element at the end of list InsertAtLast(1); document.write( "<br/>after inserting node at the end<br/><br/> " ); // print linked list elements Display(); // delete an element at the given position DeleteAtPos(1); // delete starting element DeleteAtStart(); // delete last element DeleteAtLast(); document.write( "<br/>after deleting node: second, first and last<br/>" ); // print linked list elements Display(); // This code is contributed by todaysgaurav </script> 1->2->3-> after inserting node at the end 1->2->3->1-> after deleting node: second, first and last 3-> 29AjayKumar princiraj1992 nidhi_biet todaysgaurav Arrays Technical Scripter 2018 Linked List Queue Technical Scripter Linked List Arrays Queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Circular Linked List | Set 2 (Traversal) Swap nodes in a linked list without swapping data Program to implement Singly Linked List in C++ using class Circular Singly Linked List | Insertion Given a linked list which is sorted, how will you insert in sorted way Breadth First Search or BFS for a Graph Level Order Binary Tree Traversal Queue Interface In Java Queue in Python Queue | Set 1 (Introduction and Array Implementation)
[ { "code": null, "e": 26203, "s": 26175, "text": "\n27 May, 2021" }, { "code": null, "e": 26713, "s": 26203, "text": "Static Queue: A queue is an ordered list of elements. It always works in first in first out(FIFO) fashion. All the elements get inserted at the REAR and removed from the FRONT of the queue. In implementation of the static Queue, an array will be used so all operation of queue are index based which makes it faster for all operations except deletion because deletion requires shifting of all the remaining elements to the front by one position.A Static Queue is a queue of fixed size implemented using array. " }, { "code": null, "e": 27197, "s": 26715, "text": "Singly Linked List: A linked list is also an ordered list of elements. You can add an element anywhere in the list, change an element anywhere in the list, or remove an element from any position in the list. Each node in the list stores the content and a pointer or reference to the next node in the list. To store a single linked list, only the reference or pointer to the first node in that list must be stored. The last node in a single linked list points to nothing (or null). " }, { "code": null, "e": 27286, "s": 27197, "text": "Here are some of the major differences between a Static Queue and a Singly Linked List " }, { "code": null, "e": 27335, "s": 27286, "text": "Below is the implementation of a Static Queue: " }, { "code": null, "e": 27340, "s": 27335, "text": "Java" }, { "code": null, "e": 27343, "s": 27340, "text": "C#" }, { "code": "// Java program to implement a queue using an arrayclass Queue { private static int front, rear, capacity; private static int queue[]; Queue(int c) { front = rear = 0; capacity = c; queue = new int[capacity]; } // function to insert an element // at the rear of the queue static void queueEnqueue(int data) { // check queue is full or not if (capacity == rear) { System.out.printf(\"\\nQueue is full\\n\"); return; } // insert element at the rear else { queue[rear] = data; rear++; } return; } // function to delete an element // from the front of the queue static void queueDequeue() { // if queue is empty if (front == rear) { System.out.printf(\"\\nQueue is empty\\n\"); return; } // shift all the elements from index 2 till rear // to the right by one else { for (int i = 0; i < rear - 1; i++) { queue[i] = queue[i + 1]; } // store 0 at rear indicating there's no element if (rear < capacity) queue[rear] = 0; // decrement rear rear--; } return; } // print queue elements static void queueDisplay() { int i; if (front == rear) { System.out.printf(\"\\nQueue is Empty\\n\"); return; } // traverse front to rear and print elements for (i = front; i < rear; i++) { System.out.printf(\" %d <-- \", queue[i]); } return; } // print front of queue static void queueFront() { if (front == rear) { System.out.printf(\"\\nQueue is Empty\\n\"); return; } System.out.printf(\"\\nFront Element is: %d\", queue[front]); return; }} public class StaticQueueinjava { // Driver code public static void main(String[] args) { // Create a queue of capacity 4 Queue q = new Queue(4); // print Queue elements q.queueDisplay(); // inserting elements in the queue q.queueEnqueue(20); q.queueEnqueue(30); q.queueEnqueue(40); q.queueEnqueue(50); // print Queue elements q.queueDisplay(); // insert element in the queue q.queueEnqueue(60); // print Queue elements q.queueDisplay(); q.queueDequeue(); q.queueDequeue(); System.out.printf(\"\\n\\nafter two node deletion\\n\\n\"); // print Queue elements q.queueDisplay(); // print front of the queue q.queueFront(); }}", "e": 30033, "s": 27343, "text": null }, { "code": "// C# program to implement a queue using an arrayusing System; public class Queue{ private static int front, rear, capacity; private static int []queue; public Queue(int c) { front = rear = 0; capacity = c; queue = new int[capacity]; } // function to insert an element // at the rear of the queue public void queueEnqueue(int data) { // check queue is full or not if (capacity == rear) { Console.Write(\"\\nQueue is full\\n\"); return; } // insert element at the rear else { queue[rear] = data; rear++; } return; } // function to delete an element // from the front of the queue public void queueDequeue() { // if queue is empty if (front == rear) { Console.Write(\"\\nQueue is empty\\n\"); return; } // shift all the elements from index 2 till rear // to the right by one else { for (int i = 0; i < rear - 1; i++) { queue[i] = queue[i + 1]; } // store 0 at rear indicating there's no element if (rear < capacity) queue[rear] = 0; // decrement rear rear--; } return; } // print queue elements public void queueDisplay() { int i; if (front == rear) { Console.Write(\"\\nQueue is Empty\\n\"); return; } // traverse front to rear and print elements for (i = front; i < rear; i++) { Console.Write(\" {0} <-- \", queue[i]); } return; } // print front of queue public void queueFront() { if (front == rear) { Console.Write(\"\\nQueue is Empty\\n\"); return; } Console.Write(\"\\nFront Element is: {0}\", queue[front]); return; }} public class StaticQueueinjava{ // Driver code public static void Main(String[] args) { // Create a queue of capacity 4 Queue q = new Queue(4); // print Queue elements q.queueDisplay(); // inserting elements in the queue q.queueEnqueue(20); q.queueEnqueue(30); q.queueEnqueue(40); q.queueEnqueue(50); // print Queue elements q.queueDisplay(); // insert element in the queue q.queueEnqueue(60); // print Queue elements q.queueDisplay(); q.queueDequeue(); q.queueDequeue(); Console.Write(\"\\n\\nafter two node deletion\\n\\n\"); // print Queue elements q.queueDisplay(); // print front of the queue q.queueFront(); }} /* This code contributed by PrinciRaj1992 */", "e": 32830, "s": 30033, "text": null }, { "code": null, "e": 32989, "s": 32830, "text": "Queue is Empty\n 20 <-- 30 <-- 40 <-- 50 <-- \nQueue is full\n 20 <-- 30 <-- 40 <-- 50 <-- \n\nafter two node deletion\n\n 40 <-- 50 <-- \nFront Element is: 40" }, { "code": null, "e": 33046, "s": 32991, "text": "Below is the implementation of a Singly Linked List: " }, { "code": null, "e": 33051, "s": 33046, "text": "Java" }, { "code": null, "e": 33054, "s": 33051, "text": "C#" }, { "code": null, "e": 33065, "s": 33054, "text": "Javascript" }, { "code": "// Java program to implement singly linked listclass SinglyLList { class Node { // node variables int data; Node next; public Node(int data) { this.data = data; this.next = null; } } // create reference variable of Node Node head; // function to insert a node // at the beginning of the list void InsertAtStart(int data) { // create a node Node new_node = new Node(data); new_node.next = head; head = new_node; } // function to insert node // at the end of the list void InsertAtLast(int data) { Node new_node = new Node(data); if (head == null) { head = new_node; return; } new_node.next = null; Node last = head; while (last.next != null) { last = last.next; } last.next = new_node; } // function to delete a node // at the beginning of the list void DeleteAtStart() { if (head == null) { System.out.println(\"List is empty\"); return; } head = head.next; } // function to delete a node at // a given position in the list void DeleteAtPos(int pos) throws Exception { int position = 0; if (pos > Count() || pos < 0) { throw new Exception(\"Incorrect position exception\"); } Node temp = head; while (position != pos - 1) { temp = temp.next; position++; } temp.next = temp.next.next; } // function to delete a node // from the end of the list void DeleteAtLast() { Node delete = head; while (delete.next != null && delete.next.next != null) { delete = delete.next; } delete.next = null; } // function to display all the nodes of the list void Display() { Node disp = head; while (disp != null) { System.out.print(disp.data + \"->\"); disp = disp.next; } } // function to return the total nodes in the list int Count() { int elements = 0; Node count = head; while (count != null) { count = count.next; elements++; } return elements; }} public class GFG { // Driver code public static void main(String[] args) throws Exception { // create object of class singlyList SinglyLList list = new SinglyLList(); // insert elements of singly linked list // at beginning list.InsertAtStart(3); list.InsertAtStart(2); list.InsertAtStart(1); // print linked list elements list.Display(); // insert element at the end of list list.InsertAtLast(1); System.out.println(\"\\nafter inserting node at the end\\n \"); // print linked list elements list.Display(); // delete an element at the given position list.DeleteAtPos(1); // delete starting element list.DeleteAtStart(); // delete last element list.DeleteAtLast(); System.out.println(\"\\nafter deleting node: second, first and last\\n \"); // print linked list elements list.Display(); }}", "e": 36346, "s": 33065, "text": null }, { "code": "// C# program to implement singly linked listusing System; public class SinglyLList{ public class Node { // node variables public int data; public Node next; public Node(int data) { this.data = data; this.next = null; } } // create reference variable of Node public Node head; // function to insert a node // at the beginning of the list public void InsertAtStart(int data) { // create a node Node new_node = new Node(data); new_node.next = head; head = new_node; } // function to insert node // at the end of the list public void InsertAtLast(int data) { Node new_node = new Node(data); if (head == null) { head = new_node; return; } new_node.next = null; Node last = head; while (last.next != null) { last = last.next; } last.next = new_node; } // function to delete a node // at the beginning of the list public void DeleteAtStart() { if (head == null) { Console.WriteLine(\"List is empty\"); return; } head = head.next; } // function to delete a node at // a given position in the list public void DeleteAtPos(int pos) { int position = 0; if (pos > Count() || pos < 0) { throw new Exception(\"Incorrect position exception\"); } Node temp = head; while (position != pos - 1) { temp = temp.next; position++; } temp.next = temp.next.next; } // function to delete a node // from the end of the list public void DeleteAtLast() { Node delete = head; while (delete.next != null && delete.next.next != null) { delete = delete.next; } delete.next = null; } // function to display all the nodes of the list public void Display() { Node disp = head; while (disp != null) { Console.Write(disp.data + \"->\"); disp = disp.next; } } // function to return the total nodes in the list public int Count() { int elements = 0; Node count = head; while (count != null) { count = count.next; elements++; } return elements; }} class GFG{ // Driver code public static void Main(String[] args) { // create object of class singlyList SinglyLList list = new SinglyLList(); // insert elements of singly linked list // at beginning list.InsertAtStart(3); list.InsertAtStart(2); list.InsertAtStart(1); // print linked list elements list.Display(); // insert element at the end of list list.InsertAtLast(1); Console.WriteLine(\"\\nafter inserting node at the end\\n \"); // print linked list elements list.Display(); // delete an element at the given position list.DeleteAtPos(1); // delete starting element list.DeleteAtStart(); // delete last element list.DeleteAtLast(); Console.WriteLine(\"\\nafter deleting node: second, first and last\\n \"); // print linked list elements list.Display(); }} // This code has been contributed by 29AjayKumar", "e": 39779, "s": 36346, "text": null }, { "code": "<script> // JavaScript program to implement// singly linked list class Node { constructor(val) { this.data = val; this.next = null; } } // create reference variable of Node var head; // function to insert a node // at the beginning of the list function InsertAtStart(data) { // create a node var new_node = new Node(data); new_node.next = head; head = new_node; } // function to insert node // at the end of the list function InsertAtLast(data) { var new_node = new Node(data); if (head == null) { head = new_node; return; } new_node.next = null; var last = head; while (last.next != null) { last = last.next; } last.next = new_node; } // function to delete a node // at the beginning of the list function DeleteAtStart() { if (head == null) { document.write(\"List is empty\"); return; } head = head.next; } // function to delete a node at // a given position in the list function DeleteAtPos(pos) { var position = 0; if (pos > Count() || pos < 0) { } var temp = head; while (position != pos - 1) { temp = temp.next; position++; } temp.next = temp.next.next; } // function to delete a node // from the end of the list function DeleteAtLast() { var deletenode = head; while (deletenode.next != null && deletenode.next.next != null) { deletenode = deletenode.next; } deletenode.next = null; } // function to display all the nodes of the list function Display() { var disp = head; while (disp != null) { document.write(disp.data + \"->\"); disp = disp.next; } } // function to return the total nodes in the list function Count() { var elements = 0; var count = head; while (count != null) { count = count.next; elements++; } return elements; } // Driver code // create object of class singlyList // insert elements of singly linked list // at beginning InsertAtStart(3); InsertAtStart(2); InsertAtStart(1); // print linked list elements Display(); // insert element at the end of list InsertAtLast(1); document.write( \"<br/>after inserting node at the end<br/><br/> \" ); // print linked list elements Display(); // delete an element at the given position DeleteAtPos(1); // delete starting element DeleteAtStart(); // delete last element DeleteAtLast(); document.write( \"<br/>after deleting node: second, first and last<br/>\" ); // print linked list elements Display(); // This code is contributed by todaysgaurav </script>", "e": 42843, "s": 39779, "text": null }, { "code": null, "e": 42950, "s": 42843, "text": "1->2->3->\nafter inserting node at the end\n \n1->2->3->1->\nafter deleting node: second, first and last\n \n3->" }, { "code": null, "e": 42964, "s": 42952, "text": "29AjayKumar" }, { "code": null, "e": 42978, "s": 42964, "text": "princiraj1992" }, { "code": null, "e": 42989, "s": 42978, "text": "nidhi_biet" }, { "code": null, "e": 43002, "s": 42989, "text": "todaysgaurav" }, { "code": null, "e": 43009, "s": 43002, "text": "Arrays" }, { "code": null, "e": 43033, "s": 43009, "text": "Technical Scripter 2018" }, { "code": null, "e": 43045, "s": 43033, "text": "Linked List" }, { "code": null, "e": 43051, "s": 43045, "text": "Queue" }, { "code": null, "e": 43070, "s": 43051, "text": "Technical Scripter" }, { "code": null, "e": 43082, "s": 43070, "text": "Linked List" }, { "code": null, "e": 43089, "s": 43082, "text": "Arrays" }, { "code": null, "e": 43095, "s": 43089, "text": "Queue" }, { "code": null, "e": 43193, "s": 43095, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43234, "s": 43193, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 43284, "s": 43234, "text": "Swap nodes in a linked list without swapping data" }, { "code": null, "e": 43343, "s": 43284, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 43383, "s": 43343, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 43454, "s": 43383, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 43494, "s": 43454, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 43528, "s": 43494, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 43552, "s": 43528, "text": "Queue Interface In Java" }, { "code": null, "e": 43568, "s": 43552, "text": "Queue in Python" } ]
Build A Simple "PhotoShop" Using Python | Towards Data Science
When we want to edit a piece of photo, we usually come up with some professional tools such as PhotoShop. Even though there are a lot of much easier for use tools having a fair amount of features that could satisfy most of our needs, we still usually need to download, install and spend a little bit of time to learn how to use them. However, if you are a programmer, or even better a Python developer, it might be much easier to edit your photos in Python. Or, maybe just for fun, it is still cool to understand how an image is represented in numbers and how to modify these low-level features to achieve high-level requirements. In this article, I will demonstrate how to use two libraries in Python — PIL and NumPy — to achieve most of the basic photo editing features in only 2–3 lines of code. We don’t need to do any preparation, because the library Pillow is built in the relatively newer Python. Also, I believe you must have NumPy in your Python environment if you program in Python because it is one of the most fundamental libraries that we must have. What we need to do is just import these two libraries. from PIL import Imageimport numpy as np For the Pillow library, we only need its Image module. Also, if you are not familiar with Pillow, please be noted that the package we imported PIL is different from its library name. This is not uncommon, but just be aware of that. Then, we need a photo to edit. One of my favourite places on this planet is the Twelve Apostles on the Great Ocean Road in Victoria, Australia. So, let’s use a photo from there. Thanks to JVAstudio on the website Pixabay, we have such an amazing one. We have a photo now, so we can easily use PIL to load it into memory. image = Image.open('apostles-2965525_640.jpg') If we check the type of the object image, it is not something that can be directly worked on. type(image) Now, we can use NumPy. Under the neath the image object from PIL is a 3D array. We can easily convert it as a NumPy array. After that, because it is already converted into a multi-dimensional array, we can check its shape img_data = np.array(image)img_data.shape It is shown that the image has 377 pixels high, 640 pixels wide and the 3 is the channels that are red, green and blue (RGB) respectively. Don’t worry if you have other photos with different dimensions, everything in this article that I will introduce is going to be generic. We can print the values for the first pixel, which is the one on the top left corner, but with all the 3 channels. img_data[:1,:1,:] That means, for the first pixel, we have 204 for red colour, 215 for green colour and 233 for blue colour. What do they mean? All the values that are used to represent a pixel must be in a range of [0, 255]. The colour we see in every photo consists of three values that combine to become a “colour” (here we just ignore the alpha which represents the transparency because it’s not relevant to this article). Also, the higher number means the lighter colour in this channel. In other words, (255, 255, 255) is purely white and (0, 0, 0) is purely black. Therefore, it makes sense that we have (204, 215, 233) for the top left corner pixel because it is part of the sky which is quite close to white. Now, let’s see what we can do to edit the photo! As we just explained the RGB values, so we can separate the channel to have the photo be represented in a single meta colour. Remember we have 3 channels as the third dimension of the array? To separate the channel is as easy as slicing the 3D array from the third dimension. To make sure our new photo only has colour from one channel, we need to make sure all the values for the other two channels are zero. So, we need to initialise a 3D array with all zeros, and then update the corresponding channel with the values from the original photo. img_chn_red = np.zeros(img_data.shape, dtype='uint8')img_chn_red[:,:,0] = img_data[:,:,0]image_red = Image.fromarray(img_chn_red) Because “RGB” the red colour comes first, so we need to slice the 3D array to have all values from the 1st channel. Also, it is important to initialise the zeros using explicitly data type. Otherwise, the default zeros are of float type which is not supported to be utilised to generate an image. The result is like this. Similarly, we can also separate the green channel. Simply slice the original array to have the 2nd channel. img_chn_green = np.zeros(img_data.shape, dtype='uint8')img_chn_green[:,:,1] = img_data[:,:,1]image_green = Image.fromarray(img_chn_green) And the blue channel. img_chn_blue = np.zeros(img_data.shape, dtype='uint8')img_chn_blue[:,:,2] = img_data[:,:,2]image_blue = Image.fromarray(img_chn_blue) In this example, we completely filtered the array to have values from a specific channel. Imagine that if you apply a coefficient on a certain channel, you could change the colour temperature as well. We have got the array of the image and we know the meaning of each dimension. So, it is quite easy to crop the image to size. In this case, we don’t want to hurt the colour, so we should keep the 3rd dimension unchanged, and dice the array by defining the range of the 1st dimension (height) and the 2nd dimension (width). img_cropped_data = img_data[60:250, 200:500, :]img_cropped = Image.fromarray(img_cropped_data) If we flip the 3D array, then we flip the photo. Please be noticed that we can flip on the 1st axis (upside down), or flip on the 2nd axis (left-right flipped), but we can’t do that on the 3rd axis because it will change the colour. img_flipped_data = np.flip(img_data, axis=1)img_flipped = Image.fromarray(img_flipped_data) Once we know that each value in the array is of the range [0, 255], we can reverse the colour by subtracting each value from 255. This is extremely easy using the NumPy broadcasting feature. img_reversed_data = 255 - img_dataimg_reversed = Image.fromarray(img_reversed_data) Most of the time I’m using photo editing software is to rotate the photo, I believe you might be the same :) This is also easy because NumPy provides the function to rotate an array. img_rotated_data = np.rot90(img_data)img_rotated = Image.fromarray(img_rotated_data) In this article, I have introduced how to use the Python built-in library Pillow to read a photo into a NumPy array. Then, we can do a lot of things to this multi-dimensional NumPy array to achieve many different types of photo editing features. Of course, there must be a lot more we could do to the photo. So, use your creativity to discover more cool editing features. Literally, what we can do with the NumPy multi-dimension array, must correspond to a type of editing of a photo. All the code used in this article can be found in my Google Colab Notebook. colab.research.google.com 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": 506, "s": 172, "text": "When we want to edit a piece of photo, we usually come up with some professional tools such as PhotoShop. Even though there are a lot of much easier for use tools having a fair amount of features that could satisfy most of our needs, we still usually need to download, install and spend a little bit of time to learn how to use them." }, { "code": null, "e": 803, "s": 506, "text": "However, if you are a programmer, or even better a Python developer, it might be much easier to edit your photos in Python. Or, maybe just for fun, it is still cool to understand how an image is represented in numbers and how to modify these low-level features to achieve high-level requirements." }, { "code": null, "e": 971, "s": 803, "text": "In this article, I will demonstrate how to use two libraries in Python — PIL and NumPy — to achieve most of the basic photo editing features in only 2–3 lines of code." }, { "code": null, "e": 1235, "s": 971, "text": "We don’t need to do any preparation, because the library Pillow is built in the relatively newer Python. Also, I believe you must have NumPy in your Python environment if you program in Python because it is one of the most fundamental libraries that we must have." }, { "code": null, "e": 1290, "s": 1235, "text": "What we need to do is just import these two libraries." }, { "code": null, "e": 1330, "s": 1290, "text": "from PIL import Imageimport numpy as np" }, { "code": null, "e": 1562, "s": 1330, "text": "For the Pillow library, we only need its Image module. Also, if you are not familiar with Pillow, please be noted that the package we imported PIL is different from its library name. This is not uncommon, but just be aware of that." }, { "code": null, "e": 1813, "s": 1562, "text": "Then, we need a photo to edit. One of my favourite places on this planet is the Twelve Apostles on the Great Ocean Road in Victoria, Australia. So, let’s use a photo from there. Thanks to JVAstudio on the website Pixabay, we have such an amazing one." }, { "code": null, "e": 1883, "s": 1813, "text": "We have a photo now, so we can easily use PIL to load it into memory." }, { "code": null, "e": 1930, "s": 1883, "text": "image = Image.open('apostles-2965525_640.jpg')" }, { "code": null, "e": 2024, "s": 1930, "text": "If we check the type of the object image, it is not something that can be directly worked on." }, { "code": null, "e": 2036, "s": 2024, "text": "type(image)" }, { "code": null, "e": 2258, "s": 2036, "text": "Now, we can use NumPy. Under the neath the image object from PIL is a 3D array. We can easily convert it as a NumPy array. After that, because it is already converted into a multi-dimensional array, we can check its shape" }, { "code": null, "e": 2299, "s": 2258, "text": "img_data = np.array(image)img_data.shape" }, { "code": null, "e": 2575, "s": 2299, "text": "It is shown that the image has 377 pixels high, 640 pixels wide and the 3 is the channels that are red, green and blue (RGB) respectively. Don’t worry if you have other photos with different dimensions, everything in this article that I will introduce is going to be generic." }, { "code": null, "e": 2690, "s": 2575, "text": "We can print the values for the first pixel, which is the one on the top left corner, but with all the 3 channels." }, { "code": null, "e": 2708, "s": 2690, "text": "img_data[:1,:1,:]" }, { "code": null, "e": 3408, "s": 2708, "text": "That means, for the first pixel, we have 204 for red colour, 215 for green colour and 233 for blue colour. What do they mean? All the values that are used to represent a pixel must be in a range of [0, 255]. The colour we see in every photo consists of three values that combine to become a “colour” (here we just ignore the alpha which represents the transparency because it’s not relevant to this article). Also, the higher number means the lighter colour in this channel. In other words, (255, 255, 255) is purely white and (0, 0, 0) is purely black. Therefore, it makes sense that we have (204, 215, 233) for the top left corner pixel because it is part of the sky which is quite close to white." }, { "code": null, "e": 3583, "s": 3408, "text": "Now, let’s see what we can do to edit the photo! As we just explained the RGB values, so we can separate the channel to have the photo be represented in a single meta colour." }, { "code": null, "e": 3733, "s": 3583, "text": "Remember we have 3 channels as the third dimension of the array? To separate the channel is as easy as slicing the 3D array from the third dimension." }, { "code": null, "e": 4003, "s": 3733, "text": "To make sure our new photo only has colour from one channel, we need to make sure all the values for the other two channels are zero. So, we need to initialise a 3D array with all zeros, and then update the corresponding channel with the values from the original photo." }, { "code": null, "e": 4133, "s": 4003, "text": "img_chn_red = np.zeros(img_data.shape, dtype='uint8')img_chn_red[:,:,0] = img_data[:,:,0]image_red = Image.fromarray(img_chn_red)" }, { "code": null, "e": 4430, "s": 4133, "text": "Because “RGB” the red colour comes first, so we need to slice the 3D array to have all values from the 1st channel. Also, it is important to initialise the zeros using explicitly data type. Otherwise, the default zeros are of float type which is not supported to be utilised to generate an image." }, { "code": null, "e": 4455, "s": 4430, "text": "The result is like this." }, { "code": null, "e": 4563, "s": 4455, "text": "Similarly, we can also separate the green channel. Simply slice the original array to have the 2nd channel." }, { "code": null, "e": 4701, "s": 4563, "text": "img_chn_green = np.zeros(img_data.shape, dtype='uint8')img_chn_green[:,:,1] = img_data[:,:,1]image_green = Image.fromarray(img_chn_green)" }, { "code": null, "e": 4723, "s": 4701, "text": "And the blue channel." }, { "code": null, "e": 4857, "s": 4723, "text": "img_chn_blue = np.zeros(img_data.shape, dtype='uint8')img_chn_blue[:,:,2] = img_data[:,:,2]image_blue = Image.fromarray(img_chn_blue)" }, { "code": null, "e": 5058, "s": 4857, "text": "In this example, we completely filtered the array to have values from a specific channel. Imagine that if you apply a coefficient on a certain channel, you could change the colour temperature as well." }, { "code": null, "e": 5184, "s": 5058, "text": "We have got the array of the image and we know the meaning of each dimension. So, it is quite easy to crop the image to size." }, { "code": null, "e": 5381, "s": 5184, "text": "In this case, we don’t want to hurt the colour, so we should keep the 3rd dimension unchanged, and dice the array by defining the range of the 1st dimension (height) and the 2nd dimension (width)." }, { "code": null, "e": 5476, "s": 5381, "text": "img_cropped_data = img_data[60:250, 200:500, :]img_cropped = Image.fromarray(img_cropped_data)" }, { "code": null, "e": 5709, "s": 5476, "text": "If we flip the 3D array, then we flip the photo. Please be noticed that we can flip on the 1st axis (upside down), or flip on the 2nd axis (left-right flipped), but we can’t do that on the 3rd axis because it will change the colour." }, { "code": null, "e": 5801, "s": 5709, "text": "img_flipped_data = np.flip(img_data, axis=1)img_flipped = Image.fromarray(img_flipped_data)" }, { "code": null, "e": 5992, "s": 5801, "text": "Once we know that each value in the array is of the range [0, 255], we can reverse the colour by subtracting each value from 255. This is extremely easy using the NumPy broadcasting feature." }, { "code": null, "e": 6076, "s": 5992, "text": "img_reversed_data = 255 - img_dataimg_reversed = Image.fromarray(img_reversed_data)" }, { "code": null, "e": 6259, "s": 6076, "text": "Most of the time I’m using photo editing software is to rotate the photo, I believe you might be the same :) This is also easy because NumPy provides the function to rotate an array." }, { "code": null, "e": 6344, "s": 6259, "text": "img_rotated_data = np.rot90(img_data)img_rotated = Image.fromarray(img_rotated_data)" }, { "code": null, "e": 6590, "s": 6344, "text": "In this article, I have introduced how to use the Python built-in library Pillow to read a photo into a NumPy array. Then, we can do a lot of things to this multi-dimensional NumPy array to achieve many different types of photo editing features." }, { "code": null, "e": 6829, "s": 6590, "text": "Of course, there must be a lot more we could do to the photo. So, use your creativity to discover more cool editing features. Literally, what we can do with the NumPy multi-dimension array, must correspond to a type of editing of a photo." }, { "code": null, "e": 6905, "s": 6829, "text": "All the code used in this article can be found in my Google Colab Notebook." }, { "code": null, "e": 6931, "s": 6905, "text": "colab.research.google.com" }, { "code": null, "e": 6942, "s": 6931, "text": "medium.com" } ]
Pandas vs SQL in 5 Examples. A comparison of the merge in Pandas and... | by Soner Yıldırım | Towards Data Science
Recently, I have written several articles that focus on the comparison of tools and frameworks used in the data science ecosystem such as Pandas vs dplyr, SQL vs NoSQL, Pandas vs SQL, Seaborn vs ggplot2, Seaborn vs Altair, and so on. In these articles, I focus on how a given task can be accomplished with different tools. I clearly see the differences as well as the similarities between them. Furthermore, it helps to build an intuition about how the creators of such tools approach particular problems. The focus of this article is to compare Pandas and SQL in terms of the merge and join operations. Pandas is a data analysis and manipulation library for Python. SQL is a programming language used to manage data in relational databases. Both work on tabular data with labelled rows and columns. The merge function of Pandas combines dataframes based on values in common columns. The same operation is done by joins in SQL. These are very useful operations especially when we have data about an observation (i.e. data point) in different dataframes of tables. I have created two simple dataframes and tables to illustrate merging and joining through examples. The “cust” contains 3 pieces of information about 5 customers. The columns are id, age, and category. The “purc” contains the ids of customers, ticket numbers, and purchase amounts. The id is the common column so we will be using it when merging or joining. You may have noticed that the id columns are not exactly the same. Some of the values exist in only one dataframe. We will see the ways to handle them in the examples. The first example is to merge or join based on the shared values in the id column. The default settings accomplish this task so we do not need to adjust any parameter. Pandas: import pandas as pdcust.merge(purc, on='id') SQL: mysql> select cust.*, purc.* -> from cust join purc -> on cust.id = purc.id;+------+------+------+------+--------+--------+| id | age | ctg | id | ticket | amount |+------+------+------+------+--------+--------+| 3 | 22 | B | 3 | 1001 | 24.10 || 4 | 29 | C | 4 | 1002 | 32.50 || 5 | 17 | B | 5 | 1003 | 34.80 |+------+------+------+------+--------+--------+ The merge function of Pandas does not return duplicate columns. On the hand, the id column is duplicated in SQL join if we select all of the columns (“*”) in both tables. Let’s say we want to have all the rows in the left table and only the matching rows in the right table. In Pandas, the on parameter is changed to “left”. In SQL, we use “left join” instead of “join” keyword. Pandas: cust.merge(purc, on='id', how='left') SQL: mysql> select cust.*, purc.* -> from cust -> left join purc -> on cust.id = purc.id;+------+------+------+------+--------+--------+| id | age | ctg | id | ticket | amount |+------+------+------+------+--------+--------+| 3 | 22 | B | 3 | 1001 | 24.10 || 4 | 29 | C | 4 | 1002 | 32.50 || 5 | 17 | B | 5 | 1003 | 34.80 || 1 | 34 | A | NULL | NULL | NULL || 2 | 28 | A | NULL | NULL | NULL |+------+------+------+------+--------+--------+ The purc dataframe and table do not have rows in which the id is 1 or 2. Thus, the columns from the purc are filled with Null values for these rows. We can do the same for the right dataframe using “right” argument for the on parameter. Similarly, the “right join” is used in SQL. What if we want to see all the rows in both dataframes or tables? Pandas: It is a straightforward operation in Pandas which can be done by passing ‘outer’ argument to the on parameter. cust.merge(purc, on='id', how='outer') SQL: MySQL does not provide a “full outer” join but we can implement it by combining two left joins. Note: Although relational database management systems (RDBMSs) adapt mostly the same SQL syntax, there might be small differences. Thus, it is better to check the documentation of a particular RDBMS to see if it supports full outer joins. In MySQL, here is how a full outer join can be achieved with two left joins: mysql> select cust.*, purc.* -> from cust left join purc -> on cust.id = purc.id -> union -> select cust.*, purc.* -> from purc left join cust -> on cust.id = purc.id;+------+------+------+------+--------+--------+| id | age | ctg | id | ticket | amount |+------+------+------+------+--------+--------+| 3 | 22 | B | 3 | 1001 | 24.10 || 4 | 29 | C | 4 | 1002 | 32.50 || 5 | 17 | B | 5 | 1003 | 34.80 || 1 | 34 | A | NULL | NULL | NULL || 2 | 28 | A | NULL | NULL | NULL || NULL | NULL | NULL | 6 | 1004 | 19.50 || NULL | NULL | NULL | 7 | 1005 | 26.20 |+------+------+------+------+--------+--------+ The union operator stacks the results of multiple queries. It is similar to the concat function of Pandas. Merging or joining is not just about combining data. We can use them as a tool for data analysis. For instance, we can calculate the total order amount for each category (“ctg”). Pandas: cust.merge(purc, on='id', how='left')[['ctg','amount']]\.groupby('ctg').mean() ctg amount-------------- A NaN B 29.45 C 32.50 SQL: mysql> select cust.ctg, sum(purc.amount) -> from cust -> left join purc -> on cust.id = purc.id -> group by cust.ctg;+------+------------------+| ctg | sum(purc.amount) |+------+------------------+| A | NULL || B | 58.90 || C | 32.50 |+------+------------------+ Since the purc table does not contain any purchases that belong to customers in category A, the sum turns out to be Null. We can also filter rows based on a condition before combining. Let’s assume we need to find the purchase amounts of customers who are younger than 25. Pandas: We first filter the dataframe and then apply the merge function. cust[cust.age < 25].merge(purc, on='id', how='left')[['age','amount']] age amount 0 22 24.1 1 17 34.8 SQL: We just implement a where clause to specify the condition for filtering. mysql> select cust.age, purc.amount -> from cust -> join purc -> on cust.id = purc.id -> where cust.age < 25;+------+--------+| age | amount |+------+--------+| 22 | 24.10 || 17 | 34.80 |+------+--------+ We have covered some examples to demonstrate the differences and similarities between Pandas merge function and SQL joins. The examples can be considered as simple cases but they help you build the intuition and understand the basics. After you comprehend the basics, you can build your way up to more advanced operations. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 405, "s": 171, "text": "Recently, I have written several articles that focus on the comparison of tools and frameworks used in the data science ecosystem such as Pandas vs dplyr, SQL vs NoSQL, Pandas vs SQL, Seaborn vs ggplot2, Seaborn vs Altair, and so on." }, { "code": null, "e": 677, "s": 405, "text": "In these articles, I focus on how a given task can be accomplished with different tools. I clearly see the differences as well as the similarities between them. Furthermore, it helps to build an intuition about how the creators of such tools approach particular problems." }, { "code": null, "e": 971, "s": 677, "text": "The focus of this article is to compare Pandas and SQL in terms of the merge and join operations. Pandas is a data analysis and manipulation library for Python. SQL is a programming language used to manage data in relational databases. Both work on tabular data with labelled rows and columns." }, { "code": null, "e": 1235, "s": 971, "text": "The merge function of Pandas combines dataframes based on values in common columns. The same operation is done by joins in SQL. These are very useful operations especially when we have data about an observation (i.e. data point) in different dataframes of tables." }, { "code": null, "e": 1335, "s": 1235, "text": "I have created two simple dataframes and tables to illustrate merging and joining through examples." }, { "code": null, "e": 1437, "s": 1335, "text": "The “cust” contains 3 pieces of information about 5 customers. The columns are id, age, and category." }, { "code": null, "e": 1517, "s": 1437, "text": "The “purc” contains the ids of customers, ticket numbers, and purchase amounts." }, { "code": null, "e": 1593, "s": 1517, "text": "The id is the common column so we will be using it when merging or joining." }, { "code": null, "e": 1761, "s": 1593, "text": "You may have noticed that the id columns are not exactly the same. Some of the values exist in only one dataframe. We will see the ways to handle them in the examples." }, { "code": null, "e": 1929, "s": 1761, "text": "The first example is to merge or join based on the shared values in the id column. The default settings accomplish this task so we do not need to adjust any parameter." }, { "code": null, "e": 1937, "s": 1929, "text": "Pandas:" }, { "code": null, "e": 1982, "s": 1937, "text": "import pandas as pdcust.merge(purc, on='id')" }, { "code": null, "e": 1987, "s": 1982, "text": "SQL:" }, { "code": null, "e": 2400, "s": 1987, "text": "mysql> select cust.*, purc.* -> from cust join purc -> on cust.id = purc.id;+------+------+------+------+--------+--------+| id | age | ctg | id | ticket | amount |+------+------+------+------+--------+--------+| 3 | 22 | B | 3 | 1001 | 24.10 || 4 | 29 | C | 4 | 1002 | 32.50 || 5 | 17 | B | 5 | 1003 | 34.80 |+------+------+------+------+--------+--------+" }, { "code": null, "e": 2571, "s": 2400, "text": "The merge function of Pandas does not return duplicate columns. On the hand, the id column is duplicated in SQL join if we select all of the columns (“*”) in both tables." }, { "code": null, "e": 2779, "s": 2571, "text": "Let’s say we want to have all the rows in the left table and only the matching rows in the right table. In Pandas, the on parameter is changed to “left”. In SQL, we use “left join” instead of “join” keyword." }, { "code": null, "e": 2787, "s": 2779, "text": "Pandas:" }, { "code": null, "e": 2825, "s": 2787, "text": "cust.merge(purc, on='id', how='left')" }, { "code": null, "e": 2830, "s": 2825, "text": "SQL:" }, { "code": null, "e": 3347, "s": 2830, "text": "mysql> select cust.*, purc.* -> from cust -> left join purc -> on cust.id = purc.id;+------+------+------+------+--------+--------+| id | age | ctg | id | ticket | amount |+------+------+------+------+--------+--------+| 3 | 22 | B | 3 | 1001 | 24.10 || 4 | 29 | C | 4 | 1002 | 32.50 || 5 | 17 | B | 5 | 1003 | 34.80 || 1 | 34 | A | NULL | NULL | NULL || 2 | 28 | A | NULL | NULL | NULL |+------+------+------+------+--------+--------+" }, { "code": null, "e": 3496, "s": 3347, "text": "The purc dataframe and table do not have rows in which the id is 1 or 2. Thus, the columns from the purc are filled with Null values for these rows." }, { "code": null, "e": 3628, "s": 3496, "text": "We can do the same for the right dataframe using “right” argument for the on parameter. Similarly, the “right join” is used in SQL." }, { "code": null, "e": 3694, "s": 3628, "text": "What if we want to see all the rows in both dataframes or tables?" }, { "code": null, "e": 3702, "s": 3694, "text": "Pandas:" }, { "code": null, "e": 3813, "s": 3702, "text": "It is a straightforward operation in Pandas which can be done by passing ‘outer’ argument to the on parameter." }, { "code": null, "e": 3852, "s": 3813, "text": "cust.merge(purc, on='id', how='outer')" }, { "code": null, "e": 3857, "s": 3852, "text": "SQL:" }, { "code": null, "e": 3953, "s": 3857, "text": "MySQL does not provide a “full outer” join but we can implement it by combining two left joins." }, { "code": null, "e": 4192, "s": 3953, "text": "Note: Although relational database management systems (RDBMSs) adapt mostly the same SQL syntax, there might be small differences. Thus, it is better to check the documentation of a particular RDBMS to see if it supports full outer joins." }, { "code": null, "e": 4269, "s": 4192, "text": "In MySQL, here is how a full outer join can be achieved with two left joins:" }, { "code": null, "e": 4972, "s": 4269, "text": "mysql> select cust.*, purc.* -> from cust left join purc -> on cust.id = purc.id -> union -> select cust.*, purc.* -> from purc left join cust -> on cust.id = purc.id;+------+------+------+------+--------+--------+| id | age | ctg | id | ticket | amount |+------+------+------+------+--------+--------+| 3 | 22 | B | 3 | 1001 | 24.10 || 4 | 29 | C | 4 | 1002 | 32.50 || 5 | 17 | B | 5 | 1003 | 34.80 || 1 | 34 | A | NULL | NULL | NULL || 2 | 28 | A | NULL | NULL | NULL || NULL | NULL | NULL | 6 | 1004 | 19.50 || NULL | NULL | NULL | 7 | 1005 | 26.20 |+------+------+------+------+--------+--------+" }, { "code": null, "e": 5079, "s": 4972, "text": "The union operator stacks the results of multiple queries. It is similar to the concat function of Pandas." }, { "code": null, "e": 5258, "s": 5079, "text": "Merging or joining is not just about combining data. We can use them as a tool for data analysis. For instance, we can calculate the total order amount for each category (“ctg”)." }, { "code": null, "e": 5266, "s": 5258, "text": "Pandas:" }, { "code": null, "e": 5489, "s": 5266, "text": "cust.merge(purc, on='id', how='left')[['ctg','amount']]\\.groupby('ctg').mean() ctg amount-------------- A NaN B 29.45 C 32.50" }, { "code": null, "e": 5494, "s": 5489, "text": "SQL:" }, { "code": null, "e": 5813, "s": 5494, "text": "mysql> select cust.ctg, sum(purc.amount) -> from cust -> left join purc -> on cust.id = purc.id -> group by cust.ctg;+------+------------------+| ctg | sum(purc.amount) |+------+------------------+| A | NULL || B | 58.90 || C | 32.50 |+------+------------------+" }, { "code": null, "e": 5935, "s": 5813, "text": "Since the purc table does not contain any purchases that belong to customers in category A, the sum turns out to be Null." }, { "code": null, "e": 6086, "s": 5935, "text": "We can also filter rows based on a condition before combining. Let’s assume we need to find the purchase amounts of customers who are younger than 25." }, { "code": null, "e": 6094, "s": 6086, "text": "Pandas:" }, { "code": null, "e": 6159, "s": 6094, "text": "We first filter the dataframe and then apply the merge function." }, { "code": null, "e": 6333, "s": 6159, "text": "cust[cust.age < 25].merge(purc, on='id', how='left')[['age','amount']] age amount 0 22 24.1 1 17 34.8" }, { "code": null, "e": 6338, "s": 6333, "text": "SQL:" }, { "code": null, "e": 6411, "s": 6338, "text": "We just implement a where clause to specify the condition for filtering." }, { "code": null, "e": 6635, "s": 6411, "text": "mysql> select cust.age, purc.amount -> from cust -> join purc -> on cust.id = purc.id -> where cust.age < 25;+------+--------+| age | amount |+------+--------+| 22 | 24.10 || 17 | 34.80 |+------+--------+" }, { "code": null, "e": 6758, "s": 6635, "text": "We have covered some examples to demonstrate the differences and similarities between Pandas merge function and SQL joins." }, { "code": null, "e": 6958, "s": 6758, "text": "The examples can be considered as simple cases but they help you build the intuition and understand the basics. After you comprehend the basics, you can build your way up to more advanced operations." } ]
Bresenham’s Line Generation Algorithm - GeeksforGeeks
10 Mar, 2022 Given coordinate of two points A(x1, y1) and B(x2, y2). The task to find all the intermediate points required for drawing line AB on the computer screen of pixels. Note that every pixel has integer coordinates.Examples: Input : A(0,0), B(4,4) Output : (0,0), (1,1), (2,2), (3,3), (4,4) Input : A(0,0), B(4,2) Output : (0,0), (1,0), (2,1), (3,1), (4,2) Below are some assumptions to keep algorithm simple. We draw line from left to right.x1 < x2 and y1< y2Slope of the line is between 0 and 1. We draw a line from lower left to upper right. We draw line from left to right. x1 < x2 and y1< y2 Slope of the line is between 0 and 1. We draw a line from lower left to upper right. Let us understand the process by considering the naive way first. // A naive way of drawing line void naiveDrawLine(x1, x2, y1, y2) { m = (y2 - y1)/(x2 - x1) for (x = x1; x <= x2; x++) { // Assuming that the round function finds // closest integer to a given float. y = round(mx + c); print(x, y); } } Above algorithm works, but it is slow. The idea of Bresenham’s algorithm is to avoid floating point multiplication and addition to compute mx + c, and then computing round value of (mx + c) in every step. In Bresenham’s algorithm, we move across the x-axis in unit intervals. We always increase x by 1, and we choose about next y, whether we need to go to y+1 or remain on y. In other words, from any position (Xk, Yk) we need to choose between (Xk + 1, Yk) and (Xk + 1, Yk + 1). We always increase x by 1, and we choose about next y, whether we need to go to y+1 or remain on y. In other words, from any position (Xk, Yk) we need to choose between (Xk + 1, Yk) and (Xk + 1, Yk + 1). We would like to pick the y value (among Yk + 1 and Yk) corresponding to a point that is closer to the original line. We would like to pick the y value (among Yk + 1 and Yk) corresponding to a point that is closer to the original line. We need to a decision parameter to decide whether to pick Yk + 1 or Yk as next point. The idea is to keep track of slope error from previous increment to y. If the slope error becomes greater than 0.5, we know that the line has moved upwards one pixel, and that we must increment our y coordinate and readjust the error to represent the distance from the top of the new pixel – which is done by subtracting one from error. // Modifying the naive way to use a parameter // to decide next y. void withDecisionParameter(x1, x2, y1, y2) { m = (y2 - y1)/(x2 - x1) slope_error = [Some Initial Value] for (x = x1, y = y1; x = 0.5) { y++; slope_error -= 1.0; } } How to avoid floating point arithmetic The above algorithm still includes floating point arithmetic. To avoid floating point arithmetic, consider the value below value m.m = (y2 – y1)/(x2 – x1)We multiply both sides by (x2 – x1)We also change slope_error to slope_error * (x2 – x1). To avoid comparison with 0.5, we further change it to slope_error * (x2 – x1) * 2. Also, it is generally preferred to compare with 0 than 1. // Modifying the above algorithm to avoid floating // point arithmetic and use comparison with 0. void bresenham(x1, x2, y1, y2) { m_new = 2 * (y2 - y1) slope_error_new = [Some Initial Value] for (x = x1, y = y1; x = 0) { y++; slope_error_new -= 2 * (x2 - x1); } } The initial value of slope_error_new is 2*(y2 – y1) – (x2 – x1). Refer this for proof of this valueBelow is the implementation of above algorithm. C++ Java Python3 C# PHP Javascript // C++ program for Bresenham’s Line Generation// Assumptions :// 1) Line is drawn from left to right.// 2) x1 < x2 and y1 < y2// 3) Slope of the line is between 0 and 1.// We draw a line from lower left to upper// right.#include<bits/stdc++.h>using namespace std; // function for line generationvoid bresenham(int x1, int y1, int x2, int y2){ int m_new = 2 * (y2 - y1); int slope_error_new = m_new - (x2 - x1); for (int x = x1, y = y1; x <= x2; x++) { cout << "(" << x << "," << y << ")\n"; // Add slope to increment angle formed slope_error_new += m_new; // Slope error reached limit, time to // increment y and update slope error. if (slope_error_new >= 0) { y++; slope_error_new -= 2 * (x2 - x1); } }} // driver functionint main(){ int x1 = 3, y1 = 2, x2 = 15, y2 = 5; bresenham(x1, y1, x2, y2); return 0;} // Java program for Bresenhams Line Generation// Assumptions :// 1) Line is drawn from left to right.// 2) x1 < x2 and y1 < y2// 3) Slope of the line is between 0 and 1.// We draw a line from lower left to upper// right.class GFG{ // function for line generation static void bresenham(int x1, int y1, int x2, int y2) { int m_new = 2 * (y2 - y1); int slope_error_new = m_new - (x2 - x1); for (int x = x1, y = y1; x <= x2; x++) { System.out.print("(" +x + "," + y + ")\n"); // Add slope to increment angle formed slope_error_new += m_new; // Slope error reached limit, time to // increment y and update slope error. if (slope_error_new >= 0) { y++; slope_error_new -= 2 * (x2 - x1); } } } // Driver code public static void main (String[] args) { int x1 = 3, y1 = 2, x2 = 15, y2 = 5; bresenham(x1, y1, x2, y2); }} // This code is contributed by Anant Agarwal. # Python 3 program for Bresenham’s Line Generation# Assumptions :# 1) Line is drawn from left to right.# 2) x1 < x2 and y1 < y2# 3) Slope of the line is between 0 and 1.# We draw a line from lower left to upper# right. # function for line generationdef bresenham(x1,y1,x2, y2): m_new = 2 * (y2 - y1) slope_error_new = m_new - (x2 - x1) y=y1 for x in range(x1,x2+1): print("(",x ,",",y ,")\n") # Add slope to increment angle formed slope_error_new =slope_error_new + m_new # Slope error reached limit, time to # increment y and update slope error. if (slope_error_new >= 0): y=y+1 slope_error_new =slope_error_new - 2 * (x2 - x1) # driver functionif __name__=='__main__': x1 = 3 y1 = 2 x2 = 15 y2 = 5 bresenham(x1, y1, x2, y2) #This code is contributed by ash264 // C# program for Bresenhams Line Generation// Assumptions :// 1) Line is drawn from left to right.// 2) x1 < x2 and y1< y2// 3) Slope of the line is between 0 and 1.// We draw a line from lower left to upper// right.using System; class GFG { // function for line generation static void bresenham(int x1, int y1, int x2, int y2) { int m_new = 2 * (y2 - y1); int slope_error_new = m_new - (x2 - x1); for (int x = x1, y = y1; x <= x2; x++) { Console.Write("(" + x + "," + y + ")\n"); // Add slope to increment angle formed slope_error_new += m_new; // Slope error reached limit, time to // increment y and update slope error. if (slope_error_new >= 0) { y++; slope_error_new -= 2 * (x2 - x1); } } } // Driver code public static void Main () { int x1 = 3, y1 = 2, x2 = 15, y2 = 5; bresenham(x1, y1, x2, y2); }} // This code is contributed by nitin mittal. <?php// PHP program for Bresenham’s// Line Generation Assumptions : // 1) Line is drawn from// left to right.// 2) x1 < x2 and y1 < y2// 3) Slope of the line is// between 0 and 1.// We draw a line from lower// left to upper right. // function for line generationfunction bresenham($x1, $y1, $x2, $y2){$m_new = 2 * ($y2 - $y1);$slope_error_new = $m_new - ($x2 - $x1);for ($x = $x1, $y = $y1; $x <= $x2; $x++){ echo "(" ,$x , "," , $y, ")\n"; // Add slope to increment // angle formed $slope_error_new += $m_new; // Slope error reached limit, // time to increment y and // update slope error. if ($slope_error_new >= 0) { $y++; $slope_error_new -= 2 * ($x2 - $x1); }}} // Driver Code$x1 = 3; $y1 = 2; $x2 = 15; $y2 = 5;bresenham($x1, $y1, $x2, $y2); // This code is contributed by nitin mittal.?> <script> // javascript program for Bresenhams Line Generation// Assumptions :// 1) Line is drawn from left to right.// 2) x1 < x2 and y1 < y2// 3) Slope of the line is between 0 and 1.// We draw a line from lower left to upper// right. // function for line generation function bresenham(x1 , y1 , x2,y2) { var m_new = 2 * (y2 - y1); var slope_error_new = m_new - (x2 - x1); for (x = x1, y = y1; x <= x2; x++) { document.write("(" +x + "," + y + ")<br>"); // Add slope to increment angle formed slope_error_new += m_new; // Slope error reached limit, time to // increment y and update slope error. if (slope_error_new >= 0) { y++; slope_error_new -= 2 * (x2 - x1); } } } // Driver code var x1 = 3, y1 = 2, x2 = 15, y2 = 5; bresenham(x1, y1, x2, y2); // This code is contributed by Amit Katiyar </script> Output : (3,2) (4,3) (5,3) (6,3) (7,3) (8,4) (9,4) (10,4) (11,4) (12,5) (13,5) (14,5) (15,5) Time Complexity: O(x2 – x1)Auxiliary Space: O(1) The above explanation is to provides a rough idea behind the algorithm. For detailed explanation and proof, readers can refer below references. The above program only works if the slope of line is less than 1. Here is a program implementation for any kind of slope. C++ #include <iostream>//#include <graphics.h>//Uncomment the graphics library functions if you are using itusing namespace std; void plotPixel(int x1, int y1, int x2, int y2, int dx, int dy, int decide){ //pk is initial decision making parameter //Note:x1&y1,x2&y2, dx&dy values are interchanged //and passed in plotPixel function so //it can handle both cases when m>1 & m<1 int pk = 2 * dy - dx; for (int i = 0; i <= dx; i++) { cout << x1 << "," << y1 << endl; //checking either to decrement or increment the value //if we have to plot from (0,100) to (100,0) x1 < x2 ? x1++ : x1--; if (pk < 0) { //decision value will decide to plot //either x1 or y1 in x's position if (decide == 0) { // putpixel(x1, y1, RED); pk = pk + 2 * dy; } else { //(y1,x1) is passed in xt // putpixel(y1, x1, YELLOW); pk = pk + 2 * dy; } } else { y1 < y2 ? y1++ : y1--; if (decide == 0) { //putpixel(x1, y1, RED); } else { // putpixel(y1, x1, YELLOW); } pk = pk + 2 * dy - 2 * dx; } }} int main(){ // int gd = DETECT, gm; // initgraph(&gd, &gm, "xxx"); int x1 = 100, y1 = 110, x2 = 125, y2 = 120, dx, dy, pk; //cin cout dx = abs(x2 - x1); dy = abs(y2 - y1); //If slope is less than one if (dx > dy) { //passing argument as 0 to plot(x,y) plotPixel(x1, y1, x2, y2, dx, dy, 0); } //if slope is greater than or equal to 1 else { //passing argument as 1 to plot (y,x) plotPixel(y1, x1, y2, x2, dy, dx, 1); } // getch();} 100,110 101,110 102,111 103,111 104,112 105,112 106,112 107,113 108,113 109,114 110,114 111,114 112,115 113,115 114,116 115,116 116,116 117,117 118,117 119,118 120,118 121,118 122,119 123,119 124,120 125,120 Related Articles: Mid-Point Line Generation AlgorithmDDA algorithm for line drawing Mid-Point Line Generation Algorithm DDA algorithm for line drawing Reference : https://csustan.csustan.edu/~tom/Lecture-Notes/Graphics/Bresenham-Line/Bresenham-Line.pdf https://en.wikipedia.org/wiki/Bresenham’s_line_algorithm http://graphics.idav.ucdavis.edu/education/GraphicsNotes/Bresenhams-Algorithm.pdfThis article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal ash264 gurrrung amit143katiyar pankajsharmagfg ozonewagle998 simmytarika5 surinderdawra388 computer-graphics Algorithms Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar How to Start Learning DSA? Understanding Time Complexity with Simple Examples Introduction to Algorithms How to write a Pseudo Code? Playfair Cipher with Examples Recursive Practice Problems with Solutions Difference between NP hard and NP complete problem Quick Sort vs Merge Sort
[ { "code": null, "e": 25961, "s": 25933, "text": "\n10 Mar, 2022" }, { "code": null, "e": 26183, "s": 25961, "text": "Given coordinate of two points A(x1, y1) and B(x2, y2). The task to find all the intermediate points required for drawing line AB on the computer screen of pixels. Note that every pixel has integer coordinates.Examples: " }, { "code": null, "e": 26318, "s": 26183, "text": "Input : A(0,0), B(4,4)\nOutput : (0,0), (1,1), (2,2), (3,3), (4,4)\n\nInput : A(0,0), B(4,2)\nOutput : (0,0), (1,0), (2,1), (3,1), (4,2)" }, { "code": null, "e": 26373, "s": 26318, "text": "Below are some assumptions to keep algorithm simple. " }, { "code": null, "e": 26508, "s": 26373, "text": "We draw line from left to right.x1 < x2 and y1< y2Slope of the line is between 0 and 1. We draw a line from lower left to upper right." }, { "code": null, "e": 26541, "s": 26508, "text": "We draw line from left to right." }, { "code": null, "e": 26560, "s": 26541, "text": "x1 < x2 and y1< y2" }, { "code": null, "e": 26645, "s": 26560, "text": "Slope of the line is between 0 and 1. We draw a line from lower left to upper right." }, { "code": null, "e": 26713, "s": 26645, "text": "Let us understand the process by considering the naive way first. " }, { "code": null, "e": 26996, "s": 26713, "text": "// A naive way of drawing line\nvoid naiveDrawLine(x1, x2, y1, y2)\n{\n m = (y2 - y1)/(x2 - x1)\n for (x = x1; x <= x2; x++) \n { \n // Assuming that the round function finds\n // closest integer to a given float.\n y = round(mx + c); \n print(x, y); \n }\n}" }, { "code": null, "e": 27274, "s": 26996, "text": "Above algorithm works, but it is slow. The idea of Bresenham’s algorithm is to avoid floating point multiplication and addition to compute mx + c, and then computing round value of (mx + c) in every step. In Bresenham’s algorithm, we move across the x-axis in unit intervals. " }, { "code": null, "e": 27480, "s": 27274, "text": "We always increase x by 1, and we choose about next y, whether we need to go to y+1 or remain on y. In other words, from any position (Xk, Yk) we need to choose between (Xk + 1, Yk) and (Xk + 1, Yk + 1). " }, { "code": null, "e": 27686, "s": 27480, "text": "We always increase x by 1, and we choose about next y, whether we need to go to y+1 or remain on y. In other words, from any position (Xk, Yk) we need to choose between (Xk + 1, Yk) and (Xk + 1, Yk + 1). " }, { "code": null, "e": 27804, "s": 27686, "text": "We would like to pick the y value (among Yk + 1 and Yk) corresponding to a point that is closer to the original line." }, { "code": null, "e": 27922, "s": 27804, "text": "We would like to pick the y value (among Yk + 1 and Yk) corresponding to a point that is closer to the original line." }, { "code": null, "e": 28346, "s": 27922, "text": "We need to a decision parameter to decide whether to pick Yk + 1 or Yk as next point. The idea is to keep track of slope error from previous increment to y. If the slope error becomes greater than 0.5, we know that the line has moved upwards one pixel, and that we must increment our y coordinate and readjust the error to represent the distance from the top of the new pixel – which is done by subtracting one from error. " }, { "code": null, "e": 28626, "s": 28346, "text": "// Modifying the naive way to use a parameter\n// to decide next y.\nvoid withDecisionParameter(x1, x2, y1, y2)\n{\n m = (y2 - y1)/(x2 - x1)\n slope_error = [Some Initial Value]\n for (x = x1, y = y1; x = 0.5) \n { \n y++; \n slope_error -= 1.0; \n }\n}" }, { "code": null, "e": 29052, "s": 28626, "text": "How to avoid floating point arithmetic The above algorithm still includes floating point arithmetic. To avoid floating point arithmetic, consider the value below value m.m = (y2 – y1)/(x2 – x1)We multiply both sides by (x2 – x1)We also change slope_error to slope_error * (x2 – x1). To avoid comparison with 0.5, we further change it to slope_error * (x2 – x1) * 2. Also, it is generally preferred to compare with 0 than 1. " }, { "code": null, "e": 29366, "s": 29052, "text": "// Modifying the above algorithm to avoid floating \n// point arithmetic and use comparison with 0.\nvoid bresenham(x1, x2, y1, y2)\n{\n m_new = 2 * (y2 - y1)\n slope_error_new = [Some Initial Value]\n for (x = x1, y = y1; x = 0) \n { \n y++; \n slope_error_new -= 2 * (x2 - x1); \n }\n}" }, { "code": null, "e": 29515, "s": 29366, "text": "The initial value of slope_error_new is 2*(y2 – y1) – (x2 – x1). Refer this for proof of this valueBelow is the implementation of above algorithm. " }, { "code": null, "e": 29519, "s": 29515, "text": "C++" }, { "code": null, "e": 29524, "s": 29519, "text": "Java" }, { "code": null, "e": 29532, "s": 29524, "text": "Python3" }, { "code": null, "e": 29535, "s": 29532, "text": "C#" }, { "code": null, "e": 29539, "s": 29535, "text": "PHP" }, { "code": null, "e": 29550, "s": 29539, "text": "Javascript" }, { "code": "// C++ program for Bresenham’s Line Generation// Assumptions :// 1) Line is drawn from left to right.// 2) x1 < x2 and y1 < y2// 3) Slope of the line is between 0 and 1.// We draw a line from lower left to upper// right.#include<bits/stdc++.h>using namespace std; // function for line generationvoid bresenham(int x1, int y1, int x2, int y2){ int m_new = 2 * (y2 - y1); int slope_error_new = m_new - (x2 - x1); for (int x = x1, y = y1; x <= x2; x++) { cout << \"(\" << x << \",\" << y << \")\\n\"; // Add slope to increment angle formed slope_error_new += m_new; // Slope error reached limit, time to // increment y and update slope error. if (slope_error_new >= 0) { y++; slope_error_new -= 2 * (x2 - x1); } }} // driver functionint main(){ int x1 = 3, y1 = 2, x2 = 15, y2 = 5; bresenham(x1, y1, x2, y2); return 0;}", "e": 30446, "s": 29550, "text": null }, { "code": "// Java program for Bresenhams Line Generation// Assumptions :// 1) Line is drawn from left to right.// 2) x1 < x2 and y1 < y2// 3) Slope of the line is between 0 and 1.// We draw a line from lower left to upper// right.class GFG{ // function for line generation static void bresenham(int x1, int y1, int x2, int y2) { int m_new = 2 * (y2 - y1); int slope_error_new = m_new - (x2 - x1); for (int x = x1, y = y1; x <= x2; x++) { System.out.print(\"(\" +x + \",\" + y + \")\\n\"); // Add slope to increment angle formed slope_error_new += m_new; // Slope error reached limit, time to // increment y and update slope error. if (slope_error_new >= 0) { y++; slope_error_new -= 2 * (x2 - x1); } } } // Driver code public static void main (String[] args) { int x1 = 3, y1 = 2, x2 = 15, y2 = 5; bresenham(x1, y1, x2, y2); }} // This code is contributed by Anant Agarwal.", "e": 31553, "s": 30446, "text": null }, { "code": "# Python 3 program for Bresenham’s Line Generation# Assumptions :# 1) Line is drawn from left to right.# 2) x1 < x2 and y1 < y2# 3) Slope of the line is between 0 and 1.# We draw a line from lower left to upper# right. # function for line generationdef bresenham(x1,y1,x2, y2): m_new = 2 * (y2 - y1) slope_error_new = m_new - (x2 - x1) y=y1 for x in range(x1,x2+1): print(\"(\",x ,\",\",y ,\")\\n\") # Add slope to increment angle formed slope_error_new =slope_error_new + m_new # Slope error reached limit, time to # increment y and update slope error. if (slope_error_new >= 0): y=y+1 slope_error_new =slope_error_new - 2 * (x2 - x1) # driver functionif __name__=='__main__': x1 = 3 y1 = 2 x2 = 15 y2 = 5 bresenham(x1, y1, x2, y2) #This code is contributed by ash264", "e": 32431, "s": 31553, "text": null }, { "code": "// C# program for Bresenhams Line Generation// Assumptions :// 1) Line is drawn from left to right.// 2) x1 < x2 and y1< y2// 3) Slope of the line is between 0 and 1.// We draw a line from lower left to upper// right.using System; class GFG { // function for line generation static void bresenham(int x1, int y1, int x2, int y2) { int m_new = 2 * (y2 - y1); int slope_error_new = m_new - (x2 - x1); for (int x = x1, y = y1; x <= x2; x++) { Console.Write(\"(\" + x + \",\" + y + \")\\n\"); // Add slope to increment angle formed slope_error_new += m_new; // Slope error reached limit, time to // increment y and update slope error. if (slope_error_new >= 0) { y++; slope_error_new -= 2 * (x2 - x1); } } } // Driver code public static void Main () { int x1 = 3, y1 = 2, x2 = 15, y2 = 5; bresenham(x1, y1, x2, y2); }} // This code is contributed by nitin mittal.", "e": 33553, "s": 32431, "text": null }, { "code": "<?php// PHP program for Bresenham’s// Line Generation Assumptions : // 1) Line is drawn from// left to right.// 2) x1 < x2 and y1 < y2// 3) Slope of the line is// between 0 and 1.// We draw a line from lower// left to upper right. // function for line generationfunction bresenham($x1, $y1, $x2, $y2){$m_new = 2 * ($y2 - $y1);$slope_error_new = $m_new - ($x2 - $x1);for ($x = $x1, $y = $y1; $x <= $x2; $x++){ echo \"(\" ,$x , \",\" , $y, \")\\n\"; // Add slope to increment // angle formed $slope_error_new += $m_new; // Slope error reached limit, // time to increment y and // update slope error. if ($slope_error_new >= 0) { $y++; $slope_error_new -= 2 * ($x2 - $x1); }}} // Driver Code$x1 = 3; $y1 = 2; $x2 = 15; $y2 = 5;bresenham($x1, $y1, $x2, $y2); // This code is contributed by nitin mittal.?>", "e": 34394, "s": 33553, "text": null }, { "code": "<script> // javascript program for Bresenhams Line Generation// Assumptions :// 1) Line is drawn from left to right.// 2) x1 < x2 and y1 < y2// 3) Slope of the line is between 0 and 1.// We draw a line from lower left to upper// right. // function for line generation function bresenham(x1 , y1 , x2,y2) { var m_new = 2 * (y2 - y1); var slope_error_new = m_new - (x2 - x1); for (x = x1, y = y1; x <= x2; x++) { document.write(\"(\" +x + \",\" + y + \")<br>\"); // Add slope to increment angle formed slope_error_new += m_new; // Slope error reached limit, time to // increment y and update slope error. if (slope_error_new >= 0) { y++; slope_error_new -= 2 * (x2 - x1); } } } // Driver code var x1 = 3, y1 = 2, x2 = 15, y2 = 5; bresenham(x1, y1, x2, y2); // This code is contributed by Amit Katiyar </script>", "e": 35384, "s": 34394, "text": null }, { "code": null, "e": 35394, "s": 35384, "text": "Output : " }, { "code": null, "e": 35479, "s": 35394, "text": "(3,2)\n(4,3)\n(5,3)\n(6,3)\n(7,3)\n(8,4)\n(9,4)\n(10,4)\n(11,4)\n(12,5)\n(13,5)\n(14,5)\n(15,5) " }, { "code": null, "e": 35672, "s": 35479, "text": "Time Complexity: O(x2 – x1)Auxiliary Space: O(1) The above explanation is to provides a rough idea behind the algorithm. For detailed explanation and proof, readers can refer below references." }, { "code": null, "e": 35794, "s": 35672, "text": "The above program only works if the slope of line is less than 1. Here is a program implementation for any kind of slope." }, { "code": null, "e": 35798, "s": 35794, "text": "C++" }, { "code": "#include <iostream>//#include <graphics.h>//Uncomment the graphics library functions if you are using itusing namespace std; void plotPixel(int x1, int y1, int x2, int y2, int dx, int dy, int decide){ //pk is initial decision making parameter //Note:x1&y1,x2&y2, dx&dy values are interchanged //and passed in plotPixel function so //it can handle both cases when m>1 & m<1 int pk = 2 * dy - dx; for (int i = 0; i <= dx; i++) { cout << x1 << \",\" << y1 << endl; //checking either to decrement or increment the value //if we have to plot from (0,100) to (100,0) x1 < x2 ? x1++ : x1--; if (pk < 0) { //decision value will decide to plot //either x1 or y1 in x's position if (decide == 0) { // putpixel(x1, y1, RED); pk = pk + 2 * dy; } else { //(y1,x1) is passed in xt // putpixel(y1, x1, YELLOW); pk = pk + 2 * dy; } } else { y1 < y2 ? y1++ : y1--; if (decide == 0) { //putpixel(x1, y1, RED); } else { // putpixel(y1, x1, YELLOW); } pk = pk + 2 * dy - 2 * dx; } }} int main(){ // int gd = DETECT, gm; // initgraph(&gd, &gm, \"xxx\"); int x1 = 100, y1 = 110, x2 = 125, y2 = 120, dx, dy, pk; //cin cout dx = abs(x2 - x1); dy = abs(y2 - y1); //If slope is less than one if (dx > dy) { //passing argument as 0 to plot(x,y) plotPixel(x1, y1, x2, y2, dx, dy, 0); } //if slope is greater than or equal to 1 else { //passing argument as 1 to plot (y,x) plotPixel(y1, x1, y2, x2, dy, dx, 1); } // getch();}", "e": 37635, "s": 35798, "text": null }, { "code": null, "e": 37843, "s": 37635, "text": "100,110\n101,110\n102,111\n103,111\n104,112\n105,112\n106,112\n107,113\n108,113\n109,114\n110,114\n111,114\n112,115\n113,115\n114,116\n115,116\n116,116\n117,117\n118,117\n119,118\n120,118\n121,118\n122,119\n123,119\n124,120\n125,120" }, { "code": null, "e": 37863, "s": 37843, "text": "Related Articles: " }, { "code": null, "e": 37929, "s": 37863, "text": "Mid-Point Line Generation AlgorithmDDA algorithm for line drawing" }, { "code": null, "e": 37965, "s": 37929, "text": "Mid-Point Line Generation Algorithm" }, { "code": null, "e": 37996, "s": 37965, "text": "DDA algorithm for line drawing" }, { "code": null, "e": 38672, "s": 37996, "text": "Reference : https://csustan.csustan.edu/~tom/Lecture-Notes/Graphics/Bresenham-Line/Bresenham-Line.pdf https://en.wikipedia.org/wiki/Bresenham’s_line_algorithm http://graphics.idav.ucdavis.edu/education/GraphicsNotes/Bresenhams-Algorithm.pdfThis article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 38685, "s": 38672, "text": "nitin mittal" }, { "code": null, "e": 38692, "s": 38685, "text": "ash264" }, { "code": null, "e": 38701, "s": 38692, "text": "gurrrung" }, { "code": null, "e": 38716, "s": 38701, "text": "amit143katiyar" }, { "code": null, "e": 38732, "s": 38716, "text": "pankajsharmagfg" }, { "code": null, "e": 38746, "s": 38732, "text": "ozonewagle998" }, { "code": null, "e": 38759, "s": 38746, "text": "simmytarika5" }, { "code": null, "e": 38776, "s": 38759, "text": "surinderdawra388" }, { "code": null, "e": 38794, "s": 38776, "text": "computer-graphics" }, { "code": null, "e": 38805, "s": 38794, "text": "Algorithms" }, { "code": null, "e": 38816, "s": 38805, "text": "Algorithms" }, { "code": null, "e": 38914, "s": 38816, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38963, "s": 38914, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 38988, "s": 38963, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 39015, "s": 38988, "text": "How to Start Learning DSA?" }, { "code": null, "e": 39066, "s": 39015, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 39093, "s": 39066, "text": "Introduction to Algorithms" }, { "code": null, "e": 39121, "s": 39093, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 39151, "s": 39121, "text": "Playfair Cipher with Examples" }, { "code": null, "e": 39194, "s": 39151, "text": "Recursive Practice Problems with Solutions" }, { "code": null, "e": 39245, "s": 39194, "text": "Difference between NP hard and NP complete problem" } ]
Design a Keylogger in Python
Here we are going to develop a keylogger using python. But before that, what is a keylogger? Keylogger is a program with which we monitor keystrokes. These keystrokes will be stored in a log file. We can record sensitive information like username and password using this keystroke. To create a keylogger we are going to use the pynput module. As its not the standard library of python, we might need to install it. Installing pyxhook module − I’m going to use pip to install pynput − pip install pynput Requirement already satisfied: pynput in c:\python\python361\lib\site-packages (1.4) Requirement already satisfied: six in c:\python\python361\lib\site-packages (from pynput) (1.10.0) To check our installation is successful, try to import the module in your python shell >>> import pynput >>> Once the required library is installed, import the required packages and method. To monitor the keyboard, we are going to use the key and listener method of pynput.keyboard module. We are also going to use the logging module to log our keystrokes in a file. from pynput.keyboard import Key, Listener import logging Next, we are going to set the path where we are going to store our log files, in what mode logs will be store and the format. log_dir = r"C:/users/username/desktop/" logging.basicConfig(filename = (log_dir + "keyLog.txt"), level=logging.DEBUG, format='%(asctime)s: %(message)s') Then we called the function on_press() which creates a definition for keypresses and take the key as a parameter. def on_press(key): logging.info(str(key)) The last thing we are going to do is to set up an instance of Listener and define the on_press method in it and then join the instance to the main thread. with Listener(on_press=on_press) as listener: listener.join() On combining the above mentioned step, we are in a stage to create our final program − from pynput.keyboard import Key, Listener import logging log_dir = r"C:/users/rajesh/desktop/" logging.basicConfig(filename = (log_dir + "keyLog.txt"), level=logging.DEBUG, format='%(asctime)s: %(message)s') def on_press(key): logging.info(str(key)) with Listener(on_press=on_press) as listener: listener.join() While my script is running, I tried to open a browser and type “hello world, Wikipedia”. Let’s see what happened to our log file − I can see, a “keyLog.txt” file is created in my computer desktop and if I tried to see its content I get − 2019-01-18 17:06:21,854: Key.cmd 2019-01-18 17:06:22,022: 'd' 2019-01-18 17:06:39,304: 'h' 2019-01-18 17:06:39,435: 'e' 2019-01-18 17:06:39,564: 'l' 2019-01-18 17:06:39,754: 'l' 2019-01-18 17:06:39,943: 'o' 2019-01-18 17:06:40,245: Key.space 2019-01-18 17:06:40,450: 'w' 2019-01-18 17:06:40,536: 'o' 2019-01-18 17:06:40,694: 'r' 2019-01-18 17:06:40,818: 'l' 2019-01-18 17:06:40,943: 'd' 2019-01-18 17:06:43,527: ',' 2019-01-18 17:06:44,947: Key.space 2019-01-18 17:06:45,091: 'p' 2019-01-18 17:06:45,342: 'y' 2019-01-18 17:06:45,468: 't' 2019-01-18 17:06:45,580: 'h' 2019-01-18 17:06:45,674: 'o' 2019-01-18 17:06:45,808: 'n' 2019-01-18 17:06:45,872: Key.space 2019-01-18 17:06:48,692: Key.backspace 2019-01-18 17:06:48,891: Key.backspace 2019-01-18 17:06:49,079: Key.backspace 2019-01-18 17:06:49,223: Key.backspace 2019-01-18 17:06:49,405: Key.backspace 2019-01-18 17:06:49,584: Key.backspace 2019-01-18 17:06:49,816: Key.backspace 2019-01-18 17:06:50,004: 'w' 2019-01-18 17:06:50,162: 'i' 2019-01-18 17:06:50,392: 'k' 2019-01-18 17:06:50,572: 'i' 2019-01-18 17:06:51,395: 'p' 2019-01-18 17:06:51,525: 'e' 2019-01-18 17:06:51,741: 'd' 2019-01-18 17:06:51,838: 'i' 2019-01-18 17:06:52,104: 'a' So we can see whatever I tried to type in my browser, every keystroke are stored in this file. So, we have made a very simple key logger in python here.
[ { "code": null, "e": 1344, "s": 1062, "text": "Here we are going to develop a keylogger using python. But before that, what is a keylogger? Keylogger is a program with which we monitor keystrokes. These keystrokes will be stored in a log file. We can record sensitive information like username and password using this keystroke." }, { "code": null, "e": 1477, "s": 1344, "text": "To create a keylogger we are going to use the pynput module. As its not the standard library of python, we might need to install it." }, { "code": null, "e": 1505, "s": 1477, "text": "Installing pyxhook module −" }, { "code": null, "e": 1546, "s": 1505, "text": "I’m going to use pip to install pynput −" }, { "code": null, "e": 1749, "s": 1546, "text": "pip install pynput\nRequirement already satisfied: pynput in c:\\python\\python361\\lib\\site-packages (1.4)\nRequirement already satisfied: six in c:\\python\\python361\\lib\\site-packages (from pynput) (1.10.0)" }, { "code": null, "e": 1836, "s": 1749, "text": "To check our installation is successful, try to import the module in your python shell" }, { "code": null, "e": 1858, "s": 1836, "text": ">>> import pynput\n>>>" }, { "code": null, "e": 2116, "s": 1858, "text": "Once the required library is installed, import the required packages and method. To monitor the keyboard, we are going to use the key and listener method of pynput.keyboard module. We are also going to use the logging module to log our keystrokes in a file." }, { "code": null, "e": 2173, "s": 2116, "text": "from pynput.keyboard import Key, Listener\nimport logging" }, { "code": null, "e": 2299, "s": 2173, "text": "Next, we are going to set the path where we are going to store our log files, in what mode logs will be store and the format." }, { "code": null, "e": 2452, "s": 2299, "text": "log_dir = r\"C:/users/username/desktop/\"\nlogging.basicConfig(filename = (log_dir + \"keyLog.txt\"), level=logging.DEBUG, format='%(asctime)s: %(message)s')" }, { "code": null, "e": 2566, "s": 2452, "text": "Then we called the function on_press() which creates a definition for keypresses and take the key as a parameter." }, { "code": null, "e": 2611, "s": 2566, "text": "def on_press(key):\n logging.info(str(key))" }, { "code": null, "e": 2766, "s": 2611, "text": "The last thing we are going to do is to set up an instance of Listener and define the on_press method in it and then join the instance to the main thread." }, { "code": null, "e": 2828, "s": 2766, "text": "with Listener(on_press=on_press) as listener:\nlistener.join()" }, { "code": null, "e": 2915, "s": 2828, "text": "On combining the above mentioned step, we are in a stage to create our final program −" }, { "code": null, "e": 3227, "s": 2915, "text": "from pynput.keyboard import Key, Listener\nimport logging\nlog_dir = r\"C:/users/rajesh/desktop/\"\nlogging.basicConfig(filename = (log_dir + \"keyLog.txt\"), level=logging.DEBUG, format='%(asctime)s: %(message)s')\ndef on_press(key):\nlogging.info(str(key))\nwith Listener(on_press=on_press) as listener:\nlistener.join()" }, { "code": null, "e": 3358, "s": 3227, "text": "While my script is running, I tried to open a browser and type “hello world, Wikipedia”. Let’s see what happened to our log file −" }, { "code": null, "e": 3465, "s": 3358, "text": "I can see, a “keyLog.txt” file is created in my computer desktop and if I tried to see its content I get −" }, { "code": null, "e": 4659, "s": 3465, "text": "2019-01-18 17:06:21,854: Key.cmd\n2019-01-18 17:06:22,022: 'd'\n2019-01-18 17:06:39,304: 'h'\n2019-01-18 17:06:39,435: 'e'\n2019-01-18 17:06:39,564: 'l'\n2019-01-18 17:06:39,754: 'l'\n2019-01-18 17:06:39,943: 'o'\n2019-01-18 17:06:40,245: Key.space\n2019-01-18 17:06:40,450: 'w'\n2019-01-18 17:06:40,536: 'o'\n2019-01-18 17:06:40,694: 'r'\n2019-01-18 17:06:40,818: 'l'\n2019-01-18 17:06:40,943: 'd'\n2019-01-18 17:06:43,527: ','\n2019-01-18 17:06:44,947: Key.space\n2019-01-18 17:06:45,091: 'p'\n2019-01-18 17:06:45,342: 'y'\n2019-01-18 17:06:45,468: 't'\n2019-01-18 17:06:45,580: 'h'\n2019-01-18 17:06:45,674: 'o'\n2019-01-18 17:06:45,808: 'n'\n2019-01-18 17:06:45,872: Key.space\n2019-01-18 17:06:48,692: Key.backspace\n2019-01-18 17:06:48,891: Key.backspace\n2019-01-18 17:06:49,079: Key.backspace\n2019-01-18 17:06:49,223: Key.backspace\n2019-01-18 17:06:49,405: Key.backspace\n2019-01-18 17:06:49,584: Key.backspace\n2019-01-18 17:06:49,816: Key.backspace\n2019-01-18 17:06:50,004: 'w'\n2019-01-18 17:06:50,162: 'i'\n2019-01-18 17:06:50,392: 'k'\n2019-01-18 17:06:50,572: 'i'\n2019-01-18 17:06:51,395: 'p'\n2019-01-18 17:06:51,525: 'e'\n2019-01-18 17:06:51,741: 'd'\n2019-01-18 17:06:51,838: 'i'\n2019-01-18 17:06:52,104: 'a'" }, { "code": null, "e": 4812, "s": 4659, "text": "So we can see whatever I tried to type in my browser, every keystroke are stored in this file. So, we have made a very simple key logger in python here." } ]
Django - Ajax
Ajax essentially is a combination of technologies that are integrated together to reduce the number of page loads. We generally use Ajax to ease end-user experience. Using Ajax in Django can be done by directly using an Ajax library like JQuery or others. Let's say you want to use JQuery, then you need to download and serve the library on your server through Apache or others. Then use it in your template, just like you might do while developing any Ajax-based application. Another way of using Ajax in Django is to use the Django Ajax framework. The most commonly used is django-dajax which is a powerful tool to easily and super-quickly develop asynchronous presentation logic in web applications, using Python and almost no JavaScript source code. It supports four of the most popular Ajax frameworks: Prototype, jQuery, Dojo and MooTools. First thing to do is to install django-dajax. This can be done using easy_install or pip − $ pip install django_dajax $ easy_install django_dajax This will automatically install django-dajaxice, required by django-dajax. We then need to configure both dajax and dajaxice. Add dajax and dajaxice in your project settings.py in INSTALLED_APPS option − INSTALLED_APPS += ( 'dajaxice', 'dajax' ) Make sure in the same settings.py file, you have the following − TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'django.template.loaders.eggs.Loader', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.static', 'django.core.context_processors.request', 'django.contrib.messages.context_processors.messages' ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'dajaxice.finders.DajaxiceFinder', ) DAJAXICE_MEDIA_PREFIX = 'dajaxice' Now go to the myapp/url.py file and make sure you have the following to set dajax URLs and to load dajax statics js files − from dajaxice.core import dajaxice_autodiscover, dajaxice_config from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf import settings Then dajax urls: urlpatterns += patterns('', url(r'^%s/' % settings.DAJAXICE_MEDIA_PREFIX, include('dajaxice.urls')),) urlpatterns += staticfiles_urlpatterns() Let us create a simple form based on our Dreamreal model to store it, using Ajax (means no refresh). At first, we need our Dreamreal form in myapp/form.py. class DreamrealForm(forms.Form): website = forms.CharField(max_length = 100) name = forms.CharField(max_length = 100) phonenumber = forms.CharField(max_length = 50) email = forms.CharField(max_length = 100) Then we need an ajax.py file in our application: myapp/ajax.py. That's where is our logic, that's where we put the function that will be saving our form then return the popup − from dajaxice.utils import deserialize_form from myapp.form import DreamrealForm from dajax.core import Dajax from myapp.models import Dreamreal @dajaxice_register def send_form(request, form): dajax = Dajax() form = DreamrealForm(deserialize_form(form)) if form.is_valid(): dajax.remove_css_class('#my_form input', 'error') dr = Dreamreal() dr.website = form.cleaned_data.get('website') dr.name = form.cleaned_data.get('name') dr.phonenumber = form.cleaned_data.get('phonenumber') dr.save() dajax.alert("Dreamreal Entry %s was successfully saved." % form.cleaned_data.get('name')) else: dajax.remove_css_class('#my_form input', 'error') for error in form.errors: dajax.add_css_class('#id_%s' % error, 'error') return dajax.json() Now let's create the dreamreal.html template, which has our form − <html> <head></head> <body> <form action = "" method = "post" id = "my_form" accept-charset = "utf-8"> {{ form.as_p }} <p><input type = "button" value = "Send" onclick = "send_form();"></p> </form> </body> </html> Add the view that goes with the template in myapp/views.py − def dreamreal(request): form = DreamrealForm() return render(request, 'dreamreal.html', locals()) Add the corresponding URL in myapp/urls.py − url(r'^dreamreal/', 'dreamreal', name = 'dreamreal'), Now let's add the necessary in our template to make the Ajax work − At the top of the file add − {% load static %} {% load dajaxice_templatetags %} And in the <head> section of our dreamreal.html template add − We are using the JQuery library for this example, so add − <script src = "{% static '/static/jquery-1.11.3.min.js' %}" type = "text/javascript" charset = "utf-8"></script> <script src = "{% static '/static/dajax/jquery.dajax.core.js' %}"></script> The Ajax function that will be called on click − <script> function send_form(){ Dajaxice.myapp.send_form(Dajax.process,{'form':$('#my_form').serialize(true)}); } </script> Note that you need the “jquery-1.11.3.min.js” in your static files directory, and also the jquery.dajax.core.js. To make sure all dajax static files are served under your static directory, run − $python manage.py collectstatic Note − Sometimes the jquery.dajax.core.js can be missing, if that happens, just download the source and take that file and put it under your static folder. You will get to see the following screen, upon accessing /myapp/dreamreal/ − On submit, you will get the following screen − 39 Lectures 3.5 hours John Elder 36 Lectures 2.5 hours John Elder 28 Lectures 2 hours John Elder 20 Lectures 1 hours John Elder 35 Lectures 3 hours John Elder 79 Lectures 10 hours Rathan Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 2522, "s": 2045, "text": "Ajax essentially is a combination of technologies that are integrated together to reduce the number of page loads. We generally use Ajax to ease end-user experience. Using Ajax in Django can be done by directly using an Ajax library like JQuery or others. Let's say you want to use JQuery, then you need to download and serve the library on your server through Apache or others. Then use it in your template, just like you might do while developing any Ajax-based application." }, { "code": null, "e": 2891, "s": 2522, "text": "Another way of using Ajax in Django is to use the Django Ajax framework. The most commonly used is django-dajax which is a powerful tool to easily and super-quickly develop asynchronous presentation logic in web applications, using Python and almost no JavaScript source code. It supports four of the most popular Ajax frameworks: Prototype, jQuery, Dojo and MooTools." }, { "code": null, "e": 2982, "s": 2891, "text": "First thing to do is to install django-dajax. This can be done using easy_install or pip −" }, { "code": null, "e": 3038, "s": 2982, "text": "$ pip install django_dajax\n$ easy_install django_dajax\n" }, { "code": null, "e": 3164, "s": 3038, "text": "This will automatically install django-dajaxice, required by django-dajax. We then need to configure both dajax and dajaxice." }, { "code": null, "e": 3242, "s": 3164, "text": "Add dajax and dajaxice in your project settings.py in INSTALLED_APPS option −" }, { "code": null, "e": 3290, "s": 3242, "text": "INSTALLED_APPS += (\n 'dajaxice',\n 'dajax'\n)" }, { "code": null, "e": 3355, "s": 3290, "text": "Make sure in the same settings.py file, you have the following −" }, { "code": null, "e": 4101, "s": 3355, "text": "TEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n 'django.template.loaders.eggs.Loader',\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.contrib.auth.context_processors.auth',\n 'django.core.context_processors.debug',\n 'django.core.context_processors.i18n',\n 'django.core.context_processors.media',\n 'django.core.context_processors.static',\n 'django.core.context_processors.request',\n 'django.contrib.messages.context_processors.messages'\n)\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n 'dajaxice.finders.DajaxiceFinder',\n)\n\nDAJAXICE_MEDIA_PREFIX = 'dajaxice'" }, { "code": null, "e": 4225, "s": 4101, "text": "Now go to the myapp/url.py file and make sure you have the following to set dajax URLs and to load dajax statics js files −" }, { "code": null, "e": 4558, "s": 4225, "text": "from dajaxice.core import dajaxice_autodiscover, dajaxice_config\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\nfrom django.conf import settings\n\nThen dajax urls:\n\nurlpatterns += patterns('',\n url(r'^%s/' % settings.DAJAXICE_MEDIA_PREFIX, include('dajaxice.urls')),)\n\t\nurlpatterns += staticfiles_urlpatterns()" }, { "code": null, "e": 4659, "s": 4558, "text": "Let us create a simple form based on our Dreamreal model to store it, using Ajax (means no refresh)." }, { "code": null, "e": 4714, "s": 4659, "text": "At first, we need our Dreamreal form in myapp/form.py." }, { "code": null, "e": 4933, "s": 4714, "text": "class DreamrealForm(forms.Form):\n website = forms.CharField(max_length = 100)\n name = forms.CharField(max_length = 100)\n phonenumber = forms.CharField(max_length = 50)\n email = forms.CharField(max_length = 100)" }, { "code": null, "e": 5110, "s": 4933, "text": "Then we need an ajax.py file in our application: myapp/ajax.py. That's where is our logic, that's where we put the function that will be saving our form then return the popup −" }, { "code": null, "e": 5945, "s": 5110, "text": "from dajaxice.utils import deserialize_form\nfrom myapp.form import DreamrealForm\nfrom dajax.core import Dajax\nfrom myapp.models import Dreamreal\n\n@dajaxice_register\ndef send_form(request, form):\n dajax = Dajax()\n form = DreamrealForm(deserialize_form(form))\n \n if form.is_valid():\n dajax.remove_css_class('#my_form input', 'error')\n dr = Dreamreal()\n dr.website = form.cleaned_data.get('website')\n dr.name = form.cleaned_data.get('name')\n dr.phonenumber = form.cleaned_data.get('phonenumber')\n dr.save()\n \n dajax.alert(\"Dreamreal Entry %s was successfully saved.\" % \n form.cleaned_data.get('name'))\n else:\n dajax.remove_css_class('#my_form input', 'error')\n for error in form.errors:\n dajax.add_css_class('#id_%s' % error, 'error')\n\t\t\t\n return dajax.json()" }, { "code": null, "e": 6012, "s": 5945, "text": "Now let's create the dreamreal.html template, which has our form −" }, { "code": null, "e": 6276, "s": 6012, "text": "<html>\n <head></head>\n <body>\n \n <form action = \"\" method = \"post\" id = \"my_form\" accept-charset = \"utf-8\">\n {{ form.as_p }}\n <p><input type = \"button\" value = \"Send\" onclick = \"send_form();\"></p>\n </form>\n \n </body>\n</html>" }, { "code": null, "e": 6337, "s": 6276, "text": "Add the view that goes with the template in myapp/views.py −" }, { "code": null, "e": 6441, "s": 6337, "text": "def dreamreal(request):\n form = DreamrealForm()\n return render(request, 'dreamreal.html', locals())" }, { "code": null, "e": 6486, "s": 6441, "text": "Add the corresponding URL in myapp/urls.py −" }, { "code": null, "e": 6541, "s": 6486, "text": "url(r'^dreamreal/', 'dreamreal', name = 'dreamreal'),\n" }, { "code": null, "e": 6609, "s": 6541, "text": "Now let's add the necessary in our template to make the Ajax work −" }, { "code": null, "e": 6638, "s": 6609, "text": "At the top of the file add −" }, { "code": null, "e": 6689, "s": 6638, "text": "{% load static %}\n{% load dajaxice_templatetags %}" }, { "code": null, "e": 6752, "s": 6689, "text": "And in the <head> section of our dreamreal.html template add −" }, { "code": null, "e": 6811, "s": 6752, "text": "We are using the JQuery library for this example, so add −" }, { "code": null, "e": 7004, "s": 6811, "text": "<script src = \"{% static '/static/jquery-1.11.3.min.js' %}\" \n type = \"text/javascript\" charset = \"utf-8\"></script>\n<script src = \"{% static '/static/dajax/jquery.dajax.core.js' %}\"></script>" }, { "code": null, "e": 7053, "s": 7004, "text": "The Ajax function that will be called on click −" }, { "code": null, "e": 7189, "s": 7053, "text": "<script>\n\n function send_form(){\n Dajaxice.myapp.send_form(Dajax.process,{'form':$('#my_form').serialize(true)});\n }\n</script>" }, { "code": null, "e": 7384, "s": 7189, "text": "Note that you need the “jquery-1.11.3.min.js” in your static files directory, and also the jquery.dajax.core.js. To make sure all dajax static files are served under your static directory, run −" }, { "code": null, "e": 7417, "s": 7384, "text": "$python manage.py collectstatic\n" }, { "code": null, "e": 7573, "s": 7417, "text": "Note − Sometimes the jquery.dajax.core.js can be missing, if that happens, just download the source and take that file and put it under your static folder." }, { "code": null, "e": 7650, "s": 7573, "text": "You will get to see the following screen, upon accessing /myapp/dreamreal/ −" }, { "code": null, "e": 7697, "s": 7650, "text": "On submit, you will get the following screen −" }, { "code": null, "e": 7732, "s": 7697, "text": "\n 39 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7744, "s": 7732, "text": " John Elder" }, { "code": null, "e": 7779, "s": 7744, "text": "\n 36 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7791, "s": 7779, "text": " John Elder" }, { "code": null, "e": 7824, "s": 7791, "text": "\n 28 Lectures \n 2 hours \n" }, { "code": null, "e": 7836, "s": 7824, "text": " John Elder" }, { "code": null, "e": 7869, "s": 7836, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 7881, "s": 7869, "text": " John Elder" }, { "code": null, "e": 7914, "s": 7881, "text": "\n 35 Lectures \n 3 hours \n" }, { "code": null, "e": 7926, "s": 7914, "text": " John Elder" }, { "code": null, "e": 7960, "s": 7926, "text": "\n 79 Lectures \n 10 hours \n" }, { "code": null, "e": 7974, "s": 7960, "text": " Rathan Kumar" }, { "code": null, "e": 7981, "s": 7974, "text": " Print" }, { "code": null, "e": 7992, "s": 7981, "text": " Add Notes" } ]
float keyword in C# - GeeksforGeeks
22 Jun, 2020 Keywords are the words in a language that are used for some internal process or represent some predefined actions. float is a keyword that is used to declare a variable which can store a floating point value from the range of ±1.5 x 10-45 to ±3.4 x 1038. It is an alias of System.Single. Syntax: float variable_name = value; float keyword occupies 4 bytes (32 bits) space in the memory. We use a suffix f or F with the value to represent a float value. Example: Input: -3629.4586F Output: num: -3629.458 Size of a float variable: 4 Input: 16345.6456f Output: Type of num: System.Single num: 16345.65 Size of a float variable: 4 Min value of float: -3.402823E+38 Max value of float: 3.402823E+38 Example 1: // C# program for float keywordusing System;using System.Text; class GFG { static void Main(string[] args) { // variable declaration float num = -3629.4586F; // to print value Console.WriteLine("num: " + num); // to print size Console.WriteLine("Size of a float variable: " + sizeof(float)); }} Output: num: -3629.458 Size of a float variable: 4 Example 2: // C# program for float keywordusing System;using System.Text; namespace geeks { class GFG { static void Main(string[] args) { // variable declaration float num = 16345.6456f; // to print type of variable Console.WriteLine("Type of num: " + num.GetType()); // to print value Console.WriteLine("num: " + num); // to print size Console.WriteLine("Size of a float variable: " + sizeof(float)); // to print minimum & maximum value of float Console.WriteLine("Min value of float: " + float.MinValue); Console.WriteLine("Max value of float: " + float.MaxValue); }}} Output: Type of num: System.Single num: 16345.65 Size of a float variable: 4 Min value of float: -3.402823E+38 Max value of float: 3.402823E+38 CSharp-keyword C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Lambda Expressions in C# Convert String to Character Array in C# C# | How to insert an element in an Array?
[ { "code": null, "e": 25657, "s": 25629, "text": "\n22 Jun, 2020" }, { "code": null, "e": 25945, "s": 25657, "text": "Keywords are the words in a language that are used for some internal process or represent some predefined actions. float is a keyword that is used to declare a variable which can store a floating point value from the range of ±1.5 x 10-45 to ±3.4 x 1038. It is an alias of System.Single." }, { "code": null, "e": 25953, "s": 25945, "text": "Syntax:" }, { "code": null, "e": 25982, "s": 25953, "text": "float variable_name = value;" }, { "code": null, "e": 26110, "s": 25982, "text": "float keyword occupies 4 bytes (32 bits) space in the memory. We use a suffix f or F with the value to represent a float value." }, { "code": null, "e": 26119, "s": 26110, "text": "Example:" }, { "code": null, "e": 26396, "s": 26119, "text": "Input: -3629.4586F\n\nOutput: num: -3629.458\n Size of a float variable: 4\n\nInput: 16345.6456f\n\nOutput: Type of num: System.Single\n num: 16345.65\n Size of a float variable: 4\n Min value of float: -3.402823E+38\n Max value of float: 3.402823E+38\n" }, { "code": null, "e": 26407, "s": 26396, "text": "Example 1:" }, { "code": "// C# program for float keywordusing System;using System.Text; class GFG { static void Main(string[] args) { // variable declaration float num = -3629.4586F; // to print value Console.WriteLine(\"num: \" + num); // to print size Console.WriteLine(\"Size of a float variable: \" + sizeof(float)); }}", "e": 26760, "s": 26407, "text": null }, { "code": null, "e": 26768, "s": 26760, "text": "Output:" }, { "code": null, "e": 26812, "s": 26768, "text": "num: -3629.458\nSize of a float variable: 4\n" }, { "code": null, "e": 26823, "s": 26812, "text": "Example 2:" }, { "code": "// C# program for float keywordusing System;using System.Text; namespace geeks { class GFG { static void Main(string[] args) { // variable declaration float num = 16345.6456f; // to print type of variable Console.WriteLine(\"Type of num: \" + num.GetType()); // to print value Console.WriteLine(\"num: \" + num); // to print size Console.WriteLine(\"Size of a float variable: \" + sizeof(float)); // to print minimum & maximum value of float Console.WriteLine(\"Min value of float: \" + float.MinValue); Console.WriteLine(\"Max value of float: \" + float.MaxValue); }}}", "e": 27481, "s": 26823, "text": null }, { "code": null, "e": 27489, "s": 27481, "text": "Output:" }, { "code": null, "e": 27626, "s": 27489, "text": "Type of num: System.Single\nnum: 16345.65\nSize of a float variable: 4\nMin value of float: -3.402823E+38\nMax value of float: 3.402823E+38\n" }, { "code": null, "e": 27641, "s": 27626, "text": "CSharp-keyword" }, { "code": null, "e": 27644, "s": 27641, "text": "C#" }, { "code": null, "e": 27742, "s": 27644, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27765, "s": 27742, "text": "Extension Method in C#" }, { "code": null, "e": 27793, "s": 27765, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27810, "s": 27793, "text": "C# | Inheritance" }, { "code": null, "e": 27832, "s": 27810, "text": "Partial Classes in C#" }, { "code": null, "e": 27861, "s": 27832, "text": "C# | Generics - Introduction" }, { "code": null, "e": 27901, "s": 27861, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27924, "s": 27901, "text": "Switch Statement in C#" }, { "code": null, "e": 27949, "s": 27924, "text": "Lambda Expressions in C#" }, { "code": null, "e": 27989, "s": 27949, "text": "Convert String to Character Array in C#" } ]
AngularJS | angular.equals() Function - GeeksforGeeks
16 Apr, 2019 The angular.equals() Function in AngularJS is used to compare two objects or two values whether these are same or not. If the two values are same, it returns TRUE else it will return FALSE. Syntax: angular.equals(val1, val2) Where val1 and val2 are the values or the objects to be compared.Return Value: Returns TRUE or FALSE Example 1: <html><head> <script src= "//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"> </script> <title>angular.equals()</title> </head> <body ng-app="app" style="text-align:Center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>angular.equals()</h2> <div ng-controller="geek"> Input A: <input type="number" ng-model="val1" ng-change="check()" /> <br /><br> Input B: <input type="number" ng-model="val2" ng-change="check()" /> <br /><br> {{msg}}</div> <script> var app = angular.module("app", []); app.controller('geek', ['$scope', function ($scope) { $scope.val1 = 0; $scope.val2 = 0; $scope.check = function () { if (angular.equals($scope.val1, $scope.val2)) $scope.msg = "Input values are equal."; else $scope.msg = "Input values are not equal."; } }]); </script></body></html> Output:Before Input:After Input: Example 2: <html><head> <script src= "//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"> </script> <title>angular.equals()</title> </head> <body ng-app="app" style="text-align:Center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>angular.equals()</h2> <body ng-app="app"> <div ng-controller="geek"> Password: <br> <input type="password" ng-model="pass" /> <br><br> Confirm Password: <br> <input type="password" ng-model="PASS" ng-change="match()" /><br /> <p ng-show="isMatch" style="color:green">Password matched</p> <p ng-hide="isMatch || PASS==null" style="color:red"> Password does not match</p> </div> <script> var app = angular.module("app", []); app.controller('geek', ['$scope', function ($scope) { $scope.match = function () { $scope.isMatch = angular.equals($scope.pass, $scope.PASS);}}]); </script></body></html> Output:Initially:Incorrect Input:Correct Input: AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular File Upload Angular | keyup event Angular PrimeNG Dropdown Component Auth Guards in Angular 9/10/11 Angular PrimeNG Calendar Component 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": 29626, "s": 29598, "text": "\n16 Apr, 2019" }, { "code": null, "e": 29816, "s": 29626, "text": "The angular.equals() Function in AngularJS is used to compare two objects or two values whether these are same or not. If the two values are same, it returns TRUE else it will return FALSE." }, { "code": null, "e": 29824, "s": 29816, "text": "Syntax:" }, { "code": null, "e": 29851, "s": 29824, "text": "angular.equals(val1, val2)" }, { "code": null, "e": 29952, "s": 29851, "text": "Where val1 and val2 are the values or the objects to be compared.Return Value: Returns TRUE or FALSE" }, { "code": null, "e": 29963, "s": 29952, "text": "Example 1:" }, { "code": "<html><head> <script src= \"//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js\"> </script> <title>angular.equals()</title> </head> <body ng-app=\"app\" style=\"text-align:Center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>angular.equals()</h2> <div ng-controller=\"geek\"> Input A: <input type=\"number\" ng-model=\"val1\" ng-change=\"check()\" /> <br /><br> Input B: <input type=\"number\" ng-model=\"val2\" ng-change=\"check()\" /> <br /><br> {{msg}}</div> <script> var app = angular.module(\"app\", []); app.controller('geek', ['$scope', function ($scope) { $scope.val1 = 0; $scope.val2 = 0; $scope.check = function () { if (angular.equals($scope.val1, $scope.val2)) $scope.msg = \"Input values are equal.\"; else $scope.msg = \"Input values are not equal.\"; } }]); </script></body></html>", "e": 30806, "s": 29963, "text": null }, { "code": null, "e": 30839, "s": 30806, "text": "Output:Before Input:After Input:" }, { "code": null, "e": 30850, "s": 30839, "text": "Example 2:" }, { "code": "<html><head> <script src= \"//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js\"> </script> <title>angular.equals()</title> </head> <body ng-app=\"app\" style=\"text-align:Center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>angular.equals()</h2> <body ng-app=\"app\"> <div ng-controller=\"geek\"> Password: <br> <input type=\"password\" ng-model=\"pass\" /> <br><br> Confirm Password: <br> <input type=\"password\" ng-model=\"PASS\" ng-change=\"match()\" /><br /> <p ng-show=\"isMatch\" style=\"color:green\">Password matched</p> <p ng-hide=\"isMatch || PASS==null\" style=\"color:red\"> Password does not match</p> </div> <script> var app = angular.module(\"app\", []); app.controller('geek', ['$scope', function ($scope) { $scope.match = function () { $scope.isMatch = angular.equals($scope.pass, $scope.PASS);}}]); </script></body></html>", "e": 31724, "s": 30850, "text": null }, { "code": null, "e": 31772, "s": 31724, "text": "Output:Initially:Incorrect Input:Correct Input:" }, { "code": null, "e": 31782, "s": 31772, "text": "AngularJS" }, { "code": null, "e": 31799, "s": 31782, "text": "Web Technologies" }, { "code": null, "e": 31897, "s": 31799, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31917, "s": 31897, "text": "Angular File Upload" }, { "code": null, "e": 31939, "s": 31917, "text": "Angular | keyup event" }, { "code": null, "e": 31974, "s": 31939, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 32005, "s": 31974, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 32040, "s": 32005, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 32080, "s": 32040, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32113, "s": 32080, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32158, "s": 32113, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32201, "s": 32158, "text": "How to fetch data from an API in ReactJS ?" } ]
How to Draw a Semi-Circle using HTML and CSS ? - GeeksforGeeks
30 Jul, 2021 A Semi-Circle or a Half-Circle shape can be easily created using HTML and CSS. We will use the border-radius property to draw the desired output. HTML Code: In this section we will create a simple “div” element using the <div> tag. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Semi Circle</title></head> <body> <div></div></body> </html> CSS Code: In this section we will first design the “div” box using simple CSS properties and then draw the semi-circle using the border-radius property. CSS <style> * { margin: 0; padding: 0; background-color: white; } /* Using the "border-radius" property to draw the semi-circle*/ div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); height: 100px; width: 200px; border-radius: 150px 150px 0 0; background-color: green; }</style> Final Code: It is the combination of the above two code sections. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Semi Circle</title> <style> * { margin: 0; padding: 0; background-color: white; } /* Using the border-radius property to draw the semi-circle*/ div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); height: 100px; width: 200px; border-radius: 150px 150px 0 0; background-color: green; } </style></head> <body> <div></div></body> </html> Output: CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? How to apply style to parent if it has child with CSS? Design a web page using HTML and CSS Create a Responsive Navbar using ReactJS Form validation using jQuery How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML
[ { "code": null, "e": 26803, "s": 26775, "text": "\n30 Jul, 2021" }, { "code": null, "e": 26949, "s": 26803, "text": "A Semi-Circle or a Half-Circle shape can be easily created using HTML and CSS. We will use the border-radius property to draw the desired output." }, { "code": null, "e": 27035, "s": 26949, "text": "HTML Code: In this section we will create a simple “div” element using the <div> tag." }, { "code": null, "e": 27040, "s": 27035, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Semi Circle</title></head> <body> <div></div></body> </html>", "e": 27264, "s": 27040, "text": null }, { "code": null, "e": 27417, "s": 27264, "text": "CSS Code: In this section we will first design the “div” box using simple CSS properties and then draw the semi-circle using the border-radius property." }, { "code": null, "e": 27421, "s": 27417, "text": "CSS" }, { "code": "<style> * { margin: 0; padding: 0; background-color: white; } /* Using the \"border-radius\" property to draw the semi-circle*/ div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); height: 100px; width: 200px; border-radius: 150px 150px 0 0; background-color: green; }</style>", "e": 27828, "s": 27421, "text": null }, { "code": null, "e": 27894, "s": 27828, "text": "Final Code: It is the combination of the above two code sections." }, { "code": null, "e": 27899, "s": 27894, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Semi Circle</title> <style> * { margin: 0; padding: 0; background-color: white; } /* Using the border-radius property to draw the semi-circle*/ div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); height: 100px; width: 200px; border-radius: 150px 150px 0 0; background-color: green; } </style></head> <body> <div></div></body> </html>", "e": 28606, "s": 27899, "text": null }, { "code": null, "e": 28614, "s": 28606, "text": "Output:" }, { "code": null, "e": 28800, "s": 28614, "text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 28937, "s": 28800, "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": 28946, "s": 28937, "text": "CSS-Misc" }, { "code": null, "e": 28956, "s": 28946, "text": "HTML-Misc" }, { "code": null, "e": 28960, "s": 28956, "text": "CSS" }, { "code": null, "e": 28965, "s": 28960, "text": "HTML" }, { "code": null, "e": 28982, "s": 28965, "text": "Web Technologies" }, { "code": null, "e": 29009, "s": 28982, "text": "Web technologies Questions" }, { "code": null, "e": 29014, "s": 29009, "text": "HTML" }, { "code": null, "e": 29112, "s": 29014, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29151, "s": 29112, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 29206, "s": 29151, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 29243, "s": 29206, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29284, "s": 29243, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 29313, "s": 29284, "text": "Form validation using jQuery" }, { "code": null, "e": 29373, "s": 29313, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 29426, "s": 29373, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 29487, "s": 29426, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 29511, "s": 29487, "text": "REST API (Introduction)" } ]
SQL Query to Display Nth Record from Employee Table
13 Apr, 2021 Here. we are going to see how to retrieve and display Nth records from a Microsoft SQL Server’s database table using an SQL query. We will first create a database called “geeks” and then create “Employee” table in this database and will execute our query on that table. Use the below SQL statement to create a database called geeks: CREATE DATABASE geeks; USE geeks; We have the following Employee table in our geeks database : CREATE TABLE Employee( ID INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(30) NOT NULL, PHONE INT(10) NOT NULL UNIQUE, EMAIL VARCHAR(30) NOT NULL UNIQUE, DATE_OF_JOINING DATE); You can use the below statement to query the description of the created table: EXEC SP_COLUMNS Employee; Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Use the below statement to add data to the Employee table: INSERT INTO Employee (NAME, PHONE, EMAIL, DATE_OF_JOINING) VALUES ('Yogesh Vaishnav', 0000000001, '[email protected]', '2019-10-03'), ('Vishal Vishwakarma', 0000000002, '[email protected]', '2019-11-07'), ('Ajit Yadav', 0000000003, '[email protected]', '2019-12-12'), ('Ashish Yadav', 0000000004, '[email protected]', '2019-12-25'), ('Tanvi Thakur', 0000000005, '[email protected]', '2020-01-20'), ('Sam', 0000000006, '[email protected]', '2020-03-03'), ('Ron', 0000000007, '[email protected]', '2020-05-16'), ('Sara', 0000000008, '[email protected]', '2020-07-01'), ('Zara', 0000000009, '[email protected]', '2020-08-20'), ('Yoji', 0000000010, '[email protected]', '2020-03-10'); To verify the contents of the table use the below statement: SELECT * FROM Employee; Now let’s display the Nth record of the table. Syntax : SELECT * FROM <table_name> LIMIT N-1,1; Here N refers to the row which is to be retrieved. Example : Let’s retrieve the 6th row from the start from the Employee table we have created. SELECT * FROM Employee ORDER BY <column_name> --column name is the name according to which the rows are to be ordered.Here it's ID. OFFSET 5 ROWS --since N - 1 = 6 - 1 = 5 FETCH NEXT 1 ROWS ONLY; Output : Picked SQL-Query SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL SQL Trigger | Student Database SQL Interview Questions How to Update Multiple Columns in Single Update Statement in SQL? SQL | Views Difference between DELETE, DROP and TRUNCATE Window functions in SQL SQL | GROUP BY MySQL | Group_CONCAT() Function Difference between DELETE and TRUNCATE
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Apr, 2021" }, { "code": null, "e": 324, "s": 54, "text": "Here. we are going to see how to retrieve and display Nth records from a Microsoft SQL Server’s database table using an SQL query. We will first create a database called “geeks” and then create “Employee” table in this database and will execute our query on that table." }, { "code": null, "e": 387, "s": 324, "text": "Use the below SQL statement to create a database called geeks:" }, { "code": null, "e": 410, "s": 387, "text": "CREATE DATABASE geeks;" }, { "code": null, "e": 421, "s": 410, "text": "USE geeks;" }, { "code": null, "e": 482, "s": 421, "text": "We have the following Employee table in our geeks database :" }, { "code": null, "e": 656, "s": 482, "text": "CREATE TABLE Employee(\nID INT PRIMARY KEY AUTO_INCREMENT,\nNAME VARCHAR(30) NOT NULL,\nPHONE INT(10) NOT NULL UNIQUE,\nEMAIL VARCHAR(30) NOT NULL UNIQUE,\nDATE_OF_JOINING DATE);" }, { "code": null, "e": 735, "s": 656, "text": "You can use the below statement to query the description of the created table:" }, { "code": null, "e": 761, "s": 735, "text": "EXEC SP_COLUMNS Employee;" }, { "code": null, "e": 770, "s": 761, "text": "Chapters" }, { "code": null, "e": 797, "s": 770, "text": "descriptions off, selected" }, { "code": null, "e": 847, "s": 797, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 870, "s": 847, "text": "captions off, selected" }, { "code": null, "e": 878, "s": 870, "text": "English" }, { "code": null, "e": 902, "s": 878, "text": "This is a modal window." }, { "code": null, "e": 971, "s": 902, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 993, "s": 971, "text": "End of dialog window." }, { "code": null, "e": 1052, "s": 993, "text": "Use the below statement to add data to the Employee table:" }, { "code": null, "e": 1695, "s": 1052, "text": "INSERT INTO Employee (NAME, PHONE, EMAIL, DATE_OF_JOINING)\nVALUES\n('Yogesh Vaishnav', 0000000001, '[email protected]', '2019-10-03'),\n('Vishal Vishwakarma', 0000000002, '[email protected]', '2019-11-07'),\n('Ajit Yadav', 0000000003, '[email protected]', '2019-12-12'),\n('Ashish Yadav', 0000000004, '[email protected]', '2019-12-25'),\n('Tanvi Thakur', 0000000005, '[email protected]', '2020-01-20'),\n('Sam', 0000000006, '[email protected]', '2020-03-03'),\n('Ron', 0000000007, '[email protected]', '2020-05-16'),\n('Sara', 0000000008, '[email protected]', '2020-07-01'),\n('Zara', 0000000009, '[email protected]', '2020-08-20'),\n('Yoji', 0000000010, '[email protected]', '2020-03-10');" }, { "code": null, "e": 1756, "s": 1695, "text": "To verify the contents of the table use the below statement:" }, { "code": null, "e": 1780, "s": 1756, "text": "SELECT * FROM Employee;" }, { "code": null, "e": 1827, "s": 1780, "text": "Now let’s display the Nth record of the table." }, { "code": null, "e": 1930, "s": 1827, "text": "Syntax : SELECT * FROM <table_name> LIMIT N-1,1;\n\nHere N refers to the row which is to be retrieved." }, { "code": null, "e": 1941, "s": 1930, "text": "Example : " }, { "code": null, "e": 2024, "s": 1941, "text": "Let’s retrieve the 6th row from the start from the Employee table we have created." }, { "code": null, "e": 2239, "s": 2024, "text": "SELECT * FROM Employee \nORDER BY <column_name> --column name is the name according to which the rows are to be ordered.Here it's ID.\nOFFSET 5 ROWS --since N - 1 = 6 - 1 = 5 \nFETCH NEXT 1 ROWS ONLY;" }, { "code": null, "e": 2248, "s": 2239, "text": "Output :" }, { "code": null, "e": 2255, "s": 2248, "text": "Picked" }, { "code": null, "e": 2265, "s": 2255, "text": "SQL-Query" }, { "code": null, "e": 2269, "s": 2265, "text": "SQL" }, { "code": null, "e": 2273, "s": 2269, "text": "SQL" }, { "code": null, "e": 2371, "s": 2273, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2382, "s": 2371, "text": "CTE in SQL" }, { "code": null, "e": 2413, "s": 2382, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 2437, "s": 2413, "text": "SQL Interview Questions" }, { "code": null, "e": 2503, "s": 2437, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 2515, "s": 2503, "text": "SQL | Views" }, { "code": null, "e": 2560, "s": 2515, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 2584, "s": 2560, "text": "Window functions in SQL" }, { "code": null, "e": 2599, "s": 2584, "text": "SQL | GROUP BY" }, { "code": null, "e": 2631, "s": 2599, "text": "MySQL | Group_CONCAT() Function" } ]
Transitive closure of a graph
20 Jun, 2022 Given a directed graph, find out if a vertex j is reachable from another vertex i for all vertex pairs (i, j) in the given graph. Here reachable mean that there is a path from vertex i to j. The reach-ability matrix is called the transitive closure of a graph. For example, consider below graph Transitive closure of above graphs is 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 The graph is given in the form of adjacency matrix say ‘graph[V][V]’ where graph[i][j] is 1 if there is an edge from vertex i to vertex j or i is equal to j, otherwise graph[i][j] is 0.Floyd Warshall Algorithm can be used, we can calculate the distance matrix dist[V][V] using Floyd Warshall, if dist[i][j] is infinite, then j is not reachable from I. Otherwise, j is reachable and the value of dist[i][j] will be less than V. Instead of directly using Floyd Warshall, we can optimize it in terms of space and time, for this particular problem. Following are the optimizations: Instead of an integer resultant matrix (dist[V][V] in floyd warshall), we can create a boolean reach-ability matrix reach[V][V] (we save space). The value reach[i][j] will be 1 if j is reachable from i, otherwise 0.Instead of using arithmetic operations, we can use logical operations. For arithmetic operation ‘+’, logical and ‘&&’ is used, and for a min, logical or ‘||’ is used. (We save time by a constant factor. Time complexity is the same though) Instead of an integer resultant matrix (dist[V][V] in floyd warshall), we can create a boolean reach-ability matrix reach[V][V] (we save space). The value reach[i][j] will be 1 if j is reachable from i, otherwise 0. Instead of using arithmetic operations, we can use logical operations. For arithmetic operation ‘+’, logical and ‘&&’ is used, and for a min, logical or ‘||’ is used. (We save time by a constant factor. Time complexity is the same though) Below is the implementation of the above approach: C++ Java Python3 C# Javascript // Program for transitive closure// using Floyd Warshall Algorithm#include<stdio.h> // Number of vertices in the graph#define V 4 // A function to print the solution matrixvoid printSolution(int reach[][V]); // Prints transitive closure of graph[][]// using Floyd Warshall algorithmvoid transitiveClosure(int graph[][V]){ /* reach[][] will be the output matrix // that will finally have the shortest distances between every pair of vertices */ int reach[V][V], i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) reach[i][j] = graph[i][j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have reachability values for all pairs of vertices such that the reachability values consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as // source one by one for (i = 0; i < V; i++) { // Pick all vertices as // destination for the // above picked source for (j = 0; j < V; j++) { // If vertex k is on a path // from i to j, // then make sure that the value // of reach[i][j] is 1 reach[i][j] = reach[i][j] || (reach[i][k] && reach[k][j]); } } } // Print the shortest distance matrix printSolution(reach);} /* A utility function to print solution */void printSolution(int reach[][V]){ printf ("Following matrix is transitive"); printf("closure of the given graph\n"); for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { /* because "i==j means same vertex" and we can reach same vertex from same vertex. So, we print 1.... and we have not considered this in Floyd Warshall Algo. so we need to make this true by ourself while printing transitive closure.*/ if(i == j) printf("1 "); else printf ("%d ", reach[i][j]); } printf("\n"); }} // Driver Codeint main(){ /* Let us create the following weighted graph 10 (0)------->(3) | /|\ 5 | | | | 1 \|/ | (1)------->(2) 3 */ int graph[V][V] = { {1, 1, 0, 1}, {0, 1, 1, 0}, {0, 0, 1, 1}, {0, 0, 0, 1} }; // Print the solution transitiveClosure(graph); return 0;} // Program for transitive closure// using Floyd Warshall Algorithmimport java.util.*;import java.lang.*;import java.io.*; class GraphClosure{ final static int V = 4; //Number of vertices in a graph // Prints transitive closure of graph[][] using Floyd // Warshall algorithm void transitiveClosure(int graph[][]) { /* reach[][] will be the output matrix that will finally have the shortest distances between every pair of vertices */ int reach[][] = new int[V][V]; int i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) reach[i][j] = graph[i][j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have reachability values for all pairs of vertices such that the reachability values consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination for the // above picked source for (j = 0; j < V; j++) { // If vertex k is on a path from i to j, // then make sure that the value of reach[i][j] is 1 reach[i][j] = (reach[i][j]!=0) || ((reach[i][k]!=0) && (reach[k][j]!=0))?1:0; } } } // Print the shortest distance matrix printSolution(reach); } /* A utility function to print solution */ void printSolution(int reach[][]) { System.out.println("Following matrix is transitive closure"+ " of the given graph"); for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if ( i == j) System.out.print("1 "); else System.out.print(reach[i][j]+" "); } System.out.println(); } } // Driver Code public static void main (String[] args) { /* Let us create the following weighted graph 10 (0)------->(3) | /|\ 5 | | | | 1 \|/ | (1)------->(2) 3 */ /* Let us create the following weighted graph 10 (0)------->(3) | /|\ 5 | | | | 1 \|/ | (1)------->(2) 3 */ int graph[][] = new int[][]{ {1, 1, 0, 1}, {0, 1, 1, 0}, {0, 0, 1, 1}, {0, 0, 0, 1} }; // Print the solution GraphClosure g = new GraphClosure(); g.transitiveClosure(graph); }}// This code is contributed by Aakash Hasija # Python program for transitive closure using Floyd Warshall Algorithm#Complexity : O(V^3) from collections import defaultdict #Class to represent a graphclass Graph: def __init__(self, vertices): self.V = vertices # A utility function to print the solution def printSolution(self, reach): print ("Following matrix transitive closure of the given graph ") for i in range(self.V): for j in range(self.V): if (i == j): print ("%7d\t" % (1),end=" ") else: print ("%7d\t" %(reach[i][j]),end=" ") print() # Prints transitive closure of graph[][] using Floyd Warshall algorithm def transitiveClosure(self,graph): '''reach[][] will be the output matrix that will finally have reachability values. Initialize the solution matrix same as input graph matrix''' reach =[i[:] for i in graph] '''Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have reachability value for all pairs of vertices such that the reachability values consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of an iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k}''' for k in range(self.V): # Pick all vertices as source one by one for i in range(self.V): # Pick all vertices as destination for the # above picked source for j in range(self.V): # If vertex k is on a path from i to j, # then make sure that the value of reach[i][j] is 1 reach[i][j] = reach[i][j] or (reach[i][k] and reach[k][j]) self.printSolution(reach) g= Graph(4) graph = [[1, 1, 0, 1], [0, 1, 1, 0], [0, 0, 1, 1], [0, 0, 0, 1]] #Print the solutiong.transitiveClosure(graph) #This code is contributed by Neelam Yadav // C# Program for transitive closure// using Floyd Warshall Algorithmusing System; class GFG{ static int V = 4; // Number of vertices in a graph // Prints transitive closure of graph[,] // using Floyd Warshall algorithm void transitiveClosure(int [,]graph) { /* reach[,] will be the output matrix that will finally have the shortest distances between every pair of vertices */ int [,]reach = new int[V, V]; int i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) reach[i, j] = graph[i, j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have reachability values for all pairs of vertices such that the reachability values consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ---> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination // for the above picked source for (j = 0; j < V; j++) { // If vertex k is on a path from i to j, // then make sure that the value of // reach[i,j] is 1 reach[i, j] = (reach[i, j] != 0) || ((reach[i, k] != 0) && (reach[k, j] != 0)) ? 1 : 0; } } } // Print the shortest distance matrix printSolution(reach); } /* A utility function to print solution */ void printSolution(int [,]reach) { Console.WriteLine("Following matrix is transitive" + " closure of the given graph"); for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++){ if (i == j) Console.Write("1 "); else Console.Write(reach[i, j] + " "); } Console.WriteLine(); } } // Driver Code public static void Main (String[] args) { /* Let us create the following weighted graph 10 (0)------->(3) | /|\ 5 | | | | 1 \|/ | (1)------->(2) 3 */ /* Let us create the following weighted graph 10 (0)------->(3) | /|\ 5 | | | | 1 \|/ | (1)------->(2) 3 */ int [,]graph = new int[,]{{1, 1, 0, 1}, {0, 1, 1, 0}, {0, 0, 1, 1}, {0, 0, 0, 1}}; // Print the solution GFG g = new GFG(); g.transitiveClosure(graph); }} // This code is contributed by 29AjayKumar <script> // JavaScript Program for transitive closure // using Floyd Warshall Algorithm var V = 4; // Number of vertices in a graph // Prints transitive closure of graph[,] // using Floyd Warshall algorithm function transitiveClosure(graph) { /* reach[,] will be the output matrix that will finally have the shortest distances between every pair of vertices */ var reach = Array.from(Array(V), () => new Array(V)); var i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) reach[i][j] = graph[i][j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have reachability values for all pairs of vertices such that the reachability values consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ---> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination // for the above picked source for (j = 0; j < V; j++) { // If vertex k is on a path from i to j, // then make sure that the value of // reach[i,j] is 1 reach[i][j] = reach[i][j] != 0 || (reach[i][k] != 0 && reach[k][j] != 0) ? 1 : 0; } } } // Print the shortest distance matrix printSolution(reach); } /* A utility function to print solution */ function printSolution(reach) { document.write( "Following matrix is transitive" + " closure of the given graph <br>" ); for (var i = 0; i < V; i++) { for (var j = 0; j < V; j++) { if (i == j) document.write("1 "); else document.write(reach[i][j] + " "); } document.write("<br>"); } } // Driver Code /* Let us create the following weighted graph 10 (0)------->(3) | /|\ 5 | | | | 1 \|/ | (1)------->(2) 3 */ /* Let us create the following weighted graph 10 (0)------->(3) | /|\ 5 | | | | 1 \|/ | (1)------->(2) 3 */ var graph = [ [1, 1, 0, 1], [0, 1, 1, 0], [0, 0, 1, 1], [0, 0, 0, 1], ]; // Print the solution transitiveClosure(graph); // This code is contributed by rdtank. </script> Following matrix is transitiveclosure of the given graph 1 1 1 1 0 1 1 1 0 0 1 1 0 0 0 1 Time Complexity: O(V3) where V is number of vertices in the given graph. See below post for a O(V2) solution. Transitive Closure of a Graph using DFS 29AjayKumar AMBERSINGHAL rdtank amartyaghoshgfg hardikkoriintern Graph Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Dijkstra's shortest path algorithm | Greedy Algo-7 Find if there is a path between two vertices in a directed graph Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Detect Cycle in a Directed Graph Introduction to Data Structures Find if there is a path between two vertices in an undirected graph What is Data Structure: Types, Classifications and Applications Bellman–Ford Algorithm | DP-23 Minimum number of swaps required to sort an array m Coloring Problem | Backtracking-5
[ { "code": null, "e": 54, "s": 26, "text": "\n20 Jun, 2022" }, { "code": null, "e": 315, "s": 54, "text": "Given a directed graph, find out if a vertex j is reachable from another vertex i for all vertex pairs (i, j) in the given graph. Here reachable mean that there is a path from vertex i to j. The reach-ability matrix is called the transitive closure of a graph." }, { "code": null, "e": 349, "s": 315, "text": "For example, consider below graph" }, { "code": null, "e": 443, "s": 349, "text": "Transitive closure of above graphs is \n 1 1 1 1 \n 1 1 1 1 \n 1 1 1 1 \n 0 0 0 1" }, { "code": null, "e": 871, "s": 443, "text": "The graph is given in the form of adjacency matrix say ‘graph[V][V]’ where graph[i][j] is 1 if there is an edge from vertex i to vertex j or i is equal to j, otherwise graph[i][j] is 0.Floyd Warshall Algorithm can be used, we can calculate the distance matrix dist[V][V] using Floyd Warshall, if dist[i][j] is infinite, then j is not reachable from I. Otherwise, j is reachable and the value of dist[i][j] will be less than V. " }, { "code": null, "e": 1022, "s": 871, "text": "Instead of directly using Floyd Warshall, we can optimize it in terms of space and time, for this particular problem. Following are the optimizations:" }, { "code": null, "e": 1476, "s": 1022, "text": "Instead of an integer resultant matrix (dist[V][V] in floyd warshall), we can create a boolean reach-ability matrix reach[V][V] (we save space). The value reach[i][j] will be 1 if j is reachable from i, otherwise 0.Instead of using arithmetic operations, we can use logical operations. For arithmetic operation ‘+’, logical and ‘&&’ is used, and for a min, logical or ‘||’ is used. (We save time by a constant factor. Time complexity is the same though)" }, { "code": null, "e": 1692, "s": 1476, "text": "Instead of an integer resultant matrix (dist[V][V] in floyd warshall), we can create a boolean reach-ability matrix reach[V][V] (we save space). The value reach[i][j] will be 1 if j is reachable from i, otherwise 0." }, { "code": null, "e": 1931, "s": 1692, "text": "Instead of using arithmetic operations, we can use logical operations. For arithmetic operation ‘+’, logical and ‘&&’ is used, and for a min, logical or ‘||’ is used. (We save time by a constant factor. Time complexity is the same though)" }, { "code": null, "e": 1982, "s": 1931, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1986, "s": 1982, "text": "C++" }, { "code": null, "e": 1991, "s": 1986, "text": "Java" }, { "code": null, "e": 1999, "s": 1991, "text": "Python3" }, { "code": null, "e": 2002, "s": 1999, "text": "C#" }, { "code": null, "e": 2013, "s": 2002, "text": "Javascript" }, { "code": "// Program for transitive closure// using Floyd Warshall Algorithm#include<stdio.h> // Number of vertices in the graph#define V 4 // A function to print the solution matrixvoid printSolution(int reach[][V]); // Prints transitive closure of graph[][]// using Floyd Warshall algorithmvoid transitiveClosure(int graph[][V]){ /* reach[][] will be the output matrix // that will finally have the shortest distances between every pair of vertices */ int reach[V][V], i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) reach[i][j] = graph[i][j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have reachability values for all pairs of vertices such that the reachability values consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as // source one by one for (i = 0; i < V; i++) { // Pick all vertices as // destination for the // above picked source for (j = 0; j < V; j++) { // If vertex k is on a path // from i to j, // then make sure that the value // of reach[i][j] is 1 reach[i][j] = reach[i][j] || (reach[i][k] && reach[k][j]); } } } // Print the shortest distance matrix printSolution(reach);} /* A utility function to print solution */void printSolution(int reach[][V]){ printf (\"Following matrix is transitive\"); printf(\"closure of the given graph\\n\"); for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { /* because \"i==j means same vertex\" and we can reach same vertex from same vertex. So, we print 1.... and we have not considered this in Floyd Warshall Algo. so we need to make this true by ourself while printing transitive closure.*/ if(i == j) printf(\"1 \"); else printf (\"%d \", reach[i][j]); } printf(\"\\n\"); }} // Driver Codeint main(){ /* Let us create the following weighted graph 10 (0)------->(3) | /|\\ 5 | | | | 1 \\|/ | (1)------->(2) 3 */ int graph[V][V] = { {1, 1, 0, 1}, {0, 1, 1, 0}, {0, 0, 1, 1}, {0, 0, 0, 1} }; // Print the solution transitiveClosure(graph); return 0;}", "e": 5159, "s": 2013, "text": null }, { "code": "// Program for transitive closure// using Floyd Warshall Algorithmimport java.util.*;import java.lang.*;import java.io.*; class GraphClosure{ final static int V = 4; //Number of vertices in a graph // Prints transitive closure of graph[][] using Floyd // Warshall algorithm void transitiveClosure(int graph[][]) { /* reach[][] will be the output matrix that will finally have the shortest distances between every pair of vertices */ int reach[][] = new int[V][V]; int i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) reach[i][j] = graph[i][j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have reachability values for all pairs of vertices such that the reachability values consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination for the // above picked source for (j = 0; j < V; j++) { // If vertex k is on a path from i to j, // then make sure that the value of reach[i][j] is 1 reach[i][j] = (reach[i][j]!=0) || ((reach[i][k]!=0) && (reach[k][j]!=0))?1:0; } } } // Print the shortest distance matrix printSolution(reach); } /* A utility function to print solution */ void printSolution(int reach[][]) { System.out.println(\"Following matrix is transitive closure\"+ \" of the given graph\"); for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if ( i == j) System.out.print(\"1 \"); else System.out.print(reach[i][j]+\" \"); } System.out.println(); } } // Driver Code public static void main (String[] args) { /* Let us create the following weighted graph 10 (0)------->(3) | /|\\ 5 | | | | 1 \\|/ | (1)------->(2) 3 */ /* Let us create the following weighted graph 10 (0)------->(3) | /|\\ 5 | | | | 1 \\|/ | (1)------->(2) 3 */ int graph[][] = new int[][]{ {1, 1, 0, 1}, {0, 1, 1, 0}, {0, 0, 1, 1}, {0, 0, 0, 1} }; // Print the solution GraphClosure g = new GraphClosure(); g.transitiveClosure(graph); }}// This code is contributed by Aakash Hasija", "e": 8622, "s": 5159, "text": null }, { "code": "# Python program for transitive closure using Floyd Warshall Algorithm#Complexity : O(V^3) from collections import defaultdict #Class to represent a graphclass Graph: def __init__(self, vertices): self.V = vertices # A utility function to print the solution def printSolution(self, reach): print (\"Following matrix transitive closure of the given graph \") for i in range(self.V): for j in range(self.V): if (i == j): print (\"%7d\\t\" % (1),end=\" \") else: print (\"%7d\\t\" %(reach[i][j]),end=\" \") print() # Prints transitive closure of graph[][] using Floyd Warshall algorithm def transitiveClosure(self,graph): '''reach[][] will be the output matrix that will finally have reachability values. Initialize the solution matrix same as input graph matrix''' reach =[i[:] for i in graph] '''Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have reachability value for all pairs of vertices such that the reachability values consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of an iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k}''' for k in range(self.V): # Pick all vertices as source one by one for i in range(self.V): # Pick all vertices as destination for the # above picked source for j in range(self.V): # If vertex k is on a path from i to j, # then make sure that the value of reach[i][j] is 1 reach[i][j] = reach[i][j] or (reach[i][k] and reach[k][j]) self.printSolution(reach) g= Graph(4) graph = [[1, 1, 0, 1], [0, 1, 1, 0], [0, 0, 1, 1], [0, 0, 0, 1]] #Print the solutiong.transitiveClosure(graph) #This code is contributed by Neelam Yadav", "e": 10783, "s": 8622, "text": null }, { "code": "// C# Program for transitive closure// using Floyd Warshall Algorithmusing System; class GFG{ static int V = 4; // Number of vertices in a graph // Prints transitive closure of graph[,] // using Floyd Warshall algorithm void transitiveClosure(int [,]graph) { /* reach[,] will be the output matrix that will finally have the shortest distances between every pair of vertices */ int [,]reach = new int[V, V]; int i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) reach[i, j] = graph[i, j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have reachability values for all pairs of vertices such that the reachability values consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ---> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination // for the above picked source for (j = 0; j < V; j++) { // If vertex k is on a path from i to j, // then make sure that the value of // reach[i,j] is 1 reach[i, j] = (reach[i, j] != 0) || ((reach[i, k] != 0) && (reach[k, j] != 0)) ? 1 : 0; } } } // Print the shortest distance matrix printSolution(reach); } /* A utility function to print solution */ void printSolution(int [,]reach) { Console.WriteLine(\"Following matrix is transitive\" + \" closure of the given graph\"); for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++){ if (i == j) Console.Write(\"1 \"); else Console.Write(reach[i, j] + \" \"); } Console.WriteLine(); } } // Driver Code public static void Main (String[] args) { /* Let us create the following weighted graph 10 (0)------->(3) | /|\\ 5 | | | | 1 \\|/ | (1)------->(2) 3 */ /* Let us create the following weighted graph 10 (0)------->(3) | /|\\ 5 | | | | 1 \\|/ | (1)------->(2) 3 */ int [,]graph = new int[,]{{1, 1, 0, 1}, {0, 1, 1, 0}, {0, 0, 1, 1}, {0, 0, 0, 1}}; // Print the solution GFG g = new GFG(); g.transitiveClosure(graph); }} // This code is contributed by 29AjayKumar", "e": 14083, "s": 10783, "text": null }, { "code": "<script> // JavaScript Program for transitive closure // using Floyd Warshall Algorithm var V = 4; // Number of vertices in a graph // Prints transitive closure of graph[,] // using Floyd Warshall algorithm function transitiveClosure(graph) { /* reach[,] will be the output matrix that will finally have the shortest distances between every pair of vertices */ var reach = Array.from(Array(V), () => new Array(V)); var i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) reach[i][j] = graph[i][j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have reachability values for all pairs of vertices such that the reachability values consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ---> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination // for the above picked source for (j = 0; j < V; j++) { // If vertex k is on a path from i to j, // then make sure that the value of // reach[i,j] is 1 reach[i][j] = reach[i][j] != 0 || (reach[i][k] != 0 && reach[k][j] != 0) ? 1 : 0; } } } // Print the shortest distance matrix printSolution(reach); } /* A utility function to print solution */ function printSolution(reach) { document.write( \"Following matrix is transitive\" + \" closure of the given graph <br>\" ); for (var i = 0; i < V; i++) { for (var j = 0; j < V; j++) { if (i == j) document.write(\"1 \"); else document.write(reach[i][j] + \" \"); } document.write(\"<br>\"); } } // Driver Code /* Let us create the following weighted graph 10 (0)------->(3) | /|\\ 5 | | | | 1 \\|/ | (1)------->(2) 3 */ /* Let us create the following weighted graph 10 (0)------->(3) | /|\\ 5 | | | | 1 \\|/ | (1)------->(2) 3 */ var graph = [ [1, 1, 0, 1], [0, 1, 1, 0], [0, 0, 1, 1], [0, 0, 0, 1], ]; // Print the solution transitiveClosure(graph); // This code is contributed by rdtank. </script>", "e": 17088, "s": 14083, "text": null }, { "code": null, "e": 17181, "s": 17088, "text": "Following matrix is transitiveclosure of the given graph\n1 1 1 1 \n0 1 1 1 \n0 0 1 1 \n0 0 0 1 " }, { "code": null, "e": 17254, "s": 17181, "text": "Time Complexity: O(V3) where V is number of vertices in the given graph." }, { "code": null, "e": 17292, "s": 17254, "text": "See below post for a O(V2) solution. " }, { "code": null, "e": 17332, "s": 17292, "text": "Transitive Closure of a Graph using DFS" }, { "code": null, "e": 17344, "s": 17332, "text": "29AjayKumar" }, { "code": null, "e": 17357, "s": 17344, "text": "AMBERSINGHAL" }, { "code": null, "e": 17364, "s": 17357, "text": "rdtank" }, { "code": null, "e": 17380, "s": 17364, "text": "amartyaghoshgfg" }, { "code": null, "e": 17397, "s": 17380, "text": "hardikkoriintern" }, { "code": null, "e": 17403, "s": 17397, "text": "Graph" }, { "code": null, "e": 17409, "s": 17403, "text": "Graph" }, { "code": null, "e": 17507, "s": 17409, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 17558, "s": 17507, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 17623, "s": 17558, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 17681, "s": 17623, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 17714, "s": 17681, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 17746, "s": 17714, "text": "Introduction to Data Structures" }, { "code": null, "e": 17814, "s": 17746, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 17878, "s": 17814, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 17909, "s": 17878, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 17959, "s": 17909, "text": "Minimum number of swaps required to sort an array" } ]
Python | Merging two strings with Suffix and Prefix
25 Nov, 2019 Given two strings A and B and these strings contain lower case letters. The task is to tell the length of the merged strings. For example, given A is “abcde” and B is “cdefg”, then merging the two strings results in “abcdefg”. The merge operation is performed in such a manner that the joining characters are both the suffix of A and Prefix of B.Before merging you are allowed to do any ONE of the following operations: Reverse string AReverse string B Reverse string A Reverse string B Examples: Input : A = "ababc" B = "bcabc" Output : Length is 8 the suffix of string A i.e "bc" and prefix of B i.e "bc" is the same so the merged string will be "ababcabc" and length is 8. Input : A = "cdefg" B = "abhgf" Output : Length is 8 the suffix of string A i.e "fg" and prefix of reversed B i.e "fg" is the same so the merged string will be "cdefghba" and length is 8 Input : A = "wxyz" B = "zyxw" Output : Length is 4 Below is the Python code implementation of the above mentioned approach. # function to find the length of the# merged string def mergedstring(x, y) : k = len(y) for i in range(len(x)) : if x[i:] == y[:k] : break else: k = k-1 # uncomment the below statement to # know what the merged string is # print(a + b[k:]) return len(a + b[k:]) # function to find the minimum length# among the merged stringdef merger(a, b): # reverse b b1 = b[::-1] # function call to find the length # of string without reversing string 'B' r1 = mergedstring(a, b) # function call to find the length # of the string by reversing string 'B' r2 = mergedstring(a, b1) # compare between lengths if r1 > r2 : print("Length is", r2) else : print("Length is", r1) # driver codea = "abcbc"b = "bcabc" merger(a, b) Output: Length is 8 python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Nov, 2019" }, { "code": null, "e": 448, "s": 28, "text": "Given two strings A and B and these strings contain lower case letters. The task is to tell the length of the merged strings. For example, given A is “abcde” and B is “cdefg”, then merging the two strings results in “abcdefg”. The merge operation is performed in such a manner that the joining characters are both the suffix of A and Prefix of B.Before merging you are allowed to do any ONE of the following operations:" }, { "code": null, "e": 481, "s": 448, "text": "Reverse string AReverse string B" }, { "code": null, "e": 498, "s": 481, "text": "Reverse string A" }, { "code": null, "e": 515, "s": 498, "text": "Reverse string B" }, { "code": null, "e": 525, "s": 515, "text": "Examples:" }, { "code": null, "e": 949, "s": 525, "text": "Input :\nA = \"ababc\"\nB = \"bcabc\" \nOutput :\nLength is 8\n\nthe suffix of string A i.e \"bc\" and prefix of B i.e \"bc\" is the same\nso the merged string will be \"ababcabc\" and length is 8.\n\nInput :\nA = \"cdefg\"\nB = \"abhgf\"\nOutput :\nLength is 8\n\nthe suffix of string A i.e \"fg\" and prefix of reversed B i.e \"fg\" is the same\nso the merged string will be \"cdefghba\" and length is 8\n\nInput :\nA = \"wxyz\"\nB = \"zyxw\"\nOutput :\nLength is 4\n" }, { "code": null, "e": 1022, "s": 949, "text": "Below is the Python code implementation of the above mentioned approach." }, { "code": "# function to find the length of the# merged string def mergedstring(x, y) : k = len(y) for i in range(len(x)) : if x[i:] == y[:k] : break else: k = k-1 # uncomment the below statement to # know what the merged string is # print(a + b[k:]) return len(a + b[k:]) # function to find the minimum length# among the merged stringdef merger(a, b): # reverse b b1 = b[::-1] # function call to find the length # of string without reversing string 'B' r1 = mergedstring(a, b) # function call to find the length # of the string by reversing string 'B' r2 = mergedstring(a, b1) # compare between lengths if r1 > r2 : print(\"Length is\", r2) else : print(\"Length is\", r1) # driver codea = \"abcbc\"b = \"bcabc\" merger(a, b)", "e": 1874, "s": 1022, "text": null }, { "code": null, "e": 1882, "s": 1874, "text": "Output:" }, { "code": null, "e": 1895, "s": 1882, "text": "Length is 8\n" }, { "code": null, "e": 1909, "s": 1895, "text": "python-string" }, { "code": null, "e": 1916, "s": 1909, "text": "Python" } ]
Working with Excel Files in R Programming
12 Jan, 2022 Excel files are of extension .xls, .xlsx and .csv(comma-separated values). To start working with excel files in R Programming Language, we need to first import excel files in RStudio or any other R supporting IDE(Integrated development environment). First, install readxl package in R to load excel files. Various methods including their subparts are demonstrated further. Sample_data1.xlsx: Sample_data2.xlsx: The two excel files Sample_data1.xlsx and Sample_data2.xlsx and read from the working directory. R # Working with Excel Files# Installing required packageinstall.packages("readxl") # Loading the packagelibrary(readxl) # Importing excel fileData1 < - read_excel("Sample_data1.xlsx")Data2 < - read_excel("Sample_data2.xlsx") # Printing the datahead(Data1)head(Data2) The excel files are loaded into variables Data_1 and Data_2 as a dataframes and then variable Data_1 and Data_2 is called that prints the dataset. The Sample_data1.xlsx file and Sample_file2.xlsx are modified. R # Modifying the filesData1$Pclass <- 0 Data2$Embarked <- "S" # Printing the datahead(Data1)head(Data2) The value of the P-class attribute or variable of Data1 data is modified to 0. The value of Embarked attribute or variable of Data2 is modified to S. The variable or attribute is deleted from Data1 and Data2 datasets containing Sample_data1.xlsx and Sample_data2.xlsx files. R # Deleting from filesData1 <- Data1[-2] Data2 <- Data2[-3] # Printing the dataData1Data2 The – sign is used to delete columns or attributes from the dataset. Column 2 is deleted from the Data1 dataset and Column 3 is deleted from the Data2 dataset. The two excel datasets Data1 and Data2 are merged using merge() function which is in base package and comes pre-installed in R. R # Merging FilesData3 <- merge(Data1, Data2, all.x = TRUE, all.y = TRUE) # Displaying the datahead(Data3) Data1 and Data2 are merged with each other and the resultant file is stored in the Data3 variable. New columns or features can be easily created in Data1 and Data2 datasets. R # Creating feature in Data1 datasetData1$Num < - 0 # Creating feature in Data2 datasetData2$Code < - "Mission" # Printing the datahead(Data1)head(Data2) Num is a new feature that is created with 0 default value in Data1 dataset. Code is a new feature that is created with the mission as a default string in Data2 dataset. After performing all operations, Data1 and Data2 are written into new files using write.xlsx() function built in writexl package. R # Installing the packageinstall.packages("writexl") # Loading packagelibrary(writexl) # Writing Data1write_xlsx(Data1, "New_Data1.xlsx") # Writing Data2write_xlsx(Data2, "New_Data2.xlsx") The Data1 dataset is written New_Data1.xlsx file and Data2 dataset is written in New_Data2.xlsx file. Both the files are saved in the present working directory. kumar_satyam surinderdawra388 Picked R-FileHandling R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change column name of a given DataFrame in R Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Adding elements in a vector in R programming - append() method Group by function in R using Dplyr How to change Row Names of DataFrame in R ? Convert Factor to Numeric and Numeric to Factor in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jan, 2022" }, { "code": null, "e": 278, "s": 28, "text": "Excel files are of extension .xls, .xlsx and .csv(comma-separated values). To start working with excel files in R Programming Language, we need to first import excel files in RStudio or any other R supporting IDE(Integrated development environment)." }, { "code": null, "e": 401, "s": 278, "text": "First, install readxl package in R to load excel files. Various methods including their subparts are demonstrated further." }, { "code": null, "e": 420, "s": 401, "text": "Sample_data1.xlsx:" }, { "code": null, "e": 439, "s": 420, "text": "Sample_data2.xlsx:" }, { "code": null, "e": 536, "s": 439, "text": "The two excel files Sample_data1.xlsx and Sample_data2.xlsx and read from the working directory." }, { "code": null, "e": 538, "s": 536, "text": "R" }, { "code": "# Working with Excel Files# Installing required packageinstall.packages(\"readxl\") # Loading the packagelibrary(readxl) # Importing excel fileData1 < - read_excel(\"Sample_data1.xlsx\")Data2 < - read_excel(\"Sample_data2.xlsx\") # Printing the datahead(Data1)head(Data2)", "e": 804, "s": 538, "text": null }, { "code": null, "e": 951, "s": 804, "text": "The excel files are loaded into variables Data_1 and Data_2 as a dataframes and then variable Data_1 and Data_2 is called that prints the dataset." }, { "code": null, "e": 1014, "s": 951, "text": "The Sample_data1.xlsx file and Sample_file2.xlsx are modified." }, { "code": null, "e": 1016, "s": 1014, "text": "R" }, { "code": "# Modifying the filesData1$Pclass <- 0 Data2$Embarked <- \"S\" # Printing the datahead(Data1)head(Data2)", "e": 1119, "s": 1016, "text": null }, { "code": null, "e": 1269, "s": 1119, "text": "The value of the P-class attribute or variable of Data1 data is modified to 0. The value of Embarked attribute or variable of Data2 is modified to S." }, { "code": null, "e": 1394, "s": 1269, "text": "The variable or attribute is deleted from Data1 and Data2 datasets containing Sample_data1.xlsx and Sample_data2.xlsx files." }, { "code": null, "e": 1396, "s": 1394, "text": "R" }, { "code": "# Deleting from filesData1 <- Data1[-2] Data2 <- Data2[-3] # Printing the dataData1Data2", "e": 1485, "s": 1396, "text": null }, { "code": null, "e": 1645, "s": 1485, "text": "The – sign is used to delete columns or attributes from the dataset. Column 2 is deleted from the Data1 dataset and Column 3 is deleted from the Data2 dataset." }, { "code": null, "e": 1773, "s": 1645, "text": "The two excel datasets Data1 and Data2 are merged using merge() function which is in base package and comes pre-installed in R." }, { "code": null, "e": 1775, "s": 1773, "text": "R" }, { "code": "# Merging FilesData3 <- merge(Data1, Data2, all.x = TRUE, all.y = TRUE) # Displaying the datahead(Data3)", "e": 1880, "s": 1775, "text": null }, { "code": null, "e": 1979, "s": 1880, "text": "Data1 and Data2 are merged with each other and the resultant file is stored in the Data3 variable." }, { "code": null, "e": 2054, "s": 1979, "text": "New columns or features can be easily created in Data1 and Data2 datasets." }, { "code": null, "e": 2056, "s": 2054, "text": "R" }, { "code": "# Creating feature in Data1 datasetData1$Num < - 0 # Creating feature in Data2 datasetData2$Code < - \"Mission\" # Printing the datahead(Data1)head(Data2)", "e": 2209, "s": 2056, "text": null }, { "code": null, "e": 2378, "s": 2209, "text": "Num is a new feature that is created with 0 default value in Data1 dataset. Code is a new feature that is created with the mission as a default string in Data2 dataset." }, { "code": null, "e": 2508, "s": 2378, "text": "After performing all operations, Data1 and Data2 are written into new files using write.xlsx() function built in writexl package." }, { "code": null, "e": 2510, "s": 2508, "text": "R" }, { "code": "# Installing the packageinstall.packages(\"writexl\") # Loading packagelibrary(writexl) # Writing Data1write_xlsx(Data1, \"New_Data1.xlsx\") # Writing Data2write_xlsx(Data2, \"New_Data2.xlsx\")", "e": 2698, "s": 2510, "text": null }, { "code": null, "e": 2859, "s": 2698, "text": "The Data1 dataset is written New_Data1.xlsx file and Data2 dataset is written in New_Data2.xlsx file. Both the files are saved in the present working directory." }, { "code": null, "e": 2872, "s": 2859, "text": "kumar_satyam" }, { "code": null, "e": 2889, "s": 2872, "text": "surinderdawra388" }, { "code": null, "e": 2896, "s": 2889, "text": "Picked" }, { "code": null, "e": 2911, "s": 2896, "text": "R-FileHandling" }, { "code": null, "e": 2922, "s": 2911, "text": "R Language" }, { "code": null, "e": 3020, "s": 2922, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3065, "s": 3020, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 3117, "s": 3065, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 3175, "s": 3117, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 3227, "s": 3175, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 3285, "s": 3227, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3317, "s": 3285, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 3380, "s": 3317, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 3415, "s": 3380, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 3459, "s": 3415, "text": "How to change Row Names of DataFrame in R ?" } ]
Bank of America Interview Experience | On-Campus 2021
12 Oct, 2021 Bank of America visited our campus on 9th September for various profiles testing, analysis, and development. The whole interview process was done virtually. It consists of 3 rounds. Online AssessmentHR RoundTechnical Round and Managerial Round Online Assessment HR Round Technical Round and Managerial Round Round 1: Online assessment Time: 90 minutes The test was active on 9th and 10th September and we had to complete it in 48 hours, so it was like we could attempt it at any time in these 48 hours given time and was conducted on the company’s platform. There were 5 questions (3 video questions + 2 coding questions). The camera and microphone were open for 3 video questions and the only camera was on for 2 coding questions. The first video question was to “Introduce yourself”, the second was “Why should you be a good match for this profile” and the third question was “Explaining the approach of your second coding question” like u need to explain in detail what logic you applied to solve the second coding question. Coding Questions: Given n test cases each of which has numbers in form of strings, output all numbers from 1 to that number which is not divisible by 5 or 7. Example: i/p – 24 o/p - 1 2 3 4 6 8 9 11 12 13 16 17 18 19 22 23 24 Given a string s consisting of lower and uppercase letters where each letter has a value from 1 to 26 and we need to calculate the beauty value of this string which is the sum of all alphabets in it. Note: The string is not case sensitive meaning F is exactly beautiful as f is. Output the maximum possible beauty of this string. Example: i/p – AbBCcc o/p – 152 Hint: You need to observe which alphabet will have what value..... like it’s not necessary for A or a to have a value as 1 and Z or z to have a value as 26. So think. Solution for 2nd question: First Count the frequency of all elements in the string then the one with the largest frequency is given number 26, then another one with less frequency as 25, and so on. So, for the above example: AbBCcc – here frequency of c is maximum so c has number 26, the frequency of A max so its value is 25 and for b it’s 24 so answer = 3*26 + 2*25 + 1*24 = 152 I was able to solve both the coding questions easily and also the video questions with confidence. About 80-90 students were shortlisted for further rounds. Round 2: HR Round Time: 10 min All further face-to-face interview rounds were conducted on Web-Ex. This was a very small round and was majorly around resume and HR-type questions. When I entered the meet, the first question was to Introduce myself. After this the discussion went on my projects, the technologies I used and how did I overcome all the challenges during making my project. Round 3: Technical + Managerial round Time: 1 hour This round again started with my introduction followed up with a good discussion. The interviewer was very friendly and started asking me questions on each and everything mentioned in my resume right from questions from all languages to all projects, a good discussion on projects made, to everything related to my hobby. What are lists, dictionary Differences b/w list, dictionary, and tuple The above two were asked as I mentioned Python in my resume. Difference between x++ and x=x+1 Is multiple inheritances allowed in Java How comfortable are u in coding? What is OS, DBMS, different types of joins, 1 SQL query (fairly easy – given a table with employees and their respective salaries o/p the second highest salary) Basic commands like CREATE, SELECT, GROUP BY, etc were also asked What is networking, OSI Model, LAN, and WAN since I mentioned NETWORKING in my resume and he was a networking person Implement stack using queue and vice versa only verbal implementation Questions on the project were asked and since my project was related to HTML and Css so questions from that domain were asked I mention traveling as my hobby so he asked: Where did you travel last and what enthusiast you about that place and all like he wanted to hear why is traveling my hobby Some Hr type questions were: What are your strengths and weaknesses? Which profile would you prefer? Where do you see yourself in 5 years and what are your goals? If given a choice between the client, you, and the company who would you choose first and why? So overall it was a kind of healthy conversation. The results were declared in a week and I was one of the selected people!!! Tips: Must be aware and prepare for each and every word in your resume so be confident on whatever you have mentioned in your resume. Should have high knowledge of all core subjects (i.e) OOPS, DBMS, and OS and Networking Should have at least solved more number medium questions in Competitive coding. (Standard questions are compulsory) Know about the company before applying (Very Important). Bank of America Marketing On-Campus Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE 1 Amazon Interview Experience SDE-2 (3 Years Experienced) Google Interview Questions Write It Up: Share Your Interview Experiences Google SWE Interview Experience (Google Online Coding Challenge) 2022 Nagarro Interview Experience | On-Campus 2021 Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022 Amazon Interview Experience for SDE-1 Zoho Interview | Set 3 (Off-Campus) Nagarro Interview Experience
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Oct, 2021" }, { "code": null, "e": 137, "s": 28, "text": "Bank of America visited our campus on 9th September for various profiles testing, analysis, and development." }, { "code": null, "e": 210, "s": 137, "text": "The whole interview process was done virtually. It consists of 3 rounds." }, { "code": null, "e": 272, "s": 210, "text": "Online AssessmentHR RoundTechnical Round and Managerial Round" }, { "code": null, "e": 290, "s": 272, "text": "Online Assessment" }, { "code": null, "e": 299, "s": 290, "text": "HR Round" }, { "code": null, "e": 336, "s": 299, "text": "Technical Round and Managerial Round" }, { "code": null, "e": 363, "s": 336, "text": "Round 1: Online assessment" }, { "code": null, "e": 380, "s": 363, "text": "Time: 90 minutes" }, { "code": null, "e": 587, "s": 380, "text": "The test was active on 9th and 10th September and we had to complete it in 48 hours, so it was like we could attempt it at any time in these 48 hours given time and was conducted on the company’s platform." }, { "code": null, "e": 652, "s": 587, "text": "There were 5 questions (3 video questions + 2 coding questions)." }, { "code": null, "e": 761, "s": 652, "text": "The camera and microphone were open for 3 video questions and the only camera was on for 2 coding questions." }, { "code": null, "e": 1057, "s": 761, "text": "The first video question was to “Introduce yourself”, the second was “Why should you be a good match for this profile” and the third question was “Explaining the approach of your second coding question” like u need to explain in detail what logic you applied to solve the second coding question." }, { "code": null, "e": 1075, "s": 1057, "text": "Coding Questions:" }, { "code": null, "e": 1215, "s": 1075, "text": "Given n test cases each of which has numbers in form of strings, output all numbers from 1 to that number which is not divisible by 5 or 7." }, { "code": null, "e": 1283, "s": 1215, "text": "Example: i/p – 24\no/p - 1 2 3 4 6 8 9 11 12 13 16 17 18 19 22 23 24" }, { "code": null, "e": 1485, "s": 1285, "text": "Given a string s consisting of lower and uppercase letters where each letter has a value from 1 to 26 and we need to calculate the beauty value of this string which is the sum of all alphabets in it." }, { "code": null, "e": 1615, "s": 1485, "text": "Note: The string is not case sensitive meaning F is exactly beautiful as f is. Output the maximum possible beauty of this string." }, { "code": null, "e": 1647, "s": 1615, "text": "Example: i/p – AbBCcc\no/p – 152" }, { "code": null, "e": 1814, "s": 1647, "text": "Hint: You need to observe which alphabet will have what value..... like it’s not necessary for A or a to have a value as 1 and Z or z to have a value as 26. So think." }, { "code": null, "e": 2012, "s": 1814, "text": "Solution for 2nd question: First Count the frequency of all elements in the string then the one with the largest frequency is given number 26, then another one with less frequency as 25, and so on." }, { "code": null, "e": 2197, "s": 2012, "text": "So, for the above example: AbBCcc – here frequency of c is maximum so c has number 26, the frequency of A max so its value is 25 and for b it’s 24 so answer = 3*26 + 2*25 + 1*24 = 152" }, { "code": null, "e": 2296, "s": 2197, "text": "I was able to solve both the coding questions easily and also the video questions with confidence." }, { "code": null, "e": 2354, "s": 2296, "text": "About 80-90 students were shortlisted for further rounds." }, { "code": null, "e": 2372, "s": 2354, "text": "Round 2: HR Round" }, { "code": null, "e": 2385, "s": 2372, "text": "Time: 10 min" }, { "code": null, "e": 2453, "s": 2385, "text": "All further face-to-face interview rounds were conducted on Web-Ex." }, { "code": null, "e": 2534, "s": 2453, "text": "This was a very small round and was majorly around resume and HR-type questions." }, { "code": null, "e": 2603, "s": 2534, "text": "When I entered the meet, the first question was to Introduce myself." }, { "code": null, "e": 2742, "s": 2603, "text": "After this the discussion went on my projects, the technologies I used and how did I overcome all the challenges during making my project." }, { "code": null, "e": 2781, "s": 2742, "text": "Round 3: Technical + Managerial round " }, { "code": null, "e": 2794, "s": 2781, "text": "Time: 1 hour" }, { "code": null, "e": 3117, "s": 2794, "text": "This round again started with my introduction followed up with a good discussion. The interviewer was very friendly and started asking me questions on each and everything mentioned in my resume right from questions from all languages to all projects, a good discussion on projects made, to everything related to my hobby." }, { "code": null, "e": 3144, "s": 3117, "text": "What are lists, dictionary" }, { "code": null, "e": 3188, "s": 3144, "text": "Differences b/w list, dictionary, and tuple" }, { "code": null, "e": 3249, "s": 3188, "text": "The above two were asked as I mentioned Python in my resume." }, { "code": null, "e": 3282, "s": 3249, "text": "Difference between x++ and x=x+1" }, { "code": null, "e": 3323, "s": 3282, "text": "Is multiple inheritances allowed in Java" }, { "code": null, "e": 3356, "s": 3323, "text": "How comfortable are u in coding?" }, { "code": null, "e": 3517, "s": 3356, "text": "What is OS, DBMS, different types of joins, 1 SQL query (fairly easy – given a table with employees and their respective salaries o/p the second highest salary)" }, { "code": null, "e": 3583, "s": 3517, "text": "Basic commands like CREATE, SELECT, GROUP BY, etc were also asked" }, { "code": null, "e": 3701, "s": 3583, "text": "What is networking, OSI Model, LAN, and WAN since I mentioned NETWORKING in my resume and he was a networking person" }, { "code": null, "e": 3771, "s": 3701, "text": "Implement stack using queue and vice versa only verbal implementation" }, { "code": null, "e": 3897, "s": 3771, "text": "Questions on the project were asked and since my project was related to HTML and Css so questions from that domain were asked" }, { "code": null, "e": 3942, "s": 3897, "text": "I mention traveling as my hobby so he asked:" }, { "code": null, "e": 4066, "s": 3942, "text": "Where did you travel last and what enthusiast you about that place and all like he wanted to hear why is traveling my hobby" }, { "code": null, "e": 4095, "s": 4066, "text": "Some Hr type questions were:" }, { "code": null, "e": 4135, "s": 4095, "text": "What are your strengths and weaknesses?" }, { "code": null, "e": 4167, "s": 4135, "text": "Which profile would you prefer?" }, { "code": null, "e": 4229, "s": 4167, "text": "Where do you see yourself in 5 years and what are your goals?" }, { "code": null, "e": 4324, "s": 4229, "text": "If given a choice between the client, you, and the company who would you choose first and why?" }, { "code": null, "e": 4450, "s": 4324, "text": "So overall it was a kind of healthy conversation. The results were declared in a week and I was one of the selected people!!!" }, { "code": null, "e": 4456, "s": 4450, "text": "Tips:" }, { "code": null, "e": 4584, "s": 4456, "text": "Must be aware and prepare for each and every word in your resume so be confident on whatever you have mentioned in your resume." }, { "code": null, "e": 4672, "s": 4584, "text": "Should have high knowledge of all core subjects (i.e) OOPS, DBMS, and OS and Networking" }, { "code": null, "e": 4788, "s": 4672, "text": "Should have at least solved more number medium questions in Competitive coding. (Standard questions are compulsory)" }, { "code": null, "e": 4845, "s": 4788, "text": "Know about the company before applying (Very Important)." }, { "code": null, "e": 4861, "s": 4845, "text": "Bank of America" }, { "code": null, "e": 4871, "s": 4861, "text": "Marketing" }, { "code": null, "e": 4881, "s": 4871, "text": "On-Campus" }, { "code": null, "e": 4903, "s": 4881, "text": "Interview Experiences" }, { "code": null, "e": 5001, "s": 4903, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5039, "s": 5001, "text": "Amazon Interview Experience for SDE 1" }, { "code": null, "e": 5095, "s": 5039, "text": "Amazon Interview Experience SDE-2 (3 Years Experienced)" }, { "code": null, "e": 5122, "s": 5095, "text": "Google Interview Questions" }, { "code": null, "e": 5168, "s": 5122, "text": "Write It Up: Share Your Interview Experiences" }, { "code": null, "e": 5238, "s": 5168, "text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022" }, { "code": null, "e": 5284, "s": 5238, "text": "Nagarro Interview Experience | On-Campus 2021" }, { "code": null, "e": 5357, "s": 5284, "text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022" }, { "code": null, "e": 5395, "s": 5357, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 5431, "s": 5395, "text": "Zoho Interview | Set 3 (Off-Campus)" } ]
Media.net Interview Experience 2021
06 Aug, 2021 Online Assessment: Given a tree rooted at 1 with n nodes, q queries are given. In each query, d, e are given as input. You need to find the maximum value of e^x where x is one of the ancestors of d or d itself in the tree.n<=10^5 q<=3*10^5 e<=3*10^5 1<=d<=nA bus stops at n bus stops, each bus stop having a[i] people. The bus needs to take in all the people on the bus. People from 1 bus stop get down before the next bus stop arrives. They use a resizing tech which allows the bus to be resized to whatever capacity they want. This action can be done only b times at max. The uselessness of the bus is the summation of a total number of unoccupied seats across n stops. Find the minimum uselessness the bus can achieve if the resizing tech is used optimally. 1<=a[i]<=10^6, 1<=b<=n<=400Ex 1: a = [10 20] b = 0 Ans:10Explanation – the resizing tech cannot be applied. hence the capacity of the bus is 20 initially. in the first stop, 20-10 seats were unused. in the second stop 20 – 20 seats are unused. Total unused seats = 10Ex 2: a = [10 20 30] b = 1 Ans: 10Explanation – the resizing tech can be applied only once. The capacity of the bus is 10 initially. in the first stop 10-10 seats unused = 0. in the second stop, the tech is used to resize to 30. 30 – 20 seats unused.In the third stop, 30-30 seats unusedTotal unused seats = 10.You will be given n points in a 2D plane which represents the corona orange zone. On the i-th day, Corona will spread to all the locations which are within i euclidean distance from each Corona orange zone. A zone will become red, if it coincides with atleast ‘x’ orange zones. Given the n pairs and x, find the day in which the first red zone occurs.1<=n<=100, 1<=b<=n, for each point, 1<=x<=10^9, 1<=y<=10^9 Example- (9,4),(10,3) , x=2. Ans : 1In point (9,3) both the zones would have been affected after day 1. Hence it will become a red zone after day 1. Given a tree rooted at 1 with n nodes, q queries are given. In each query, d, e are given as input. You need to find the maximum value of e^x where x is one of the ancestors of d or d itself in the tree.n<=10^5 q<=3*10^5 e<=3*10^5 1<=d<=n n<=10^5 q<=3*10^5 e<=3*10^5 1<=d<=n A bus stops at n bus stops, each bus stop having a[i] people. The bus needs to take in all the people on the bus. People from 1 bus stop get down before the next bus stop arrives. They use a resizing tech which allows the bus to be resized to whatever capacity they want. This action can be done only b times at max. The uselessness of the bus is the summation of a total number of unoccupied seats across n stops. Find the minimum uselessness the bus can achieve if the resizing tech is used optimally. 1<=a[i]<=10^6, 1<=b<=n<=400Ex 1: a = [10 20] b = 0 Ans:10Explanation – the resizing tech cannot be applied. hence the capacity of the bus is 20 initially. in the first stop, 20-10 seats were unused. in the second stop 20 – 20 seats are unused. Total unused seats = 10Ex 2: a = [10 20 30] b = 1 Ans: 10Explanation – the resizing tech can be applied only once. The capacity of the bus is 10 initially. in the first stop 10-10 seats unused = 0. in the second stop, the tech is used to resize to 30. 30 – 20 seats unused.In the third stop, 30-30 seats unusedTotal unused seats = 10. Ex 1: a = [10 20] b = 0 Ans:10 Explanation – the resizing tech cannot be applied. hence the capacity of the bus is 20 initially. in the first stop, 20-10 seats were unused. in the second stop 20 – 20 seats are unused. Total unused seats = 10 Ex 2: a = [10 20 30] b = 1 Ans: 10 Explanation – the resizing tech can be applied only once. The capacity of the bus is 10 initially. in the first stop 10-10 seats unused = 0. in the second stop, the tech is used to resize to 30. 30 – 20 seats unused. In the third stop, 30-30 seats unused Total unused seats = 10. You will be given n points in a 2D plane which represents the corona orange zone. On the i-th day, Corona will spread to all the locations which are within i euclidean distance from each Corona orange zone. A zone will become red, if it coincides with atleast ‘x’ orange zones. Given the n pairs and x, find the day in which the first red zone occurs.1<=n<=100, 1<=b<=n, for each point, 1<=x<=10^9, 1<=y<=10^9 Example- (9,4),(10,3) , x=2. Ans : 1In point (9,3) both the zones would have been affected after day 1. Hence it will become a red zone after day 1. 1<=n<=100, 1<=b<=n, for each point, 1<=x<=10^9, 1<=y<=10^9 Example- (9,4),(10,3) , x=2. Ans : 1 In point (9,3) both the zones would have been affected after day 1. Hence it will become a red zone after day 1. Interview Round 1: I was asked to introduce myself. After a short introduction, I was directly given a problem. The problem is as follows: You are given 4 strings w,x,y,z. You can permute each of the strings however you want. You have to fix 1 permutation for each of the 4 strings such that when you add all the 4 strings into a trie, the number of nodes created in the trie is minimized.Example- w = abaa x = aaaa y = acca z = abca For permutaion: w = abaa x = aaaa y = acca z = abcaNumber of nodes in Trie – 1 (number of new nodes for first character of all strings) + 3(for second character ) + 4(for third character ) + 4(for fourth character ) = 12minimum number of trie nodes when:w = aaab x = aaaa y = aacc z = aacd Number of nodes : 1 + 1 + 2 + 4 = 8I gave a O(2^ (number of words (4 in this case)) * number of characters(26 in this case)) using bitmasks. The interviewer was convinced. You are given 4 strings w,x,y,z. You can permute each of the strings however you want. You have to fix 1 permutation for each of the 4 strings such that when you add all the 4 strings into a trie, the number of nodes created in the trie is minimized.Example- w = abaa x = aaaa y = acca z = abca For permutaion: w = abaa x = aaaa y = acca z = abcaNumber of nodes in Trie – 1 (number of new nodes for first character of all strings) + 3(for second character ) + 4(for third character ) + 4(for fourth character ) = 12minimum number of trie nodes when:w = aaab x = aaaa y = aacc z = aacd Number of nodes : 1 + 1 + 2 + 4 = 8I gave a O(2^ (number of words (4 in this case)) * number of characters(26 in this case)) using bitmasks. The interviewer was convinced. Example- w = abaa x = aaaa y = acca z = abca For permutaion: w = abaa x = aaaa y = acca z = abca Number of nodes in Trie – 1 (number of new nodes for first character of all strings) + 3(for second character ) + 4(for third character ) + 4(for fourth character ) = 12 minimum number of trie nodes when: w = aaab x = aaaa y = aacc z = aacd Number of nodes : 1 + 1 + 2 + 4 = 8 I gave a O(2^ (number of words (4 in this case)) * number of characters(26 in this case)) using bitmasks. The interviewer was convinced. Interview Round 2: There was a small introduction. Then the interviewer directly jumped into a problem. You are given a 2D array of integers with dimension n X m and a value ‘k’. Find if there exists a square submatrix whose sum is equal to k.Example- n = 3, m = 3, k = 10 1 2 3 2 3 4 3 2 6 Output: trueExplanation: The square starting from (1,0) to (2,1) (Zero based indexing) has a sum 2 + 3 + 2 + 3 = 10 which is equal to k.I first gave O(m*n*min(m,n)) solution using DP and optimised it O(m*n*log(min(n,m))) using binary search. But the expected solution was O(m*n) using 2 pointers. You are given a 2D array of integers with dimension n X m and a value ‘k’. Find if there exists a square submatrix whose sum is equal to k.Example- n = 3, m = 3, k = 10 1 2 3 2 3 4 3 2 6 Output: trueExplanation: The square starting from (1,0) to (2,1) (Zero based indexing) has a sum 2 + 3 + 2 + 3 = 10 which is equal to k.I first gave O(m*n*min(m,n)) solution using DP and optimised it O(m*n*log(min(n,m))) using binary search. But the expected solution was O(m*n) using 2 pointers. Example- n = 3, m = 3, k = 10 1 2 3 2 3 4 3 2 6 Output: true Explanation: The square starting from (1,0) to (2,1) (Zero based indexing) has a sum 2 + 3 + 2 + 3 = 10 which is equal to k. I first gave O(m*n*min(m,n)) solution using DP and optimised it O(m*n*log(min(n,m))) using binary search. But the expected solution was O(m*n) using 2 pointers. Marketing media.net Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Aug, 2021" }, { "code": null, "e": 73, "s": 54, "text": "Online Assessment:" }, { "code": null, "e": 1956, "s": 73, "text": "Given a tree rooted at 1 with n nodes, q queries are given. In each query, d, e are given as input. You need to find the maximum value of e^x where x is one of the ancestors of d or d itself in the tree.n<=10^5\nq<=3*10^5\ne<=3*10^5\n1<=d<=nA bus stops at n bus stops, each bus stop having a[i] people. The bus needs to take in all the people on the bus. People from 1 bus stop get down before the next bus stop arrives. They use a resizing tech which allows the bus to be resized to whatever capacity they want. This action can be done only b times at max. The uselessness of the bus is the summation of a total number of unoccupied seats across n stops. Find the minimum uselessness the bus can achieve if the resizing tech is used optimally. 1<=a[i]<=10^6, 1<=b<=n<=400Ex 1:\na = [10 20] b = 0\nAns:10Explanation – the resizing tech cannot be applied. hence the capacity of the bus is 20 initially. in the first stop, 20-10 seats were unused. in the second stop 20 – 20 seats are unused. Total unused seats = 10Ex 2:\na = [10 20 30] b = 1\nAns: 10Explanation – the resizing tech can be applied only once. The capacity of the bus is 10 initially. in the first stop 10-10 seats unused = 0. in the second stop, the tech is used to resize to 30. 30 – 20 seats unused.In the third stop, 30-30 seats unusedTotal unused seats = 10.You will be given n points in a 2D plane which represents the corona orange zone. On the i-th day, Corona will spread to all the locations which are within i euclidean distance from each Corona orange zone. A zone will become red, if it coincides with atleast ‘x’ orange zones. Given the n pairs and x, find the day in which the first red zone occurs.1<=n<=100, 1<=b<=n, \nfor each point, \n1<=x<=10^9, 1<=y<=10^9\nExample-\n(9,4),(10,3) , x=2.\nAns : 1In point (9,3) both the zones would have been affected after day 1. Hence it will become a red zone after day 1." }, { "code": null, "e": 2195, "s": 1956, "text": "Given a tree rooted at 1 with n nodes, q queries are given. In each query, d, e are given as input. You need to find the maximum value of e^x where x is one of the ancestors of d or d itself in the tree.n<=10^5\nq<=3*10^5\ne<=3*10^5\n1<=d<=n" }, { "code": null, "e": 2231, "s": 2195, "text": "n<=10^5\nq<=3*10^5\ne<=3*10^5\n1<=d<=n" }, { "code": null, "e": 3315, "s": 2231, "text": "A bus stops at n bus stops, each bus stop having a[i] people. The bus needs to take in all the people on the bus. People from 1 bus stop get down before the next bus stop arrives. They use a resizing tech which allows the bus to be resized to whatever capacity they want. This action can be done only b times at max. The uselessness of the bus is the summation of a total number of unoccupied seats across n stops. Find the minimum uselessness the bus can achieve if the resizing tech is used optimally. 1<=a[i]<=10^6, 1<=b<=n<=400Ex 1:\na = [10 20] b = 0\nAns:10Explanation – the resizing tech cannot be applied. hence the capacity of the bus is 20 initially. in the first stop, 20-10 seats were unused. in the second stop 20 – 20 seats are unused. Total unused seats = 10Ex 2:\na = [10 20 30] b = 1\nAns: 10Explanation – the resizing tech can be applied only once. The capacity of the bus is 10 initially. in the first stop 10-10 seats unused = 0. in the second stop, the tech is used to resize to 30. 30 – 20 seats unused.In the third stop, 30-30 seats unusedTotal unused seats = 10." }, { "code": null, "e": 3346, "s": 3315, "text": "Ex 1:\na = [10 20] b = 0\nAns:10" }, { "code": null, "e": 3557, "s": 3346, "text": "Explanation – the resizing tech cannot be applied. hence the capacity of the bus is 20 initially. in the first stop, 20-10 seats were unused. in the second stop 20 – 20 seats are unused. Total unused seats = 10" }, { "code": null, "e": 3592, "s": 3557, "text": "Ex 2:\na = [10 20 30] b = 1\nAns: 10" }, { "code": null, "e": 3809, "s": 3592, "text": "Explanation – the resizing tech can be applied only once. The capacity of the bus is 10 initially. in the first stop 10-10 seats unused = 0. in the second stop, the tech is used to resize to 30. 30 – 20 seats unused." }, { "code": null, "e": 3848, "s": 3809, "text": "In the third stop, 30-30 seats unused" }, { "code": null, "e": 3873, "s": 3848, "text": "Total unused seats = 10." }, { "code": null, "e": 4435, "s": 3873, "text": "You will be given n points in a 2D plane which represents the corona orange zone. On the i-th day, Corona will spread to all the locations which are within i euclidean distance from each Corona orange zone. A zone will become red, if it coincides with atleast ‘x’ orange zones. Given the n pairs and x, find the day in which the first red zone occurs.1<=n<=100, 1<=b<=n, \nfor each point, \n1<=x<=10^9, 1<=y<=10^9\nExample-\n(9,4),(10,3) , x=2.\nAns : 1In point (9,3) both the zones would have been affected after day 1. Hence it will become a red zone after day 1." }, { "code": null, "e": 4533, "s": 4435, "text": "1<=n<=100, 1<=b<=n, \nfor each point, \n1<=x<=10^9, 1<=y<=10^9\nExample-\n(9,4),(10,3) , x=2.\nAns : 1" }, { "code": null, "e": 4646, "s": 4533, "text": "In point (9,3) both the zones would have been affected after day 1. Hence it will become a red zone after day 1." }, { "code": null, "e": 4785, "s": 4646, "text": "Interview Round 1: I was asked to introduce myself. After a short introduction, I was directly given a problem. The problem is as follows:" }, { "code": null, "e": 5543, "s": 4785, "text": "You are given 4 strings w,x,y,z. You can permute each of the strings however you want. You have to fix 1 permutation for each of the 4 strings such that when you add all the 4 strings into a trie, the number of nodes created in the trie is minimized.Example-\nw = abaa\nx = aaaa\ny = acca\nz = abca\nFor permutaion:\nw = abaa\nx = aaaa\ny = acca\nz = abcaNumber of nodes in Trie – 1 (number of new nodes for first character of all strings) + 3(for second character ) + 4(for third character ) + 4(for fourth character ) = 12minimum number of trie nodes when:w = aaab\nx = aaaa\ny = aacc\nz = aacd\nNumber of nodes : \n1 + 1 + 2 + 4 = 8I gave a O(2^ (number of words (4 in this case)) * number of characters(26 in this case)) using bitmasks. The interviewer was convinced." }, { "code": null, "e": 6301, "s": 5543, "text": "You are given 4 strings w,x,y,z. You can permute each of the strings however you want. You have to fix 1 permutation for each of the 4 strings such that when you add all the 4 strings into a trie, the number of nodes created in the trie is minimized.Example-\nw = abaa\nx = aaaa\ny = acca\nz = abca\nFor permutaion:\nw = abaa\nx = aaaa\ny = acca\nz = abcaNumber of nodes in Trie – 1 (number of new nodes for first character of all strings) + 3(for second character ) + 4(for third character ) + 4(for fourth character ) = 12minimum number of trie nodes when:w = aaab\nx = aaaa\ny = aacc\nz = aacd\nNumber of nodes : \n1 + 1 + 2 + 4 = 8I gave a O(2^ (number of words (4 in this case)) * number of characters(26 in this case)) using bitmasks. The interviewer was convinced." }, { "code": null, "e": 6398, "s": 6301, "text": "Example-\nw = abaa\nx = aaaa\ny = acca\nz = abca\nFor permutaion:\nw = abaa\nx = aaaa\ny = acca\nz = abca" }, { "code": null, "e": 6568, "s": 6398, "text": "Number of nodes in Trie – 1 (number of new nodes for first character of all strings) + 3(for second character ) + 4(for third character ) + 4(for fourth character ) = 12" }, { "code": null, "e": 6603, "s": 6568, "text": "minimum number of trie nodes when:" }, { "code": null, "e": 6676, "s": 6603, "text": "w = aaab\nx = aaaa\ny = aacc\nz = aacd\nNumber of nodes : \n1 + 1 + 2 + 4 = 8" }, { "code": null, "e": 6813, "s": 6676, "text": "I gave a O(2^ (number of words (4 in this case)) * number of characters(26 in this case)) using bitmasks. The interviewer was convinced." }, { "code": null, "e": 6917, "s": 6813, "text": "Interview Round 2: There was a small introduction. Then the interviewer directly jumped into a problem." }, { "code": null, "e": 7401, "s": 6917, "text": "You are given a 2D array of integers with dimension n X m and a value ‘k’. Find if there exists a square submatrix whose sum is equal to k.Example-\nn = 3, m = 3, k = 10\n1 2 3\n2 3 4\n3 2 6\nOutput: trueExplanation: The square starting from (1,0) to (2,1) (Zero based indexing) has a sum 2 + 3 + 2 + 3 = 10 which is equal to k.I first gave O(m*n*min(m,n)) solution using DP and optimised it O(m*n*log(min(n,m))) using binary search. But the expected solution was O(m*n) using 2 pointers." }, { "code": null, "e": 7885, "s": 7401, "text": "You are given a 2D array of integers with dimension n X m and a value ‘k’. Find if there exists a square submatrix whose sum is equal to k.Example-\nn = 3, m = 3, k = 10\n1 2 3\n2 3 4\n3 2 6\nOutput: trueExplanation: The square starting from (1,0) to (2,1) (Zero based indexing) has a sum 2 + 3 + 2 + 3 = 10 which is equal to k.I first gave O(m*n*min(m,n)) solution using DP and optimised it O(m*n*log(min(n,m))) using binary search. But the expected solution was O(m*n) using 2 pointers." }, { "code": null, "e": 7946, "s": 7885, "text": "Example-\nn = 3, m = 3, k = 10\n1 2 3\n2 3 4\n3 2 6\nOutput: true" }, { "code": null, "e": 8071, "s": 7946, "text": "Explanation: The square starting from (1,0) to (2,1) (Zero based indexing) has a sum 2 + 3 + 2 + 3 = 10 which is equal to k." }, { "code": null, "e": 8232, "s": 8071, "text": "I first gave O(m*n*min(m,n)) solution using DP and optimised it O(m*n*log(min(n,m))) using binary search. But the expected solution was O(m*n) using 2 pointers." }, { "code": null, "e": 8242, "s": 8232, "text": "Marketing" }, { "code": null, "e": 8252, "s": 8242, "text": "media.net" }, { "code": null, "e": 8274, "s": 8252, "text": "Interview Experiences" } ]
How to get the current Date and Time in PHP ?
14 Jan, 2021 The purpose of the article is to get the current Date and Time in PHP. It is performed by using a simple in-built PHP function date(). The Date is an inbuilt function used to format the timestamp. The computer stores date and time in UNIX timestamp. This time is measured as a number of seconds since Jan 1, 1970. As this is difficult for humans to read, PHP converts timestamps to format in such a way that it is readable and more understandable to humans. Syntax: date('d-m-y h:i:s'); Parameters : The date() have different parameters. Each parameter represents some meaningful unit. d: It represents the day of the month which has two digits with leading zeros (01 or 31)m: It represents month in numbers with leading zeros (01 or 1)y: It represents a year in two digits (08 or 14).h: It represents the hour of the day in two digits with leading zeros (01 or 1)I: It represents the minute in the current time zone.s: It represents the number of seconds in the current timezone. d: It represents the day of the month which has two digits with leading zeros (01 or 31) m: It represents month in numbers with leading zeros (01 or 1) y: It represents a year in two digits (08 or 14). h: It represents the hour of the day in two digits with leading zeros (01 or 1) I: It represents the minute in the current time zone. s: It represents the number of seconds in the current timezone. Example 1: PHP <?php // PHP program to get the // current date and time echo "Current date and time is :"; // Store the date and time to // the variable $myDate = date("d-m-y h:i:s"); // Display the date and time echo $myDate; ?> Output: Current date and time is :03-01-21 04:49:52 Example 2: The following demonstrates other date() functions format which can be used by the developer as per the need. PHP <!DOCTYPE html><html><body><h2>Other ways of using date() function</h2><?phpecho "Date in Year.Month.Day format is: " . date("Y.m.d") . "<br>"; echo "Date in Year-Month-day format is: " . date("Y-m-d") . "<br>"; echo "Date in Year/Month/day format is: " . date("Y/m/d") . "<br>"; ?></body></html> Output: PHP-date-time PHP-Misc PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? PHP in_array() Function How to delete an array element based on key in PHP? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to execute PHP code using command line ? How to delete an array element based on key in PHP? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to pop an alert message box using PHP ?
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jan, 2021" }, { "code": null, "e": 488, "s": 28, "text": "The purpose of the article is to get the current Date and Time in PHP. It is performed by using a simple in-built PHP function date(). The Date is an inbuilt function used to format the timestamp. The computer stores date and time in UNIX timestamp. This time is measured as a number of seconds since Jan 1, 1970. As this is difficult for humans to read, PHP converts timestamps to format in such a way that it is readable and more understandable to humans. " }, { "code": null, "e": 498, "s": 488, "text": "Syntax: " }, { "code": null, "e": 519, "s": 498, "text": "date('d-m-y h:i:s');" }, { "code": null, "e": 620, "s": 519, "text": "Parameters : The date() have different parameters. Each parameter represents some meaningful unit. " }, { "code": null, "e": 1015, "s": 620, "text": "d: It represents the day of the month which has two digits with leading zeros (01 or 31)m: It represents month in numbers with leading zeros (01 or 1)y: It represents a year in two digits (08 or 14).h: It represents the hour of the day in two digits with leading zeros (01 or 1)I: It represents the minute in the current time zone.s: It represents the number of seconds in the current timezone." }, { "code": null, "e": 1104, "s": 1015, "text": "d: It represents the day of the month which has two digits with leading zeros (01 or 31)" }, { "code": null, "e": 1167, "s": 1104, "text": "m: It represents month in numbers with leading zeros (01 or 1)" }, { "code": null, "e": 1217, "s": 1167, "text": "y: It represents a year in two digits (08 or 14)." }, { "code": null, "e": 1297, "s": 1217, "text": "h: It represents the hour of the day in two digits with leading zeros (01 or 1)" }, { "code": null, "e": 1351, "s": 1297, "text": "I: It represents the minute in the current time zone." }, { "code": null, "e": 1415, "s": 1351, "text": "s: It represents the number of seconds in the current timezone." }, { "code": null, "e": 1427, "s": 1415, "text": "Example 1: " }, { "code": null, "e": 1431, "s": 1427, "text": "PHP" }, { "code": "<?php // PHP program to get the // current date and time echo \"Current date and time is :\"; // Store the date and time to // the variable $myDate = date(\"d-m-y h:i:s\"); // Display the date and time echo $myDate; ?> ", "e": 1655, "s": 1431, "text": null }, { "code": null, "e": 1663, "s": 1655, "text": "Output:" }, { "code": null, "e": 1707, "s": 1663, "text": "Current date and time is :03-01-21 04:49:52" }, { "code": null, "e": 1827, "s": 1707, "text": "Example 2: The following demonstrates other date() functions format which can be used by the developer as per the need." }, { "code": null, "e": 1831, "s": 1827, "text": "PHP" }, { "code": "<!DOCTYPE html><html><body><h2>Other ways of using date() function</h2><?phpecho \"Date in Year.Month.Day format is: \" . date(\"Y.m.d\") . \"<br>\"; echo \"Date in Year-Month-day format is: \" . date(\"Y-m-d\") . \"<br>\"; echo \"Date in Year/Month/day format is: \" . date(\"Y/m/d\") . \"<br>\"; ?></body></html>", "e": 2143, "s": 1831, "text": null }, { "code": null, "e": 2151, "s": 2143, "text": "Output:" }, { "code": null, "e": 2165, "s": 2151, "text": "PHP-date-time" }, { "code": null, "e": 2174, "s": 2165, "text": "PHP-Misc" }, { "code": null, "e": 2178, "s": 2174, "text": "PHP" }, { "code": null, "e": 2191, "s": 2178, "text": "PHP Programs" }, { "code": null, "e": 2208, "s": 2191, "text": "Web Technologies" }, { "code": null, "e": 2212, "s": 2208, "text": "PHP" }, { "code": null, "e": 2310, "s": 2212, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2355, "s": 2310, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 2379, "s": 2355, "text": "PHP in_array() Function" }, { "code": null, "e": 2431, "s": 2379, "text": "How to delete an array element based on key in PHP?" }, { "code": null, "e": 2481, "s": 2431, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 2521, "s": 2481, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 2566, "s": 2521, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 2618, "s": 2566, "text": "How to delete an array element based on key in PHP?" }, { "code": null, "e": 2668, "s": 2618, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 2708, "s": 2668, "text": "How to convert array to string in PHP ?" } ]
ListField in serializers – Django REST Framework
29 Jul, 2021 In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField, CharField and BooleanField for storing and manipulating data through Django. Similarly, serializer also works with same principle and has fields that are used to create a serializer. This article revolves around ListField in Serializers in Django REST Framework. ListField is basically a list field that validates the input against a list of objects.It has the following arguments – child – A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated. allow_empty – Designates if empty lists are allowed. min_length – Validates that the list contains no fewer than this number of elements. max_length – Validates that the list contains no more than this number of elements. Syntax – field_name = serializers.ListField(*args, **kwargs) Example – For example, to validate a list of integers one might use something like the following: scores = serializers.ListField( child=serializers.IntegerField(min_value=0, max_value=100) ) To explain the usage of ListField, let’s use the same project setup from – How to Create a basic API using Django Rest Framework ?. Now that you have a file called serializers in your project, let’s create a serializer with ListField as the fields. Python3 # import serializer from rest_frameworkfrom rest_framework import serializers class Geeks(object): def __init__(self, integers): self.integers = integers # create a serializerclass GeeksSerializer(serializers.Serializer): # initialize fields integers = serializers.ListField( child = serializers.IntegerField(min_value = 0, max_value = 100) ) Now let us create some objects and try serializing them and check if they are actually working, Run, – Python manage.py shell Now, run following python commands in the shell # import everything from serializers >>> from apis.serializers import * # create a object of type Geeks >>> obj = Geeks([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) # serialize the object >>> serializer = GeeksSerializer(obj) # print serialized data >>> serializer.data {'integers': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]} Here is the output of all these operations on terminal – Note that prime motto of these fields is to impart validations, such as ListField validates the data to list only. Let’s check if these validations are working or not – # Create a dictionary and add invalid values >>> data = {} >>> data['integers'] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # dictionary created >>> data {'integers': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]} # deserialize the data >>> serializer = GeeksSerializer(data=data) # check if data is valid >>> serializer.is_valid() True # check the errors >>> serializer.errors {} Here is the output of these commands which clearly shows integers valid – Validations are part of Deserialization and not serialization. As explained earlier, serializing is process of converting already made data into another data type, so there is no requirement of these default validations out there. Deserialization requires validations as data needs to be saved to database or any more operation as specified. So if you serialize data using these fields that would work. gabaa406 Django-REST Python Django rest-framework Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jul, 2021" }, { "code": null, "e": 644, "s": 28, "text": "In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField, CharField and BooleanField for storing and manipulating data through Django. Similarly, serializer also works with same principle and has fields that are used to create a serializer. This article revolves around ListField in Serializers in Django REST Framework. " }, { "code": null, "e": 766, "s": 644, "text": "ListField is basically a list field that validates the input against a list of objects.It has the following arguments – " }, { "code": null, "e": 932, "s": 766, "text": "child – A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated." }, { "code": null, "e": 985, "s": 932, "text": "allow_empty – Designates if empty lists are allowed." }, { "code": null, "e": 1070, "s": 985, "text": "min_length – Validates that the list contains no fewer than this number of elements." }, { "code": null, "e": 1154, "s": 1070, "text": "max_length – Validates that the list contains no more than this number of elements." }, { "code": null, "e": 1165, "s": 1154, "text": "Syntax – " }, { "code": null, "e": 1217, "s": 1165, "text": "field_name = serializers.ListField(*args, **kwargs)" }, { "code": null, "e": 1317, "s": 1217, "text": "Example – For example, to validate a list of integers one might use something like the following: " }, { "code": null, "e": 1413, "s": 1317, "text": "scores = serializers.ListField(\n child=serializers.IntegerField(min_value=0, max_value=100)\n)" }, { "code": null, "e": 1666, "s": 1415, "text": "To explain the usage of ListField, let’s use the same project setup from – How to Create a basic API using Django Rest Framework ?. Now that you have a file called serializers in your project, let’s create a serializer with ListField as the fields. " }, { "code": null, "e": 1674, "s": 1666, "text": "Python3" }, { "code": "# import serializer from rest_frameworkfrom rest_framework import serializers class Geeks(object): def __init__(self, integers): self.integers = integers # create a serializerclass GeeksSerializer(serializers.Serializer): # initialize fields integers = serializers.ListField( child = serializers.IntegerField(min_value = 0, max_value = 100) )", "e": 2039, "s": 1674, "text": null }, { "code": null, "e": 2144, "s": 2039, "text": "Now let us create some objects and try serializing them and check if they are actually working, Run, – " }, { "code": null, "e": 2167, "s": 2144, "text": "Python manage.py shell" }, { "code": null, "e": 2217, "s": 2167, "text": "Now, run following python commands in the shell " }, { "code": null, "e": 2524, "s": 2217, "text": "# import everything from serializers\n>>> from apis.serializers import *\n\n# create a object of type Geeks\n>>> obj = Geeks([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n\n# serialize the object\n>>> serializer = GeeksSerializer(obj)\n\n# print serialized data\n>>> serializer.data\n{'integers': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}" }, { "code": null, "e": 2583, "s": 2524, "text": "Here is the output of all these operations on terminal – " }, { "code": null, "e": 2756, "s": 2585, "text": "Note that prime motto of these fields is to impart validations, such as ListField validates the data to list only. Let’s check if these validations are working or not – " }, { "code": null, "e": 3117, "s": 2756, "text": "# Create a dictionary and add invalid values\n>>> data = {}\n>>> data['integers'] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\n# dictionary created\n>>> data\n{'integers': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}\n\n# deserialize the data\n>>> serializer = GeeksSerializer(data=data)\n\n# check if data is valid\n>>> serializer.is_valid()\nTrue\n\n# check the errors\n>>> serializer.errors\n{}" }, { "code": null, "e": 3193, "s": 3117, "text": "Here is the output of these commands which clearly shows integers valid – " }, { "code": null, "e": 3599, "s": 3195, "text": "Validations are part of Deserialization and not serialization. As explained earlier, serializing is process of converting already made data into another data type, so there is no requirement of these default validations out there. Deserialization requires validations as data needs to be saved to database or any more operation as specified. So if you serialize data using these fields that would work. " }, { "code": null, "e": 3610, "s": 3601, "text": "gabaa406" }, { "code": null, "e": 3622, "s": 3610, "text": "Django-REST" }, { "code": null, "e": 3636, "s": 3622, "text": "Python Django" }, { "code": null, "e": 3651, "s": 3636, "text": "rest-framework" }, { "code": null, "e": 3658, "s": 3651, "text": "Python" }, { "code": null, "e": 3756, "s": 3658, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3774, "s": 3756, "text": "Python Dictionary" }, { "code": null, "e": 3816, "s": 3774, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3838, "s": 3816, "text": "Enumerate() in Python" }, { "code": null, "e": 3873, "s": 3838, "text": "Read a file line by line in Python" }, { "code": null, "e": 3899, "s": 3873, "text": "Python String | replace()" }, { "code": null, "e": 3931, "s": 3899, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3960, "s": 3931, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3990, "s": 3960, "text": "Iterate over a list in Python" }, { "code": null, "e": 4017, "s": 3990, "text": "Python Classes and Objects" } ]
Pair in Kotlin
02 Aug, 2019 In programming, we call functions to perform a particular task. The best thing about function is that we can call it any number of times and it return some value after computation i.e. if we are having add() function then it always returns the sum of both the numbers entered. But, functions has some limitations like function return only one value at a time. If there is need to return more than one value of different data type, then we can create a class and declare all the variables that we want to return from the function and after that create an object of the class and easily collect all the returned values in a list. The main problem is that if there are so many functions in the program which returns more than one value at a time then we have to create a separate class for all those functions and finally use that class. This process increases the verbosity and complexity of the program. In order to deal with these type of problems, Kotlin introduced the concept of Pair and Triple. Kotlin language provides a simple datatype to store two values in a single instance. This can be done using a data class known as Pair. It is a simple generic class that can store two values of same or different data types, and there can or can not be a relationship between the two values. The comparison between two Pair objects is done on the basis of values, i.e. two Pair objects are equal if their values are equal. Class Definition – data class Pair<out A, out B> : Serializable There are two parameters:A – type of the first valueB – type of the second value In Kotlin, constructor is a special member function that is invoked when an object of the class is created primarily to initialize variables or properties. To create a new instance of the Pair we use: Pair(first: A, second: B) Kotlin example of creating pair using the constructor – fun main() { val (x, y) = Pair(1, "Geeks") println(x) println(y)} Output: 1 Geeks We can either receive the values of pair in a single variable or we can use first and second properties to extract the values.first: This field stores the first value of the Pair.second: This field stores the second value of the Pair. Kotlin program to retrieve the values of Pair using properties – fun main() { // declare pair var pair = Pair("Hello Geeks", "This is Kotlin tutorial") println(pair.first) println(pair.second)} Output: Hello Geeks This is Kotlin tutorial toString(): This function returns the string equivalent of the Pair. fun toString(): String Kotlin program of using the function – fun main() { val obj = Pair(5,5) println("String representation is "+obj.toString()) val pair = Pair("Geeks", listOf("Praveen", "Gaurav", "Abhi")) print("Another string representation is "+pair.toString())} Output: String representation is (5, 5) Another string representation is (Geeks, [Praveen, Gaurav, Abhi]) As we have learnt in previous articles, extension functions gives ability to add more functionality to the existing classes, by without inheriting them.toList(): This function returns the List equivalent of the given Pair. fun <T>Pair<T, T>.toList(): List Kotlin program of using the extended function – fun main() { // first pair var obj = Pair(1,2) val list1: List<Any> = obj.toList() println(list1) // second pair var obj2 = Pair("Hello","Geeks") val list2: List<Any> = obj2.toList() println(list2)} Output [1, 2] [Hello, Geeks] Kotlin 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 Broadcast Receiver in Android With Example How to Communicate Between Fragments in Android? Content Providers in Android with Example Retrofit with Kotlin Coroutine in Android Kotlin constructor Kotlin Setters and Getters How to Add and Customize Back Button of Action Bar in Android? Suspend Function In Kotlin Coroutines
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Aug, 2019" }, { "code": null, "e": 305, "s": 28, "text": "In programming, we call functions to perform a particular task. The best thing about function is that we can call it any number of times and it return some value after computation i.e. if we are having add() function then it always returns the sum of both the numbers entered." }, { "code": null, "e": 931, "s": 305, "text": "But, functions has some limitations like function return only one value at a time. If there is need to return more than one value of different data type, then we can create a class and declare all the variables that we want to return from the function and after that create an object of the class and easily collect all the returned values in a list. The main problem is that if there are so many functions in the program which returns more than one value at a time then we have to create a separate class for all those functions and finally use that class. This process increases the verbosity and complexity of the program." }, { "code": null, "e": 1027, "s": 931, "text": "In order to deal with these type of problems, Kotlin introduced the concept of Pair and Triple." }, { "code": null, "e": 1449, "s": 1027, "text": "Kotlin language provides a simple datatype to store two values in a single instance. This can be done using a data class known as Pair. It is a simple generic class that can store two values of same or different data types, and there can or can not be a relationship between the two values. The comparison between two Pair objects is done on the basis of values, i.e. two Pair objects are equal if their values are equal." }, { "code": null, "e": 1468, "s": 1449, "text": "Class Definition –" }, { "code": null, "e": 1514, "s": 1468, "text": "data class Pair<out A, out B> : Serializable\n" }, { "code": null, "e": 1595, "s": 1514, "text": "There are two parameters:A – type of the first valueB – type of the second value" }, { "code": null, "e": 1796, "s": 1595, "text": "In Kotlin, constructor is a special member function that is invoked when an object of the class is created primarily to initialize variables or properties. To create a new instance of the Pair we use:" }, { "code": null, "e": 1822, "s": 1796, "text": "Pair(first: A, second: B)" }, { "code": null, "e": 1878, "s": 1822, "text": "Kotlin example of creating pair using the constructor –" }, { "code": "fun main() { val (x, y) = Pair(1, \"Geeks\") println(x) println(y)}", "e": 1953, "s": 1878, "text": null }, { "code": null, "e": 1961, "s": 1953, "text": "Output:" }, { "code": null, "e": 1970, "s": 1961, "text": "1\nGeeks\n" }, { "code": null, "e": 2205, "s": 1970, "text": "We can either receive the values of pair in a single variable or we can use first and second properties to extract the values.first: This field stores the first value of the Pair.second: This field stores the second value of the Pair." }, { "code": null, "e": 2270, "s": 2205, "text": "Kotlin program to retrieve the values of Pair using properties –" }, { "code": "fun main() { // declare pair var pair = Pair(\"Hello Geeks\", \"This is Kotlin tutorial\") println(pair.first) println(pair.second)}", "e": 2411, "s": 2270, "text": null }, { "code": null, "e": 2419, "s": 2411, "text": "Output:" }, { "code": null, "e": 2456, "s": 2419, "text": "Hello Geeks\nThis is Kotlin tutorial\n" }, { "code": null, "e": 2525, "s": 2456, "text": "toString(): This function returns the string equivalent of the Pair." }, { "code": null, "e": 2549, "s": 2525, "text": "fun toString(): String\n" }, { "code": null, "e": 2588, "s": 2549, "text": "Kotlin program of using the function –" }, { "code": "fun main() { val obj = Pair(5,5) println(\"String representation is \"+obj.toString()) val pair = Pair(\"Geeks\", listOf(\"Praveen\", \"Gaurav\", \"Abhi\")) print(\"Another string representation is \"+pair.toString())}", "e": 2807, "s": 2588, "text": null }, { "code": null, "e": 2815, "s": 2807, "text": "Output:" }, { "code": null, "e": 2914, "s": 2815, "text": "String representation is (5, 5)\nAnother string representation is (Geeks, [Praveen, Gaurav, Abhi])\n" }, { "code": null, "e": 3137, "s": 2914, "text": "As we have learnt in previous articles, extension functions gives ability to add more functionality to the existing classes, by without inheriting them.toList(): This function returns the List equivalent of the given Pair." }, { "code": null, "e": 3171, "s": 3137, "text": "fun <T>Pair<T, T>.toList(): List\n" }, { "code": null, "e": 3219, "s": 3171, "text": "Kotlin program of using the extended function –" }, { "code": "fun main() { // first pair var obj = Pair(1,2) val list1: List<Any> = obj.toList() println(list1) // second pair var obj2 = Pair(\"Hello\",\"Geeks\") val list2: List<Any> = obj2.toList() println(list2)}", "e": 3442, "s": 3219, "text": null }, { "code": null, "e": 3449, "s": 3442, "text": "Output" }, { "code": null, "e": 3472, "s": 3449, "text": "[1, 2]\n[Hello, Geeks]\n" }, { "code": null, "e": 3479, "s": 3472, "text": "Kotlin" }, { "code": null, "e": 3577, "s": 3479, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3646, "s": 3577, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 3677, "s": 3646, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 3720, "s": 3677, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 3769, "s": 3720, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 3811, "s": 3769, "text": "Content Providers in Android with Example" }, { "code": null, "e": 3853, "s": 3811, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 3872, "s": 3853, "text": "Kotlin constructor" }, { "code": null, "e": 3899, "s": 3872, "text": "Kotlin Setters and Getters" }, { "code": null, "e": 3962, "s": 3899, "text": "How to Add and Customize Back Button of Action Bar in Android?" } ]
Save Files in ElectronJS
28 May, 2020 ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. Any native desktop application should integrate itself with the System OS environment. The application should have the ability to interact with core OS functionalities such as the File System, System Tray, etc. Electron provides us with built-in dialog module to display the native System dialogs for interacting with files. This tutorial will use the instance method of the dialog module to demonstrate how to Save Files locally in Electron. We assume you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system. dialog Module: The dialog Module is part of the Main Process. To import and use the dialog Module in the Renderer Process, we will be using Electron remote module. For more details on the remote module, Refer this link. Project Structure: Example: We will start by building the Electron Application for Saving files to local System by following the given steps. Step 1: Navigate to an Empty Directory to setup the project, and run the following command.npm initTo generate the package.json file. Install Electron using npm if it is not installed.npm install electron --saveThis command will also create the package-lock.json file and install the required node_modules dependencies. Create the assets folder according to the project structure. We will save the new files to this folder from the native dialog.package.json:{ "name": "electron-save", "version": "1.0.0", "description": "Save Files to local in Electron", "main": "main.js", "scripts": { "start": "electron ." }, "keywords": [ "electron" ], "author": "Radhesh Khanna", "license": "ISC", "dependencies": { "electron": "^8.2.5" } } npm init To generate the package.json file. Install Electron using npm if it is not installed. npm install electron --save This command will also create the package-lock.json file and install the required node_modules dependencies. Create the assets folder according to the project structure. We will save the new files to this folder from the native dialog.package.json: { "name": "electron-save", "version": "1.0.0", "description": "Save Files to local in Electron", "main": "main.js", "scripts": { "start": "electron ." }, "keywords": [ "electron" ], "author": "Radhesh Khanna", "license": "ISC", "dependencies": { "electron": "^8.2.5" } } Step 2: Create the main.js file according to the project structure. This file is the Main Process and acts as an entry point into the application. Copy the Boilerplate code for the main.js file as given in the following link. We have modified the code to suit our project needs.main.js:const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.// This method is equivalent to 'app.on('ready', function())'app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are no // other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your // app's specific main process code. You can also // put them in separate files and require them here. main.js: const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.// This method is equivalent to 'app.on('ready', function())'app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are no // other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your // app's specific main process code. You can also // put them in separate files and require them here. Step 3: Create the index.html file and index.js file within the src directory. We will also copy the boilerplate code for the index.html file from the above-mentioned link. We have modified the code to suit our project needs.index.html:<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" /> </head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <br><br> <button id="save">Save sample.txt to local System</button> <!-- Adding Individual Renderer Process JS File --> <script src="index.js"></script> </body></html>Output: At this point, our application is set up and we can launch the application to check the GUI Output. To launch the Electron Application, run the Command:npm start index.html: <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" /> </head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <br><br> <button id="save">Save sample.txt to local System</button> <!-- Adding Individual Renderer Process JS File --> <script src="index.js"></script> </body></html> Output: At this point, our application is set up and we can launch the application to check the GUI Output. To launch the Electron Application, run the Command: npm start Step 4: The Save sample.txt to local System button does not have any functionality associated with it yet.index.js: Add the following snippet in that file.const electron = require('electron');const path = require('path');const fs = require('fs');// Importing dialog module using remoteconst dialog = electron.remote.dialog; var save = document.getElementById('save'); save.addEventListener('click', (event) => { // Resolves to a Promise<Object> dialog.showSaveDialog({ title: 'Select the File Path to save', defaultPath: path.join(__dirname, '../assets/sample.txt'), // defaultPath: path.join(__dirname, '../assets/'), buttonLabel: 'Save', // Restricting the user to only Text Files. filters: [ { name: 'Text Files', extensions: ['txt', 'docx'] }, ], properties: [] }).then(file => { // Stating whether dialog operation was cancelled or not. console.log(file.canceled); if (!file.canceled) { console.log(file.filePath.toString()); // Creating and Writing to the sample.txt file fs.writeFile(file.filePath.toString(), 'This is a Sample File', function (err) { if (err) throw err; console.log('Saved!'); }); } }).catch(err => { console.log(err) });});The dialog.showSaveDialog(browserWindow, options) takes in the following parameters. For more detailed information on dialog.showSaveDialog() method, Refer this link.browserWindow: BrowserWindow (Optional) The BrowserWindow Instance. This argument allows the native dialog to attach itself to the parent window, making it a modal. A modal window is a child window that disables the parent window. If BrowserWindow Instance is not shown, dialog will not be attached to it. In such case It will be displayed as independent window. In the above code, the BrowserWindow instance is not being passed to the dialog, therefore the dialog opens as an independent window on clicking the Save sample.txt to local System button. For more detailed information on BrowserWindow Object and Modal window, Refer this link.options: Object It takes in the following parameters,title: String (Optional) The title to be displayed on the dialog window.defaultPath: String (Optional) The Absolute directory path, the absolute file path or the file name to be opened/used by default on clicking the Save sample.txt to local System button. In case, we specify the absolute directory path, the file Explorer will navigate to that directory but will not populate the File name: text field in the dialog window. In case, the absolute file path is specified along with the file name and extension, the File name: text field will be auto-populated as shown in the code. In both of these cases the file path and the file name can be changed from within the dialog window.buttonLabel: String (Optional) Custom label for the confirmation Button. If empty, the default label will be used. In the above code it is defined as Save.message: String (Optional) This parameter is supported in macOS only. This is used to display the custom message above the text fields.nameFieldLabel: String (Optional) This parameter is supported in macOS only. It defines a custom label for the text displayed in front of the File name: text field.showsTagField: Boolean (Optional) This parameter is supported in macOS only. It shows the tags input box to assign custom tags to files. Default value is true.securityScopedBookmarks: Boolean (Optional) This parameter is supported in macOS only. This parameter is used to create security scoped bookmark when packaged for the Mac App Store. If this option is set to true and the file does not exist then a blank file will be created at the chosen path. For more detailed Information, Refer this link.filters: FileFilter[{}] (Optional) It is an Array of Objects. It defines an array of file types that can be displayed when we want to limit the user to a specific type. We can define multiple file types object belonging to different categories. The FileFilter object takes in the following parameters,name: String The name of the category of extensions.extensions: String[] The extensions array should consist of extensions without wildcards or dots as demonstrated in the code. To show all files, use the * wildcard (no other wildcard is supported). For more detailed Information, Refer this link.In the above code, we want to restrict the user to Text files only. Hence we have defined the name as Text Files and the extensions array as [‘txt’, ‘docx’].properties: String[] (Optional) Contains a list of features which are available for the native dialog. It take take in the following values,showHiddenFiles: Show Hidden files in dialog.createDirectory: This value is supported in macOS only. It allows creating new directories from within the dialog. In Windows, the context-menu is pre-available in the dialog (right-click in dialog window) and we can create new files and directories from it.treatPackageAsDirectory: This value is supported in macOS only. It treats packages such as .app folders, as a directory instead of a file.dontAddToRecent: This value is supported in Windows only. This value signifies that the file being saved should not be added to the recent documents list.showOverwriteConfirmation: This value is supported in Linux only. This value defines whether the user should be presented with a confirmation dialog if the user types in a file name that already exists in that directory.The dialog.showSaveDialog(browserWindow, options) returns a Promise. It resolves to an Object containing the following parameters,canceled: Boolean Whether or not the dialog operation was cancelled.filePath: String (Optional) The file path chosen by the user. If the dialog operation is cancelled, it is going to be undefined.bookmark: String (Optional) This return String is supported in macOS only. It is a Base64 encoded String which contains the security scoped bookmark data for the saved file. This is returned when the securityScopedBookmarks parameter is defined as true in the options Object. For the different return values, Refer this link.The fs.writeFile(file, data, options, callback) method is used to write the specified data to a file. By default, this will replace the file if it exists at the defined file path. We have specified the absolute file path, the String data to be written and a callback for handling Error in the above code. We can use the options parameter to modify the functionality. For more detailed Information, Refer this link.We should now be able to successfully choose the file path from the dialog window, give a new file name (if required, in our code will be sample.txt by default) and save the newly created sample.txt file at that path.Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/20200514211548/Output-27.mp400:0000:0000:25Use Up/Down Arrow keys to increase or decrease volume. const electron = require('electron');const path = require('path');const fs = require('fs');// Importing dialog module using remoteconst dialog = electron.remote.dialog; var save = document.getElementById('save'); save.addEventListener('click', (event) => { // Resolves to a Promise<Object> dialog.showSaveDialog({ title: 'Select the File Path to save', defaultPath: path.join(__dirname, '../assets/sample.txt'), // defaultPath: path.join(__dirname, '../assets/'), buttonLabel: 'Save', // Restricting the user to only Text Files. filters: [ { name: 'Text Files', extensions: ['txt', 'docx'] }, ], properties: [] }).then(file => { // Stating whether dialog operation was cancelled or not. console.log(file.canceled); if (!file.canceled) { console.log(file.filePath.toString()); // Creating and Writing to the sample.txt file fs.writeFile(file.filePath.toString(), 'This is a Sample File', function (err) { if (err) throw err; console.log('Saved!'); }); } }).catch(err => { console.log(err) });}); The dialog.showSaveDialog(browserWindow, options) takes in the following parameters. For more detailed information on dialog.showSaveDialog() method, Refer this link. browserWindow: BrowserWindow (Optional) The BrowserWindow Instance. This argument allows the native dialog to attach itself to the parent window, making it a modal. A modal window is a child window that disables the parent window. If BrowserWindow Instance is not shown, dialog will not be attached to it. In such case It will be displayed as independent window. In the above code, the BrowserWindow instance is not being passed to the dialog, therefore the dialog opens as an independent window on clicking the Save sample.txt to local System button. For more detailed information on BrowserWindow Object and Modal window, Refer this link. options: Object It takes in the following parameters,title: String (Optional) The title to be displayed on the dialog window.defaultPath: String (Optional) The Absolute directory path, the absolute file path or the file name to be opened/used by default on clicking the Save sample.txt to local System button. In case, we specify the absolute directory path, the file Explorer will navigate to that directory but will not populate the File name: text field in the dialog window. In case, the absolute file path is specified along with the file name and extension, the File name: text field will be auto-populated as shown in the code. In both of these cases the file path and the file name can be changed from within the dialog window.buttonLabel: String (Optional) Custom label for the confirmation Button. If empty, the default label will be used. In the above code it is defined as Save.message: String (Optional) This parameter is supported in macOS only. This is used to display the custom message above the text fields.nameFieldLabel: String (Optional) This parameter is supported in macOS only. It defines a custom label for the text displayed in front of the File name: text field.showsTagField: Boolean (Optional) This parameter is supported in macOS only. It shows the tags input box to assign custom tags to files. Default value is true.securityScopedBookmarks: Boolean (Optional) This parameter is supported in macOS only. This parameter is used to create security scoped bookmark when packaged for the Mac App Store. If this option is set to true and the file does not exist then a blank file will be created at the chosen path. For more detailed Information, Refer this link.filters: FileFilter[{}] (Optional) It is an Array of Objects. It defines an array of file types that can be displayed when we want to limit the user to a specific type. We can define multiple file types object belonging to different categories. The FileFilter object takes in the following parameters,name: String The name of the category of extensions.extensions: String[] The extensions array should consist of extensions without wildcards or dots as demonstrated in the code. To show all files, use the * wildcard (no other wildcard is supported). For more detailed Information, Refer this link.In the above code, we want to restrict the user to Text files only. Hence we have defined the name as Text Files and the extensions array as [‘txt’, ‘docx’].properties: String[] (Optional) Contains a list of features which are available for the native dialog. It take take in the following values,showHiddenFiles: Show Hidden files in dialog.createDirectory: This value is supported in macOS only. It allows creating new directories from within the dialog. In Windows, the context-menu is pre-available in the dialog (right-click in dialog window) and we can create new files and directories from it.treatPackageAsDirectory: This value is supported in macOS only. It treats packages such as .app folders, as a directory instead of a file.dontAddToRecent: This value is supported in Windows only. This value signifies that the file being saved should not be added to the recent documents list.showOverwriteConfirmation: This value is supported in Linux only. This value defines whether the user should be presented with a confirmation dialog if the user types in a file name that already exists in that directory. title: String (Optional) The title to be displayed on the dialog window. defaultPath: String (Optional) The Absolute directory path, the absolute file path or the file name to be opened/used by default on clicking the Save sample.txt to local System button. In case, we specify the absolute directory path, the file Explorer will navigate to that directory but will not populate the File name: text field in the dialog window. In case, the absolute file path is specified along with the file name and extension, the File name: text field will be auto-populated as shown in the code. In both of these cases the file path and the file name can be changed from within the dialog window. buttonLabel: String (Optional) Custom label for the confirmation Button. If empty, the default label will be used. In the above code it is defined as Save. message: String (Optional) This parameter is supported in macOS only. This is used to display the custom message above the text fields. nameFieldLabel: String (Optional) This parameter is supported in macOS only. It defines a custom label for the text displayed in front of the File name: text field. showsTagField: Boolean (Optional) This parameter is supported in macOS only. It shows the tags input box to assign custom tags to files. Default value is true. securityScopedBookmarks: Boolean (Optional) This parameter is supported in macOS only. This parameter is used to create security scoped bookmark when packaged for the Mac App Store. If this option is set to true and the file does not exist then a blank file will be created at the chosen path. For more detailed Information, Refer this link. filters: FileFilter[{}] (Optional) It is an Array of Objects. It defines an array of file types that can be displayed when we want to limit the user to a specific type. We can define multiple file types object belonging to different categories. The FileFilter object takes in the following parameters,name: String The name of the category of extensions.extensions: String[] The extensions array should consist of extensions without wildcards or dots as demonstrated in the code. To show all files, use the * wildcard (no other wildcard is supported). For more detailed Information, Refer this link.In the above code, we want to restrict the user to Text files only. Hence we have defined the name as Text Files and the extensions array as [‘txt’, ‘docx’]. name: String The name of the category of extensions. extensions: String[] The extensions array should consist of extensions without wildcards or dots as demonstrated in the code. To show all files, use the * wildcard (no other wildcard is supported). For more detailed Information, Refer this link. In the above code, we want to restrict the user to Text files only. Hence we have defined the name as Text Files and the extensions array as [‘txt’, ‘docx’]. properties: String[] (Optional) Contains a list of features which are available for the native dialog. It take take in the following values,showHiddenFiles: Show Hidden files in dialog.createDirectory: This value is supported in macOS only. It allows creating new directories from within the dialog. In Windows, the context-menu is pre-available in the dialog (right-click in dialog window) and we can create new files and directories from it.treatPackageAsDirectory: This value is supported in macOS only. It treats packages such as .app folders, as a directory instead of a file.dontAddToRecent: This value is supported in Windows only. This value signifies that the file being saved should not be added to the recent documents list.showOverwriteConfirmation: This value is supported in Linux only. This value defines whether the user should be presented with a confirmation dialog if the user types in a file name that already exists in that directory. showHiddenFiles: Show Hidden files in dialog. createDirectory: This value is supported in macOS only. It allows creating new directories from within the dialog. In Windows, the context-menu is pre-available in the dialog (right-click in dialog window) and we can create new files and directories from it. treatPackageAsDirectory: This value is supported in macOS only. It treats packages such as .app folders, as a directory instead of a file. dontAddToRecent: This value is supported in Windows only. This value signifies that the file being saved should not be added to the recent documents list. showOverwriteConfirmation: This value is supported in Linux only. This value defines whether the user should be presented with a confirmation dialog if the user types in a file name that already exists in that directory. The dialog.showSaveDialog(browserWindow, options) returns a Promise. It resolves to an Object containing the following parameters, canceled: Boolean Whether or not the dialog operation was cancelled. filePath: String (Optional) The file path chosen by the user. If the dialog operation is cancelled, it is going to be undefined. bookmark: String (Optional) This return String is supported in macOS only. It is a Base64 encoded String which contains the security scoped bookmark data for the saved file. This is returned when the securityScopedBookmarks parameter is defined as true in the options Object. For the different return values, Refer this link. The fs.writeFile(file, data, options, callback) method is used to write the specified data to a file. By default, this will replace the file if it exists at the defined file path. We have specified the absolute file path, the String data to be written and a callback for handling Error in the above code. We can use the options parameter to modify the functionality. For more detailed Information, Refer this link. We should now be able to successfully choose the file path from the dialog window, give a new file name (if required, in our code will be sample.txt by default) and save the newly created sample.txt file at that path.Output: ElectronJS 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 How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request 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": "\n28 May, 2020" }, { "code": null, "e": 328, "s": 28, "text": "ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime." }, { "code": null, "e": 771, "s": 328, "text": "Any native desktop application should integrate itself with the System OS environment. The application should have the ability to interact with core OS functionalities such as the File System, System Tray, etc. Electron provides us with built-in dialog module to display the native System dialogs for interacting with files. This tutorial will use the instance method of the dialog module to demonstrate how to Save Files locally in Electron." }, { "code": null, "e": 936, "s": 771, "text": "We assume you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system." }, { "code": null, "e": 1156, "s": 936, "text": "dialog Module: The dialog Module is part of the Main Process. To import and use the dialog Module in the Renderer Process, we will be using Electron remote module. For more details on the remote module, Refer this link." }, { "code": null, "e": 1175, "s": 1156, "text": "Project Structure:" }, { "code": null, "e": 1298, "s": 1175, "text": "Example: We will start by building the Electron Application for Saving files to local System by following the given steps." }, { "code": null, "e": 2065, "s": 1298, "text": "Step 1: Navigate to an Empty Directory to setup the project, and run the following command.npm initTo generate the package.json file. Install Electron using npm if it is not installed.npm install electron --saveThis command will also create the package-lock.json file and install the required node_modules dependencies. Create the assets folder according to the project structure. We will save the new files to this folder from the native dialog.package.json:{\n \"name\": \"electron-save\",\n \"version\": \"1.0.0\",\n \"description\": \"Save Files to local in Electron\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.2.5\"\n }\n}\n" }, { "code": null, "e": 2074, "s": 2065, "text": "npm init" }, { "code": null, "e": 2160, "s": 2074, "text": "To generate the package.json file. Install Electron using npm if it is not installed." }, { "code": null, "e": 2188, "s": 2160, "text": "npm install electron --save" }, { "code": null, "e": 2437, "s": 2188, "text": "This command will also create the package-lock.json file and install the required node_modules dependencies. Create the assets folder according to the project structure. We will save the new files to this folder from the native dialog.package.json:" }, { "code": null, "e": 2745, "s": 2437, "text": "{\n \"name\": \"electron-save\",\n \"version\": \"1.0.0\",\n \"description\": \"Save Files to local in Electron\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.2.5\"\n }\n}\n" }, { "code": null, "e": 4307, "s": 2745, "text": "Step 2: Create the main.js file according to the project structure. This file is the Main Process and acts as an entry point into the application. Copy the Boilerplate code for the main.js file as given in the following link. We have modified the code to suit our project needs.main.js:const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.// This method is equivalent to 'app.on('ready', function())'app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are no // other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your // app's specific main process code. You can also // put them in separate files and require them here." }, { "code": null, "e": 4316, "s": 4307, "text": "main.js:" }, { "code": "const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.// This method is equivalent to 'app.on('ready', function())'app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are no // other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your // app's specific main process code. You can also // put them in separate files and require them here.", "e": 5592, "s": 4316, "text": null }, { "code": null, "e": 6776, "s": 5592, "text": "Step 3: Create the index.html file and index.js file within the src directory. We will also copy the boilerplate code for the index.html file from the above-mentioned link. We have modified the code to suit our project needs.index.html:<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'self' 'unsafe-inline';\" /> </head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <br><br> <button id=\"save\">Save sample.txt to local System</button> <!-- Adding Individual Renderer Process JS File --> <script src=\"index.js\"></script> </body></html>Output: At this point, our application is set up and we can launch the application to check the GUI Output. To launch the Electron Application, run the Command:npm start" }, { "code": null, "e": 6788, "s": 6776, "text": "index.html:" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'self' 'unsafe-inline';\" /> </head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <br><br> <button id=\"save\">Save sample.txt to local System</button> <!-- Adding Individual Renderer Process JS File --> <script src=\"index.js\"></script> </body></html>", "e": 7567, "s": 6788, "text": null }, { "code": null, "e": 7728, "s": 7567, "text": "Output: At this point, our application is set up and we can launch the application to check the GUI Output. To launch the Electron Application, run the Command:" }, { "code": null, "e": 7738, "s": 7728, "text": "npm start" }, { "code": null, "e": 14808, "s": 7738, "text": "Step 4: The Save sample.txt to local System button does not have any functionality associated with it yet.index.js: Add the following snippet in that file.const electron = require('electron');const path = require('path');const fs = require('fs');// Importing dialog module using remoteconst dialog = electron.remote.dialog; var save = document.getElementById('save'); save.addEventListener('click', (event) => { // Resolves to a Promise<Object> dialog.showSaveDialog({ title: 'Select the File Path to save', defaultPath: path.join(__dirname, '../assets/sample.txt'), // defaultPath: path.join(__dirname, '../assets/'), buttonLabel: 'Save', // Restricting the user to only Text Files. filters: [ { name: 'Text Files', extensions: ['txt', 'docx'] }, ], properties: [] }).then(file => { // Stating whether dialog operation was cancelled or not. console.log(file.canceled); if (!file.canceled) { console.log(file.filePath.toString()); // Creating and Writing to the sample.txt file fs.writeFile(file.filePath.toString(), 'This is a Sample File', function (err) { if (err) throw err; console.log('Saved!'); }); } }).catch(err => { console.log(err) });});The dialog.showSaveDialog(browserWindow, options) takes in the following parameters. For more detailed information on dialog.showSaveDialog() method, Refer this link.browserWindow: BrowserWindow (Optional) The BrowserWindow Instance. This argument allows the native dialog to attach itself to the parent window, making it a modal. A modal window is a child window that disables the parent window. If BrowserWindow Instance is not shown, dialog will not be attached to it. In such case It will be displayed as independent window. In the above code, the BrowserWindow instance is not being passed to the dialog, therefore the dialog opens as an independent window on clicking the Save sample.txt to local System button. For more detailed information on BrowserWindow Object and Modal window, Refer this link.options: Object It takes in the following parameters,title: String (Optional) The title to be displayed on the dialog window.defaultPath: String (Optional) The Absolute directory path, the absolute file path or the file name to be opened/used by default on clicking the Save sample.txt to local System button. In case, we specify the absolute directory path, the file Explorer will navigate to that directory but will not populate the File name: text field in the dialog window. In case, the absolute file path is specified along with the file name and extension, the File name: text field will be auto-populated as shown in the code. In both of these cases the file path and the file name can be changed from within the dialog window.buttonLabel: String (Optional) Custom label for the confirmation Button. If empty, the default label will be used. In the above code it is defined as Save.message: String (Optional) This parameter is supported in macOS only. This is used to display the custom message above the text fields.nameFieldLabel: String (Optional) This parameter is supported in macOS only. It defines a custom label for the text displayed in front of the File name: text field.showsTagField: Boolean (Optional) This parameter is supported in macOS only. It shows the tags input box to assign custom tags to files. Default value is true.securityScopedBookmarks: Boolean (Optional) This parameter is supported in macOS only. This parameter is used to create security scoped bookmark when packaged for the Mac App Store. If this option is set to true and the file does not exist then a blank file will be created at the chosen path. For more detailed Information, Refer this link.filters: FileFilter[{}] (Optional) It is an Array of Objects. It defines an array of file types that can be displayed when we want to limit the user to a specific type. We can define multiple file types object belonging to different categories. The FileFilter object takes in the following parameters,name: String The name of the category of extensions.extensions: String[] The extensions array should consist of extensions without wildcards or dots as demonstrated in the code. To show all files, use the * wildcard (no other wildcard is supported). For more detailed Information, Refer this link.In the above code, we want to restrict the user to Text files only. Hence we have defined the name as Text Files and the extensions array as [‘txt’, ‘docx’].properties: String[] (Optional) Contains a list of features which are available for the native dialog. It take take in the following values,showHiddenFiles: Show Hidden files in dialog.createDirectory: This value is supported in macOS only. It allows creating new directories from within the dialog. In Windows, the context-menu is pre-available in the dialog (right-click in dialog window) and we can create new files and directories from it.treatPackageAsDirectory: This value is supported in macOS only. It treats packages such as .app folders, as a directory instead of a file.dontAddToRecent: This value is supported in Windows only. This value signifies that the file being saved should not be added to the recent documents list.showOverwriteConfirmation: This value is supported in Linux only. This value defines whether the user should be presented with a confirmation dialog if the user types in a file name that already exists in that directory.The dialog.showSaveDialog(browserWindow, options) returns a Promise. It resolves to an Object containing the following parameters,canceled: Boolean Whether or not the dialog operation was cancelled.filePath: String (Optional) The file path chosen by the user. If the dialog operation is cancelled, it is going to be undefined.bookmark: String (Optional) This return String is supported in macOS only. It is a Base64 encoded String which contains the security scoped bookmark data for the saved file. This is returned when the securityScopedBookmarks parameter is defined as true in the options Object. For the different return values, Refer this link.The fs.writeFile(file, data, options, callback) method is used to write the specified data to a file. By default, this will replace the file if it exists at the defined file path. We have specified the absolute file path, the String data to be written and a callback for handling Error in the above code. We can use the options parameter to modify the functionality. For more detailed Information, Refer this link.We should now be able to successfully choose the file path from the dialog window, give a new file name (if required, in our code will be sample.txt by default) and save the newly created sample.txt file at that path.Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/20200514211548/Output-27.mp400:0000:0000:25Use Up/Down Arrow keys to increase or decrease volume." }, { "code": "const electron = require('electron');const path = require('path');const fs = require('fs');// Importing dialog module using remoteconst dialog = electron.remote.dialog; var save = document.getElementById('save'); save.addEventListener('click', (event) => { // Resolves to a Promise<Object> dialog.showSaveDialog({ title: 'Select the File Path to save', defaultPath: path.join(__dirname, '../assets/sample.txt'), // defaultPath: path.join(__dirname, '../assets/'), buttonLabel: 'Save', // Restricting the user to only Text Files. filters: [ { name: 'Text Files', extensions: ['txt', 'docx'] }, ], properties: [] }).then(file => { // Stating whether dialog operation was cancelled or not. console.log(file.canceled); if (!file.canceled) { console.log(file.filePath.toString()); // Creating and Writing to the sample.txt file fs.writeFile(file.filePath.toString(), 'This is a Sample File', function (err) { if (err) throw err; console.log('Saved!'); }); } }).catch(err => { console.log(err) });});", "e": 16069, "s": 14808, "text": null }, { "code": null, "e": 16236, "s": 16069, "text": "The dialog.showSaveDialog(browserWindow, options) takes in the following parameters. For more detailed information on dialog.showSaveDialog() method, Refer this link." }, { "code": null, "e": 16877, "s": 16236, "text": "browserWindow: BrowserWindow (Optional) The BrowserWindow Instance. This argument allows the native dialog to attach itself to the parent window, making it a modal. A modal window is a child window that disables the parent window. If BrowserWindow Instance is not shown, dialog will not be attached to it. In such case It will be displayed as independent window. In the above code, the BrowserWindow instance is not being passed to the dialog, therefore the dialog opens as an independent window on clicking the Save sample.txt to local System button. For more detailed information on BrowserWindow Object and Modal window, Refer this link." }, { "code": null, "e": 20277, "s": 16877, "text": "options: Object It takes in the following parameters,title: String (Optional) The title to be displayed on the dialog window.defaultPath: String (Optional) The Absolute directory path, the absolute file path or the file name to be opened/used by default on clicking the Save sample.txt to local System button. In case, we specify the absolute directory path, the file Explorer will navigate to that directory but will not populate the File name: text field in the dialog window. In case, the absolute file path is specified along with the file name and extension, the File name: text field will be auto-populated as shown in the code. In both of these cases the file path and the file name can be changed from within the dialog window.buttonLabel: String (Optional) Custom label for the confirmation Button. If empty, the default label will be used. In the above code it is defined as Save.message: String (Optional) This parameter is supported in macOS only. This is used to display the custom message above the text fields.nameFieldLabel: String (Optional) This parameter is supported in macOS only. It defines a custom label for the text displayed in front of the File name: text field.showsTagField: Boolean (Optional) This parameter is supported in macOS only. It shows the tags input box to assign custom tags to files. Default value is true.securityScopedBookmarks: Boolean (Optional) This parameter is supported in macOS only. This parameter is used to create security scoped bookmark when packaged for the Mac App Store. If this option is set to true and the file does not exist then a blank file will be created at the chosen path. For more detailed Information, Refer this link.filters: FileFilter[{}] (Optional) It is an Array of Objects. It defines an array of file types that can be displayed when we want to limit the user to a specific type. We can define multiple file types object belonging to different categories. The FileFilter object takes in the following parameters,name: String The name of the category of extensions.extensions: String[] The extensions array should consist of extensions without wildcards or dots as demonstrated in the code. To show all files, use the * wildcard (no other wildcard is supported). For more detailed Information, Refer this link.In the above code, we want to restrict the user to Text files only. Hence we have defined the name as Text Files and the extensions array as [‘txt’, ‘docx’].properties: String[] (Optional) Contains a list of features which are available for the native dialog. It take take in the following values,showHiddenFiles: Show Hidden files in dialog.createDirectory: This value is supported in macOS only. It allows creating new directories from within the dialog. In Windows, the context-menu is pre-available in the dialog (right-click in dialog window) and we can create new files and directories from it.treatPackageAsDirectory: This value is supported in macOS only. It treats packages such as .app folders, as a directory instead of a file.dontAddToRecent: This value is supported in Windows only. This value signifies that the file being saved should not be added to the recent documents list.showOverwriteConfirmation: This value is supported in Linux only. This value defines whether the user should be presented with a confirmation dialog if the user types in a file name that already exists in that directory." }, { "code": null, "e": 20350, "s": 20277, "text": "title: String (Optional) The title to be displayed on the dialog window." }, { "code": null, "e": 20961, "s": 20350, "text": "defaultPath: String (Optional) The Absolute directory path, the absolute file path or the file name to be opened/used by default on clicking the Save sample.txt to local System button. In case, we specify the absolute directory path, the file Explorer will navigate to that directory but will not populate the File name: text field in the dialog window. In case, the absolute file path is specified along with the file name and extension, the File name: text field will be auto-populated as shown in the code. In both of these cases the file path and the file name can be changed from within the dialog window." }, { "code": null, "e": 21117, "s": 20961, "text": "buttonLabel: String (Optional) Custom label for the confirmation Button. If empty, the default label will be used. In the above code it is defined as Save." }, { "code": null, "e": 21253, "s": 21117, "text": "message: String (Optional) This parameter is supported in macOS only. This is used to display the custom message above the text fields." }, { "code": null, "e": 21418, "s": 21253, "text": "nameFieldLabel: String (Optional) This parameter is supported in macOS only. It defines a custom label for the text displayed in front of the File name: text field." }, { "code": null, "e": 21578, "s": 21418, "text": "showsTagField: Boolean (Optional) This parameter is supported in macOS only. It shows the tags input box to assign custom tags to files. Default value is true." }, { "code": null, "e": 21920, "s": 21578, "text": "securityScopedBookmarks: Boolean (Optional) This parameter is supported in macOS only. This parameter is used to create security scoped bookmark when packaged for the Mac App Store. If this option is set to true and the file does not exist then a blank file will be created at the chosen path. For more detailed Information, Refer this link." }, { "code": null, "e": 22676, "s": 21920, "text": "filters: FileFilter[{}] (Optional) It is an Array of Objects. It defines an array of file types that can be displayed when we want to limit the user to a specific type. We can define multiple file types object belonging to different categories. The FileFilter object takes in the following parameters,name: String The name of the category of extensions.extensions: String[] The extensions array should consist of extensions without wildcards or dots as demonstrated in the code. To show all files, use the * wildcard (no other wildcard is supported). For more detailed Information, Refer this link.In the above code, we want to restrict the user to Text files only. Hence we have defined the name as Text Files and the extensions array as [‘txt’, ‘docx’]." }, { "code": null, "e": 22729, "s": 22676, "text": "name: String The name of the category of extensions." }, { "code": null, "e": 22975, "s": 22729, "text": "extensions: String[] The extensions array should consist of extensions without wildcards or dots as demonstrated in the code. To show all files, use the * wildcard (no other wildcard is supported). For more detailed Information, Refer this link." }, { "code": null, "e": 23133, "s": 22975, "text": "In the above code, we want to restrict the user to Text files only. Hence we have defined the name as Text Files and the extensions array as [‘txt’, ‘docx’]." }, { "code": null, "e": 24089, "s": 23133, "text": "properties: String[] (Optional) Contains a list of features which are available for the native dialog. It take take in the following values,showHiddenFiles: Show Hidden files in dialog.createDirectory: This value is supported in macOS only. It allows creating new directories from within the dialog. In Windows, the context-menu is pre-available in the dialog (right-click in dialog window) and we can create new files and directories from it.treatPackageAsDirectory: This value is supported in macOS only. It treats packages such as .app folders, as a directory instead of a file.dontAddToRecent: This value is supported in Windows only. This value signifies that the file being saved should not be added to the recent documents list.showOverwriteConfirmation: This value is supported in Linux only. This value defines whether the user should be presented with a confirmation dialog if the user types in a file name that already exists in that directory." }, { "code": null, "e": 24135, "s": 24089, "text": "showHiddenFiles: Show Hidden files in dialog." }, { "code": null, "e": 24394, "s": 24135, "text": "createDirectory: This value is supported in macOS only. It allows creating new directories from within the dialog. In Windows, the context-menu is pre-available in the dialog (right-click in dialog window) and we can create new files and directories from it." }, { "code": null, "e": 24533, "s": 24394, "text": "treatPackageAsDirectory: This value is supported in macOS only. It treats packages such as .app folders, as a directory instead of a file." }, { "code": null, "e": 24688, "s": 24533, "text": "dontAddToRecent: This value is supported in Windows only. This value signifies that the file being saved should not be added to the recent documents list." }, { "code": null, "e": 24909, "s": 24688, "text": "showOverwriteConfirmation: This value is supported in Linux only. This value defines whether the user should be presented with a confirmation dialog if the user types in a file name that already exists in that directory." }, { "code": null, "e": 25040, "s": 24909, "text": "The dialog.showSaveDialog(browserWindow, options) returns a Promise. It resolves to an Object containing the following parameters," }, { "code": null, "e": 25109, "s": 25040, "text": "canceled: Boolean Whether or not the dialog operation was cancelled." }, { "code": null, "e": 25238, "s": 25109, "text": "filePath: String (Optional) The file path chosen by the user. If the dialog operation is cancelled, it is going to be undefined." }, { "code": null, "e": 25564, "s": 25238, "text": "bookmark: String (Optional) This return String is supported in macOS only. It is a Base64 encoded String which contains the security scoped bookmark data for the saved file. This is returned when the securityScopedBookmarks parameter is defined as true in the options Object. For the different return values, Refer this link." }, { "code": null, "e": 25979, "s": 25564, "text": "The fs.writeFile(file, data, options, callback) method is used to write the specified data to a file. By default, this will replace the file if it exists at the defined file path. We have specified the absolute file path, the String data to be written and a callback for handling Error in the above code. We can use the options parameter to modify the functionality. For more detailed Information, Refer this link." }, { "code": null, "e": 26204, "s": 25979, "text": "We should now be able to successfully choose the file path from the dialog window, give a new file name (if required, in our code will be sample.txt by default) and save the newly created sample.txt file at that path.Output:" }, { "code": null, "e": 26215, "s": 26204, "text": "ElectronJS" }, { "code": null, "e": 26226, "s": 26215, "text": "JavaScript" }, { "code": null, "e": 26243, "s": 26226, "text": "Web Technologies" }, { "code": null, "e": 26341, "s": 26243, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26402, "s": 26341, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26474, "s": 26402, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 26514, "s": 26474, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 26566, "s": 26514, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 26607, "s": 26566, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 26669, "s": 26607, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26702, "s": 26669, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26763, "s": 26702, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26813, "s": 26763, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Create Subsets of a Data frame in R Programming – subset() Function
22 Nov, 2021 subset() function in R Programming Language is used to create subsets of a Data frame. This can also be used to drop columns from a data frame. Syntax: subset(df, expr) Parameters: df: Data frame used expr: Condition for subset Here we will make subsets of dataframe using subset() methods in R language. R # R program to create# subset of a data frame # Creating a Data Framedf<-data.frame(row1 = 0:2, row2 = 3:5, row3 = 6:8)print ("Original Data Frame")print (df) # Creating a Subsetdf1<-subset(df, select = row2)print("Modified Data Frame")print(df1) Output: [1] "Original Data Frame" row1 row2 row3 1 0 3 6 2 1 4 7 3 2 5 8 [1] "Modified Data Frame" row2 1 3 2 4 3 5 Here, in the above code, the original data frame remains intact while another subset of data frame is created which holds a selected row from the original data frame. Python3 # R program to create# subset of a data frame # Creating a Data Framedf<-data.frame(row1 = 0:2, row2 = 3:5, row3 = 6:8)print ("Original Data Frame")print (df) # Creating a Subsetdf<-subset(df, select = -c(row2, row3))print("Modified Data Frame")print(df) Output: [1] "Original Data Frame" row1 row2 row3 1 0 3 6 2 1 4 7 3 2 5 8 [1] "Modified Data Frame" row1 1 0 2 1 3 2 Here, in the above code, the rows are permanently deleted from the original data frame. kumar_satyam R DataFrame-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? R - if statement Logistic Regression in R Programming How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Nov, 2021" }, { "code": null, "e": 172, "s": 28, "text": "subset() function in R Programming Language is used to create subsets of a Data frame. This can also be used to drop columns from a data frame." }, { "code": null, "e": 197, "s": 172, "text": "Syntax: subset(df, expr)" }, { "code": null, "e": 210, "s": 197, "text": "Parameters: " }, { "code": null, "e": 230, "s": 210, "text": "df: Data frame used" }, { "code": null, "e": 257, "s": 230, "text": "expr: Condition for subset" }, { "code": null, "e": 334, "s": 257, "text": "Here we will make subsets of dataframe using subset() methods in R language." }, { "code": null, "e": 336, "s": 334, "text": "R" }, { "code": "# R program to create# subset of a data frame # Creating a Data Framedf<-data.frame(row1 = 0:2, row2 = 3:5, row3 = 6:8)print (\"Original Data Frame\")print (df) # Creating a Subsetdf1<-subset(df, select = row2)print(\"Modified Data Frame\")print(df1)", "e": 587, "s": 336, "text": null }, { "code": null, "e": 596, "s": 587, "text": "Output: " }, { "code": null, "e": 744, "s": 596, "text": "[1] \"Original Data Frame\"\n row1 row2 row3\n1 0 3 6\n2 1 4 7\n3 2 5 8\n[1] \"Modified Data Frame\"\n row2\n1 3\n2 4\n3 5" }, { "code": null, "e": 912, "s": 744, "text": "Here, in the above code, the original data frame remains intact while another subset of data frame is created which holds a selected row from the original data frame. " }, { "code": null, "e": 920, "s": 912, "text": "Python3" }, { "code": "# R program to create# subset of a data frame # Creating a Data Framedf<-data.frame(row1 = 0:2, row2 = 3:5, row3 = 6:8)print (\"Original Data Frame\")print (df) # Creating a Subsetdf<-subset(df, select = -c(row2, row3))print(\"Modified Data Frame\")print(df)", "e": 1179, "s": 920, "text": null }, { "code": null, "e": 1188, "s": 1179, "text": "Output: " }, { "code": null, "e": 1336, "s": 1188, "text": "[1] \"Original Data Frame\"\n row1 row2 row3\n1 0 3 6\n2 1 4 7\n3 2 5 8\n[1] \"Modified Data Frame\"\n row1\n1 0\n2 1\n3 2" }, { "code": null, "e": 1424, "s": 1336, "text": "Here, in the above code, the rows are permanently deleted from the original data frame." }, { "code": null, "e": 1437, "s": 1424, "text": "kumar_satyam" }, { "code": null, "e": 1458, "s": 1437, "text": "R DataFrame-Function" }, { "code": null, "e": 1469, "s": 1458, "text": "R Language" }, { "code": null, "e": 1567, "s": 1469, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1619, "s": 1567, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1677, "s": 1619, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1712, "s": 1677, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1750, "s": 1712, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 1767, "s": 1750, "text": "R - if statement" }, { "code": null, "e": 1804, "s": 1767, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 1853, "s": 1804, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 1896, "s": 1853, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 1933, "s": 1896, "text": "How to import an Excel File into R ?" } ]
How to pass PHP Variables by reference ?
20 Dec, 2018 By default, PHP variables are passed by value as the function arguments in PHP. When variables in PHP is passed by value, the scope of the variable defined at function level bound within the scope of function. Changing either of the variables doesn’t have any effect on either of the variables. Example: <?php // Function used for assigning new// value to $string variable and // printing itfunction print_string( $string ) { $string = "Function geeksforgeeks"."\n"; // Print $string variable print($string);} // Driver code$string = "Global geeksforgeeks"."\n";print_string($string);print($string);?> Function geeksforgeeks Global geeksforgeeks Pass by reference: When variables are passed by reference, use & (ampersand) symbol need to be added before variable argument. For example: function( &$x ). Scope of both global and function variable becomes global as both variables are defined by same reference. Therefore, whenever global variable is change, variable inside function also gets changed and vice-versa is applicable. Example: <?php // Function used for assigning new value to // $string variable and printing itfunction print_string( &$string ) { $string = "Function geeksforgeeks \n"; // Print $string variable print( $string );} // Driver code$string = "Global geeksforgeeks \n";print_string( $string );print( $string );?> Function geeksforgeeks Function geeksforgeeks PHP-basics PHP-function Picked PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? How to Insert Form Data into Database using PHP ? PHP in_array() Function How to delete an array element based on key in PHP? How to pop an alert message box using PHP ? How to Upload Image into Database and Display it using PHP ? How to execute PHP code using command line ? How to call PHP function on the click of a Button ? How to Insert Form Data into Database using PHP ? How to pop an alert message box using PHP ?
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Dec, 2018" }, { "code": null, "e": 323, "s": 28, "text": "By default, PHP variables are passed by value as the function arguments in PHP. When variables in PHP is passed by value, the scope of the variable defined at function level bound within the scope of function. Changing either of the variables doesn’t have any effect on either of the variables." }, { "code": null, "e": 332, "s": 323, "text": "Example:" }, { "code": "<?php // Function used for assigning new// value to $string variable and // printing itfunction print_string( $string ) { $string = \"Function geeksforgeeks\".\"\\n\"; // Print $string variable print($string);} // Driver code$string = \"Global geeksforgeeks\".\"\\n\";print_string($string);print($string);?>", "e": 643, "s": 332, "text": null }, { "code": null, "e": 688, "s": 643, "text": "Function geeksforgeeks\nGlobal geeksforgeeks\n" }, { "code": null, "e": 1072, "s": 688, "text": "Pass by reference: When variables are passed by reference, use & (ampersand) symbol need to be added before variable argument. For example: function( &$x ). Scope of both global and function variable becomes global as both variables are defined by same reference. Therefore, whenever global variable is change, variable inside function also gets changed and vice-versa is applicable." }, { "code": null, "e": 1081, "s": 1072, "text": "Example:" }, { "code": "<?php // Function used for assigning new value to // $string variable and printing itfunction print_string( &$string ) { $string = \"Function geeksforgeeks \\n\"; // Print $string variable print( $string );} // Driver code$string = \"Global geeksforgeeks \\n\";print_string( $string );print( $string );?>", "e": 1399, "s": 1081, "text": null }, { "code": null, "e": 1447, "s": 1399, "text": "Function geeksforgeeks \nFunction geeksforgeeks\n" }, { "code": null, "e": 1458, "s": 1447, "text": "PHP-basics" }, { "code": null, "e": 1471, "s": 1458, "text": "PHP-function" }, { "code": null, "e": 1478, "s": 1471, "text": "Picked" }, { "code": null, "e": 1482, "s": 1478, "text": "PHP" }, { "code": null, "e": 1495, "s": 1482, "text": "PHP Programs" }, { "code": null, "e": 1512, "s": 1495, "text": "Web Technologies" }, { "code": null, "e": 1516, "s": 1512, "text": "PHP" }, { "code": null, "e": 1614, "s": 1516, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1659, "s": 1614, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 1709, "s": 1659, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 1733, "s": 1709, "text": "PHP in_array() Function" }, { "code": null, "e": 1785, "s": 1733, "text": "How to delete an array element based on key in PHP?" }, { "code": null, "e": 1829, "s": 1785, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 1890, "s": 1829, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 1935, "s": 1890, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 1987, "s": 1935, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 2037, "s": 1987, "text": "How to Insert Form Data into Database using PHP ?" } ]
map find() function in C++ STL
In this article we will be discussing the working, syntax and examples of map::find() function in C++ STL. Maps are the associative container, which facilitates to store the elements formed by a combination on key value and mapped value in a specific order. In a map container the data is internally always sorted with the help of its associated keys. The values in map container is accessed by its unique keys. The map::find( ) is a function which comes under <map> header file. This function returns an iterator which points to an element of a given key which we want to search. map_name.find(key_value k); This function accepts the following k: This is the key value which we want to search from the map container It returns an iterator pointing to the element associated with key k. map<char, int> newmap; newmap[‘a’] = 1; newmap[‘b’] = 2; newmap.find(b); 2 Live Demo #include <bits/stdc++.h> using namespace std; int main() { map<int, int> TP_Map; TP_Map.insert({3, 50}); TP_Map.insert({2, 30}); TP_Map.insert({1, 10}); TP_Map.insert({4, 70}); cout<<"TP Map is : \n"; cout << "MAP_KEY\tMAP_ELEMENT\n"; for (auto i = TP_Map.begin(); i!= TP_Map.end(); i++) { cout << i->first << "\t" << i->second << endl; } //to find the map values at position auto var = TP_Map.find(1); cout<<"Found element at position "<<var->first<<" is : "<<var->second; auto var_1 = TP_Map.find(2); cout<<"\nFound element at position "<<var_1->first<<" is : "<<var_1->second; return 0; } TP Map is: MAP_KEY MAP_ELEMENT 1 10 2 30 3 50 4 70 Found element at position 1 is : 10 Found element at position 2 is : 30 Live Demo #include <bits/stdc++.h> using namespace std; int main() { map<int, int> TP_Map; TP_Map.insert({3, 50}); TP_Map.insert({2, 30}); TP_Map.insert({1, 10}); TP_Map.insert({4, 70}); cout<<"TP Map is : \n"; cout << "MAP_KEY\tMAP_ELEMENT\n"; for (auto i = TP_Map.find(2); i!= TP_Map.end(); i++) { cout << i->first << "\t" << i->second << endl; } return 0; } TP Map is: MAP_KEY MAP_ELEMENT 2 30 3 50 4 70
[ { "code": null, "e": 1294, "s": 1187, "text": "In this article we will be discussing the working, syntax and examples of map::find() function in C++ STL." }, { "code": null, "e": 1599, "s": 1294, "text": "Maps are the associative container, which facilitates to store the elements formed by a combination on key value and mapped value in a specific order. In a map container the data is internally always sorted with the help of its associated keys. The values in map container is accessed by its unique keys." }, { "code": null, "e": 1768, "s": 1599, "text": "The map::find( ) is a function which comes under <map> header file. This function returns an iterator which points to an element of a given key which we want to search." }, { "code": null, "e": 1796, "s": 1768, "text": "map_name.find(key_value k);" }, { "code": null, "e": 1832, "s": 1796, "text": "This function accepts the following" }, { "code": null, "e": 1904, "s": 1832, "text": "k: This is the key value which we want to search from the map container" }, { "code": null, "e": 1974, "s": 1904, "text": "It returns an iterator pointing to the element associated with key k." }, { "code": null, "e": 2047, "s": 1974, "text": "map<char, int> newmap;\nnewmap[‘a’]\n= 1;\nnewmap[‘b’] = 2;\nnewmap.find(b);" }, { "code": null, "e": 2049, "s": 2047, "text": "2" }, { "code": null, "e": 2060, "s": 2049, "text": " Live Demo" }, { "code": null, "e": 2703, "s": 2060, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n map<int, int> TP_Map;\n TP_Map.insert({3, 50});\n TP_Map.insert({2, 30});\n TP_Map.insert({1, 10});\n TP_Map.insert({4, 70});\n cout<<\"TP Map is : \\n\";\n cout << \"MAP_KEY\\tMAP_ELEMENT\\n\";\n for (auto i = TP_Map.begin(); i!= TP_Map.end(); i++) {\n cout << i->first << \"\\t\" << i->second << endl;\n }\n //to find the map values at position\n auto var = TP_Map.find(1);\n cout<<\"Found element at position \"<<var->first<<\" is : \"<<var->second;\n auto var_1 = TP_Map.find(2);\n cout<<\"\\nFound element at position \"<<var_1->first<<\" is : \"<<var_1->second;\n return 0;\n}" }, { "code": null, "e": 2877, "s": 2703, "text": "TP Map is:\nMAP_KEY MAP_ELEMENT\n1 10\n2 30\n3 50\n4 70\nFound element at position 1 is : 10\nFound element at position 2 is : 30" }, { "code": null, "e": 2888, "s": 2877, "text": " Live Demo" }, { "code": null, "e": 3275, "s": 2888, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n map<int, int> TP_Map;\n TP_Map.insert({3, 50});\n TP_Map.insert({2, 30});\n TP_Map.insert({1, 10});\n TP_Map.insert({4, 70});\n cout<<\"TP Map is : \\n\";\n cout << \"MAP_KEY\\tMAP_ELEMENT\\n\";\n for (auto i = TP_Map.find(2); i!= TP_Map.end(); i++) {\n cout << i->first << \"\\t\" << i->second << endl;\n }\n return 0;\n}" }, { "code": null, "e": 3360, "s": 3275, "text": "TP Map is:\nMAP_KEY MAP_ELEMENT\n2 30\n3 50\n4 70" } ]
Divide and Conquer | Set 5 (Strassen’s Matrix Multiplication)
23 Jun, 2022 Given two square matrices A and B of size n x n each, find their multiplication matrix. Naive Method: Following is a simple way to multiply two matrices. C++ C Java Python3 C# Javascript void multiply(int A[][N], int B[][N], int C[][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { C[i][j] = 0; for (int k = 0; k < N; k++) { C[i][j] += A[i][k]*B[k][j]; } } }} // This code is contributed by noob2000. void multiply(int A[][N], int B[][N], int C[][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { C[i][j] = 0; for (int k = 0; k < N; k++) { C[i][j] += A[i][k]*B[k][j]; } } }} // java codestatic int multiply(int A[][N], int B[][N], int C[][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { C[i][j] = 0; for (int k = 0; k < N; k++) { C[i][j] += A[i][k]*B[k][j]; } } }} // This code is contributed by shivanisinghss2110 def multiply(A, B, C): for i in range(N): for j in range( N): C[i][j] = 0 for k in range(N): C[i][j] += A[i][k]*B[k][j] # this code is contributed by shivanisinghss2110 // C# codestatic int multiply(int A[,N], int B[,N], int C[,N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { C[i,j] = 0; for (int k = 0; k < N; k++) { C[i,j] += A[i,k]*B[k,j]; } } }} // This code is contributed by rutvik_56. <script> function multiply(A, B, C){ for (var i = 0; i < N; i++) { for (var j = 0; j < N; j++) { C[i][j] = 0; for (var k = 0; k < N; k++) { C[i][j] += A[i][k]*B[k][j]; } } }} </script> Time Complexity of above method is O(N3). Divide and Conquer : Following is simple Divide and Conquer method to multiply two square matrices. 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. Divide matrices A and B in 4 sub-matrices of size N/2 x N/2 as shown in the below diagram. Calculate following values recursively. ae + bg, af + bh, ce + dg and cf + dh. Divide matrices A and B in 4 sub-matrices of size N/2 x N/2 as shown in the below diagram. Calculate following values recursively. ae + bg, af + bh, ce + dg and cf + dh. Implementation: C++ Java #include <bits/stdc++.h>using namespace std; #define ROW_1 4#define COL_1 4 #define ROW_2 4#define COL_2 4 void print(string display, vector<vector<int> > matrix, int start_row, int start_column, int end_row, int end_column){ cout << endl << display << " =>" << endl; for (int i = start_row; i <= end_row; i++) { for (int j = start_column; j <= end_column; j++) { cout << setw(10); cout << matrix[i][j]; } cout << endl; } cout << endl; return;} void add_matrix(vector<vector<int> > matrix_A, vector<vector<int> > matrix_B, vector<vector<int> >& matrix_C, int split_index){ for (auto i = 0; i < split_index; i++) for (auto j = 0; j < split_index; j++) matrix_C[i][j] = matrix_A[i][j] + matrix_B[i][j];} vector<vector<int> >multiply_matrix(vector<vector<int> > matrix_A, vector<vector<int> > matrix_B){ int col_1 = matrix_A[0].size(); int row_1 = matrix_A.size(); int col_2 = matrix_B[0].size(); int row_2 = matrix_B.size(); if (col_1 != row_2) { cout << "\nError: The number of columns in Matrix " "A must be equal to the number of rows in " "Matrix B\n"; return {}; } vector<int> result_matrix_row(col_2, 0); vector<vector<int> > result_matrix(row_1, result_matrix_row); if (col_1 == 1) result_matrix[0][0] = matrix_A[0][0] * matrix_B[0][0]; else { int split_index = col_1 / 2; vector<int> row_vector(split_index, 0); vector<vector<int> > result_matrix_00(split_index, row_vector); vector<vector<int> > result_matrix_01(split_index, row_vector); vector<vector<int> > result_matrix_10(split_index, row_vector); vector<vector<int> > result_matrix_11(split_index, row_vector); vector<vector<int> > a00(split_index, row_vector); vector<vector<int> > a01(split_index, row_vector); vector<vector<int> > a10(split_index, row_vector); vector<vector<int> > a11(split_index, row_vector); vector<vector<int> > b00(split_index, row_vector); vector<vector<int> > b01(split_index, row_vector); vector<vector<int> > b10(split_index, row_vector); vector<vector<int> > b11(split_index, row_vector); for (auto i = 0; i < split_index; i++) for (auto j = 0; j < split_index; j++) { a00[i][j] = matrix_A[i][j]; a01[i][j] = matrix_A[i][j + split_index]; a10[i][j] = matrix_A[split_index + i][j]; a11[i][j] = matrix_A[i + split_index] [j + split_index]; b00[i][j] = matrix_B[i][j]; b01[i][j] = matrix_B[i][j + split_index]; b10[i][j] = matrix_B[split_index + i][j]; b11[i][j] = matrix_B[i + split_index] [j + split_index]; } add_matrix(multiply_matrix(a00, b00), multiply_matrix(a01, b10), result_matrix_00, split_index); add_matrix(multiply_matrix(a00, b01), multiply_matrix(a01, b11), result_matrix_01, split_index); add_matrix(multiply_matrix(a10, b00), multiply_matrix(a11, b10), result_matrix_10, split_index); add_matrix(multiply_matrix(a10, b01), multiply_matrix(a11, b11), result_matrix_11, split_index); for (auto i = 0; i < split_index; i++) for (auto j = 0; j < split_index; j++) { result_matrix[i][j] = result_matrix_00[i][j]; result_matrix[i][j + split_index] = result_matrix_01[i][j]; result_matrix[split_index + i][j] = result_matrix_10[i][j]; result_matrix[i + split_index] [j + split_index] = result_matrix_11[i][j]; } result_matrix_00.clear(); result_matrix_01.clear(); result_matrix_10.clear(); result_matrix_11.clear(); a00.clear(); a01.clear(); a10.clear(); a11.clear(); b00.clear(); b01.clear(); b10.clear(); b11.clear(); } return result_matrix;} int main(){ vector<vector<int> > matrix_A = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 2, 2, 2, 2 } }; print("Array A", matrix_A, 0, 0, ROW_1 - 1, COL_1 - 1); vector<vector<int> > matrix_B = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 2, 2, 2, 2 } }; print("Array B", matrix_B, 0, 0, ROW_2 - 1, COL_2 - 1); vector<vector<int> > result_matrix( multiply_matrix(matrix_A, matrix_B)); print("Result Array", result_matrix, 0, 0, ROW_1 - 1, COL_2 - 1);} // Time Complexity: O(n^3)// Code Contributed By: lucasletum //Java program to find the resultant//product matrix for a given pair of matrices//using Divide and Conquer Approach import java.io.*;import java.util.*; class GFG { static int ROW_1 = 4,COL_1 = 4, ROW_2 = 4, COL_2 = 4; public static void printMat(int[][] a, int r, int c){ for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ System.out.print(a[i][j]+" "); } System.out.println(""); } System.out.println(""); } public static void print(String display, int[][] matrix,int start_row, int start_column, int end_row,int end_column) { System.out.println(display + " =>\n"); for (int i = start_row; i <= end_row; i++) { for (int j = start_column; j <= end_column; j++) { //cout << setw(10); System.out.print(matrix[i][j]+" "); } System.out.println(""); } System.out.println(""); } public static void add_matrix(int[][] matrix_A,int[][] matrix_B,int[][] matrix_C, int split_index) { for (int i = 0; i < split_index; i++){ for (int j = 0; j < split_index; j++){ matrix_C[i][j] = matrix_A[i][j] + matrix_B[i][j]; } } } public static void initWithZeros(int a[][], int r, int c){ for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ a[i][j]=0; } } } public static int[][] multiply_matrix(int[][] matrix_A,int[][] matrix_B) { int col_1 = matrix_A[0].length; int row_1 = matrix_A.length; int col_2 = matrix_B[0].length; int row_2 = matrix_B.length; if (col_1 != row_2) { System.out.println("\nError: The number of columns in Matrix A must be equal to the number of rows in Matrix B\n"); int temp[][] = new int[1][1]; temp[0][0]=0; return temp; } int[] result_matrix_row = new int[col_2]; Arrays.fill(result_matrix_row,0); int[][] result_matrix = new int[row_1][col_2]; initWithZeros(result_matrix,row_1,col_2); if (col_1 == 1){ result_matrix[0][0] = matrix_A[0][0] * matrix_B[0][0]; }else { int split_index = col_1 / 2; int[] row_vector = new int[split_index]; Arrays.fill(row_vector,0); int[][] result_matrix_00 = new int[split_index][split_index]; int[][] result_matrix_01 = new int[split_index][split_index]; int[][] result_matrix_10 = new int[split_index][split_index]; int[][] result_matrix_11 = new int[split_index][split_index]; initWithZeros(result_matrix_00,split_index,split_index); initWithZeros(result_matrix_01,split_index,split_index); initWithZeros(result_matrix_10,split_index,split_index); initWithZeros(result_matrix_11,split_index,split_index); int[][] a00 = new int[split_index][split_index]; int[][] a01 = new int[split_index][split_index]; int[][] a10 = new int[split_index][split_index]; int[][] a11 = new int[split_index][split_index]; int[][] b00 = new int[split_index][split_index]; int[][] b01 = new int[split_index][split_index]; int[][] b10 = new int[split_index][split_index]; int[][] b11 = new int[split_index][split_index]; initWithZeros(a00,split_index,split_index); initWithZeros(a01,split_index,split_index); initWithZeros(a10,split_index,split_index); initWithZeros(a11,split_index,split_index); initWithZeros(b00,split_index,split_index); initWithZeros(b01,split_index,split_index); initWithZeros(b10,split_index,split_index); initWithZeros(b11,split_index,split_index); for (int i = 0; i < split_index; i++){ for (int j = 0; j < split_index; j++) { a00[i][j] = matrix_A[i][j]; a01[i][j] = matrix_A[i][j + split_index]; a10[i][j] = matrix_A[split_index + i][j]; a11[i][j] = matrix_A[i + split_index][j + split_index]; b00[i][j] = matrix_B[i][j]; b01[i][j] = matrix_B[i][j + split_index]; b10[i][j] = matrix_B[split_index + i][j]; b11[i][j] = matrix_B[i + split_index][j + split_index]; } } add_matrix(multiply_matrix(a00, b00),multiply_matrix(a01, b10),result_matrix_00, split_index); add_matrix(multiply_matrix(a00, b01),multiply_matrix(a01, b11),result_matrix_01, split_index); add_matrix(multiply_matrix(a10, b00),multiply_matrix(a11, b10),result_matrix_10, split_index); add_matrix(multiply_matrix(a10, b01),multiply_matrix(a11, b11),result_matrix_11, split_index); for (int i = 0; i < split_index; i++){ for (int j = 0; j < split_index; j++) { result_matrix[i][j] = result_matrix_00[i][j]; result_matrix[i][j + split_index] = result_matrix_01[i][j]; result_matrix[split_index + i][j] = result_matrix_10[i][j]; result_matrix[i + split_index] [j + split_index] = result_matrix_11[i][j]; } } } return result_matrix; } public static void main (String[] args) { int[][] matrix_A = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 2, 2, 2, 2 } }; System.out.println("Array A =>"); printMat(matrix_A,4,4); int[][] matrix_B = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 2, 2, 2, 2 } }; System.out.println("Array B =>"); printMat(matrix_B,4,4); int[][] result_matrix = multiply_matrix(matrix_A, matrix_B); System.out.println("Result Array =>"); printMat(result_matrix,4,4); }}// Time Complexity: O(n^3)//This code is contributed by shruti456rawal Array A => 1 1 1 1 2 2 2 2 3 3 3 3 2 2 2 2 Array B => 1 1 1 1 2 2 2 2 3 3 3 3 2 2 2 2 Result Array => 8 8 8 8 16 16 16 16 24 24 24 24 16 16 16 16 In the above method, we do 8 multiplications for matrices of size N/2 x N/2 and 4 additions. Addition of two matrices takes O(N2) time. So the time complexity can be written as T(N) = 8T(N/2) + O(N2) From Master's Theorem, time complexity of above method is O(N3) which is unfortunately same as the above naive method. Simple Divide and Conquer also leads to O(N3), can there be a better way? In the above divide and conquer method, the main component for high time complexity is 8 recursive calls. The idea of Strassen’s method is to reduce the number of recursive calls to 7. Strassen’s method is similar to above simple divide and conquer method in the sense that this method also divide matrices to sub-matrices of size N/2 x N/2 as shown in the above diagram, but in Strassen’s method, the four sub-matrices of result are calculated using following formulae. Time Complexity of Strassen’s Method Addition and Subtraction of two matrices takes O(N2) time. So time complexity can be written as T(N) = 7T(N/2) + O(N2) From Master's Theorem, time complexity of above method is O(NLog7) which is approximately O(N2.8074) Generally Strassen’s Method is not preferred for practical applications for following reasons. The constants used in Strassen’s method are high and for a typical application Naive method works better. For Sparse matrices, there are better methods especially designed for them. The submatrices in recursion take extra space. Because of the limited precision of computer arithmetic on noninteger values, larger errors accumulate in Strassen’s algorithm than in Naive Method The constants used in Strassen’s method are high and for a typical application Naive method works better. For Sparse matrices, there are better methods especially designed for them. The submatrices in recursion take extra space. Because of the limited precision of computer arithmetic on noninteger values, larger errors accumulate in Strassen’s algorithm than in Naive Method Implementation: C++ Python3 #include <bits/stdc++.h>using namespace std; #define ROW_1 4#define COL_1 4 #define ROW_2 4#define COL_2 4 void print(string display, vector<vector<int> > matrix, int start_row, int start_column, int end_row, int end_column){ cout << endl << display << " =>" << endl; for (int i = start_row; i <= end_row; i++) { for (int j = start_column; j <= end_column; j++) { cout << setw(10); cout << matrix[i][j]; } cout << endl; } cout << endl; return;} vector<vector<int> >add_matrix(vector<vector<int> > matrix_A, vector<vector<int> > matrix_B, int split_index, int multiplier = 1){ for (auto i = 0; i < split_index; i++) for (auto j = 0; j < split_index; j++) matrix_A[i][j] = matrix_A[i][j] + (multiplier * matrix_B[i][j]); return matrix_A;} vector<vector<int> >multiply_matrix(vector<vector<int> > matrix_A, vector<vector<int> > matrix_B){ int col_1 = matrix_A[0].size(); int row_1 = matrix_A.size(); int col_2 = matrix_B[0].size(); int row_2 = matrix_B.size(); if (col_1 != row_2) { cout << "\nError: The number of columns in Matrix " "A must be equal to the number of rows in " "Matrix B\n"; return {}; } vector<int> result_matrix_row(col_2, 0); vector<vector<int> > result_matrix(row_1, result_matrix_row); if (col_1 == 1) result_matrix[0][0] = matrix_A[0][0] * matrix_B[0][0]; else { int split_index = col_1 / 2; vector<int> row_vector(split_index, 0); vector<vector<int> > a00(split_index, row_vector); vector<vector<int> > a01(split_index, row_vector); vector<vector<int> > a10(split_index, row_vector); vector<vector<int> > a11(split_index, row_vector); vector<vector<int> > b00(split_index, row_vector); vector<vector<int> > b01(split_index, row_vector); vector<vector<int> > b10(split_index, row_vector); vector<vector<int> > b11(split_index, row_vector); for (auto i = 0; i < split_index; i++) for (auto j = 0; j < split_index; j++) { a00[i][j] = matrix_A[i][j]; a01[i][j] = matrix_A[i][j + split_index]; a10[i][j] = matrix_A[split_index + i][j]; a11[i][j] = matrix_A[i + split_index] [j + split_index]; b00[i][j] = matrix_B[i][j]; b01[i][j] = matrix_B[i][j + split_index]; b10[i][j] = matrix_B[split_index + i][j]; b11[i][j] = matrix_B[i + split_index] [j + split_index]; } vector<vector<int> > p(multiply_matrix( a00, add_matrix(b01, b11, split_index, -1))); vector<vector<int> > q(multiply_matrix( add_matrix(a00, a01, split_index), b11)); vector<vector<int> > r(multiply_matrix( add_matrix(a10, a11, split_index), b00)); vector<vector<int> > s(multiply_matrix( a11, add_matrix(b10, b00, split_index, -1))); vector<vector<int> > t(multiply_matrix( add_matrix(a00, a11, split_index), add_matrix(b00, b11, split_index))); vector<vector<int> > u(multiply_matrix( add_matrix(a01, a11, split_index, -1), add_matrix(b10, b11, split_index))); vector<vector<int> > v(multiply_matrix( add_matrix(a00, a10, split_index, -1), add_matrix(b00, b01, split_index))); vector<vector<int> > result_matrix_00(add_matrix( add_matrix(add_matrix(t, s, split_index), u, split_index), q, split_index, -1)); vector<vector<int> > result_matrix_01( add_matrix(p, q, split_index)); vector<vector<int> > result_matrix_10( add_matrix(r, s, split_index)); vector<vector<int> > result_matrix_11(add_matrix( add_matrix(add_matrix(t, p, split_index), r, split_index, -1), v, split_index, -1)); for (auto i = 0; i < split_index; i++) for (auto j = 0; j < split_index; j++) { result_matrix[i][j] = result_matrix_00[i][j]; result_matrix[i][j + split_index] = result_matrix_01[i][j]; result_matrix[split_index + i][j] = result_matrix_10[i][j]; result_matrix[i + split_index] [j + split_index] = result_matrix_11[i][j]; } a00.clear(); a01.clear(); a10.clear(); a11.clear(); b00.clear(); b01.clear(); b10.clear(); b11.clear(); p.clear(); q.clear(); r.clear(); s.clear(); t.clear(); u.clear(); v.clear(); result_matrix_00.clear(); result_matrix_01.clear(); result_matrix_10.clear(); result_matrix_11.clear(); } return result_matrix;} int main(){ vector<vector<int> > matrix_A = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 2, 2, 2, 2 } }; print("Array A", matrix_A, 0, 0, ROW_1 - 1, COL_1 - 1); vector<vector<int> > matrix_B = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 2, 2, 2, 2 } }; print("Array B", matrix_B, 0, 0, ROW_2 - 1, COL_2 - 1); vector<vector<int> > result_matrix( multiply_matrix(matrix_A, matrix_B)); print("Result Array", result_matrix, 0, 0, ROW_1 - 1, COL_2 - 1);} // Time Complexity: T(N) = 7T(N/2) + O(N^2) => O(N^Log7)// which is approximately O(N^2.8074) Code Contributed By:// lucasletum # Version 3.6 import numpy as np def split(matrix): """ Splits a given matrix into quarters. Input: nxn matrix Output: tuple containing 4 n/2 x n/2 matrices corresponding to a, b, c, d """ row, col = matrix.shape row2, col2 = row//2, col//2 return matrix[:row2, :col2], matrix[:row2, col2:], matrix[row2:, :col2], matrix[row2:, col2:] def strassen(x, y): """ Computes matrix product by divide and conquer approach, recursively. Input: nxn matrices x and y Output: nxn matrix, product of x and y """ # Base case when size of matrices is 1x1 if len(x) == 1: return x * y # Splitting the matrices into quadrants. This will be done recursively # until the base case is reached. a, b, c, d = split(x) e, f, g, h = split(y) # Computing the 7 products, recursively (p1, p2...p7) p1 = strassen(a, f - h) p2 = strassen(a + b, h) p3 = strassen(c + d, e) p4 = strassen(d, g - e) p5 = strassen(a + d, e + h) p6 = strassen(b - d, g + h) p7 = strassen(a - c, e + f) # Computing the values of the 4 quadrants of the final matrix c c11 = p5 + p4 - p2 + p6 c12 = p1 + p2 c21 = p3 + p4 c22 = p1 + p5 - p3 - p7 # Combining the 4 quadrants into a single matrix by stacking horizontally and vertically. c = np.vstack((np.hstack((c11, c12)), np.hstack((c21, c22)))) return c Array A => 1 1 1 1 2 2 2 2 3 3 3 3 2 2 2 2 Array B => 1 1 1 1 2 2 2 2 3 3 3 3 2 2 2 2 Result Array => 8 8 8 8 16 16 16 16 24 24 24 24 16 16 16 16 Easy way to remember Strassen’s Matrix Equation Strassen’s Matrix Multiplication | Divide and Conquer | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersStrassen’s Matrix Multiplication | Divide and Conquer | 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 / 4:37•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=E-QtwPi620I" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> References: Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest https://www.youtube.com/watch?v=LOLebQ8nKHA https://www.youtube.com/watch?v=QXY4RskLQcIPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above PrayushDawda rrrtnx anikaseth98 shivanisinghss2110 rutvik_56 noob2000 amartyaghoshgfg lucasletum shruti456rawal hardikkoriintern Divide and Conquer Matrix Divide and Conquer Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge Sort QuickSort Binary Search Count Inversions in an array | Set 1 (Using Merge Sort) Median of two sorted arrays of different sizes Matrix Chain Multiplication | DP-8 Print a given matrix in spiral form Program to find largest element in an array Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2022" }, { "code": null, "e": 143, "s": 54, "text": "Given two square matrices A and B of size n x n each, find their multiplication matrix. " }, { "code": null, "e": 210, "s": 143, "text": "Naive Method: Following is a simple way to multiply two matrices. " }, { "code": null, "e": 214, "s": 210, "text": "C++" }, { "code": null, "e": 216, "s": 214, "text": "C" }, { "code": null, "e": 221, "s": 216, "text": "Java" }, { "code": null, "e": 229, "s": 221, "text": "Python3" }, { "code": null, "e": 232, "s": 229, "text": "C#" }, { "code": null, "e": 243, "s": 232, "text": "Javascript" }, { "code": "void multiply(int A[][N], int B[][N], int C[][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { C[i][j] = 0; for (int k = 0; k < N; k++) { C[i][j] += A[i][k]*B[k][j]; } } }} // This code is contributed by noob2000.", "e": 562, "s": 243, "text": null }, { "code": "void multiply(int A[][N], int B[][N], int C[][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { C[i][j] = 0; for (int k = 0; k < N; k++) { C[i][j] += A[i][k]*B[k][j]; } } }}", "e": 840, "s": 562, "text": null }, { "code": "// java codestatic int multiply(int A[][N], int B[][N], int C[][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { C[i][j] = 0; for (int k = 0; k < N; k++) { C[i][j] += A[i][k]*B[k][j]; } } }} // This code is contributed by shivanisinghss2110", "e": 1186, "s": 840, "text": null }, { "code": "def multiply(A, B, C): for i in range(N): for j in range( N): C[i][j] = 0 for k in range(N): C[i][j] += A[i][k]*B[k][j] # this code is contributed by shivanisinghss2110", "e": 1430, "s": 1186, "text": null }, { "code": "// C# codestatic int multiply(int A[,N], int B[,N], int C[,N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { C[i,j] = 0; for (int k = 0; k < N; k++) { C[i,j] += A[i,k]*B[k,j]; } } }} // This code is contributed by rutvik_56.", "e": 1759, "s": 1430, "text": null }, { "code": "<script> function multiply(A, B, C){ for (var i = 0; i < N; i++) { for (var j = 0; j < N; j++) { C[i][j] = 0; for (var k = 0; k < N; k++) { C[i][j] += A[i][k]*B[k][j]; } } }} </script>", "e": 2033, "s": 1759, "text": null }, { "code": null, "e": 2076, "s": 2033, "text": "Time Complexity of above method is O(N3). " }, { "code": null, "e": 2097, "s": 2076, "text": "Divide and Conquer :" }, { "code": null, "e": 2177, "s": 2097, "text": "Following is simple Divide and Conquer method to multiply two square matrices. " }, { "code": null, "e": 2186, "s": 2177, "text": "Chapters" }, { "code": null, "e": 2213, "s": 2186, "text": "descriptions off, selected" }, { "code": null, "e": 2263, "s": 2213, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 2286, "s": 2263, "text": "captions off, selected" }, { "code": null, "e": 2294, "s": 2286, "text": "English" }, { "code": null, "e": 2312, "s": 2294, "text": "default, selected" }, { "code": null, "e": 2336, "s": 2312, "text": "This is a modal window." }, { "code": null, "e": 2405, "s": 2336, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 2427, "s": 2405, "text": "End of dialog window." }, { "code": null, "e": 2598, "s": 2427, "text": "Divide matrices A and B in 4 sub-matrices of size N/2 x N/2 as shown in the below diagram. Calculate following values recursively. ae + bg, af + bh, ce + dg and cf + dh. " }, { "code": null, "e": 2690, "s": 2598, "text": "Divide matrices A and B in 4 sub-matrices of size N/2 x N/2 as shown in the below diagram. " }, { "code": null, "e": 2770, "s": 2690, "text": "Calculate following values recursively. ae + bg, af + bh, ce + dg and cf + dh. " }, { "code": null, "e": 2786, "s": 2770, "text": "Implementation:" }, { "code": null, "e": 2790, "s": 2786, "text": "C++" }, { "code": null, "e": 2795, "s": 2790, "text": "Java" }, { "code": "#include <bits/stdc++.h>using namespace std; #define ROW_1 4#define COL_1 4 #define ROW_2 4#define COL_2 4 void print(string display, vector<vector<int> > matrix, int start_row, int start_column, int end_row, int end_column){ cout << endl << display << \" =>\" << endl; for (int i = start_row; i <= end_row; i++) { for (int j = start_column; j <= end_column; j++) { cout << setw(10); cout << matrix[i][j]; } cout << endl; } cout << endl; return;} void add_matrix(vector<vector<int> > matrix_A, vector<vector<int> > matrix_B, vector<vector<int> >& matrix_C, int split_index){ for (auto i = 0; i < split_index; i++) for (auto j = 0; j < split_index; j++) matrix_C[i][j] = matrix_A[i][j] + matrix_B[i][j];} vector<vector<int> >multiply_matrix(vector<vector<int> > matrix_A, vector<vector<int> > matrix_B){ int col_1 = matrix_A[0].size(); int row_1 = matrix_A.size(); int col_2 = matrix_B[0].size(); int row_2 = matrix_B.size(); if (col_1 != row_2) { cout << \"\\nError: The number of columns in Matrix \" \"A must be equal to the number of rows in \" \"Matrix B\\n\"; return {}; } vector<int> result_matrix_row(col_2, 0); vector<vector<int> > result_matrix(row_1, result_matrix_row); if (col_1 == 1) result_matrix[0][0] = matrix_A[0][0] * matrix_B[0][0]; else { int split_index = col_1 / 2; vector<int> row_vector(split_index, 0); vector<vector<int> > result_matrix_00(split_index, row_vector); vector<vector<int> > result_matrix_01(split_index, row_vector); vector<vector<int> > result_matrix_10(split_index, row_vector); vector<vector<int> > result_matrix_11(split_index, row_vector); vector<vector<int> > a00(split_index, row_vector); vector<vector<int> > a01(split_index, row_vector); vector<vector<int> > a10(split_index, row_vector); vector<vector<int> > a11(split_index, row_vector); vector<vector<int> > b00(split_index, row_vector); vector<vector<int> > b01(split_index, row_vector); vector<vector<int> > b10(split_index, row_vector); vector<vector<int> > b11(split_index, row_vector); for (auto i = 0; i < split_index; i++) for (auto j = 0; j < split_index; j++) { a00[i][j] = matrix_A[i][j]; a01[i][j] = matrix_A[i][j + split_index]; a10[i][j] = matrix_A[split_index + i][j]; a11[i][j] = matrix_A[i + split_index] [j + split_index]; b00[i][j] = matrix_B[i][j]; b01[i][j] = matrix_B[i][j + split_index]; b10[i][j] = matrix_B[split_index + i][j]; b11[i][j] = matrix_B[i + split_index] [j + split_index]; } add_matrix(multiply_matrix(a00, b00), multiply_matrix(a01, b10), result_matrix_00, split_index); add_matrix(multiply_matrix(a00, b01), multiply_matrix(a01, b11), result_matrix_01, split_index); add_matrix(multiply_matrix(a10, b00), multiply_matrix(a11, b10), result_matrix_10, split_index); add_matrix(multiply_matrix(a10, b01), multiply_matrix(a11, b11), result_matrix_11, split_index); for (auto i = 0; i < split_index; i++) for (auto j = 0; j < split_index; j++) { result_matrix[i][j] = result_matrix_00[i][j]; result_matrix[i][j + split_index] = result_matrix_01[i][j]; result_matrix[split_index + i][j] = result_matrix_10[i][j]; result_matrix[i + split_index] [j + split_index] = result_matrix_11[i][j]; } result_matrix_00.clear(); result_matrix_01.clear(); result_matrix_10.clear(); result_matrix_11.clear(); a00.clear(); a01.clear(); a10.clear(); a11.clear(); b00.clear(); b01.clear(); b10.clear(); b11.clear(); } return result_matrix;} int main(){ vector<vector<int> > matrix_A = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 2, 2, 2, 2 } }; print(\"Array A\", matrix_A, 0, 0, ROW_1 - 1, COL_1 - 1); vector<vector<int> > matrix_B = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 2, 2, 2, 2 } }; print(\"Array B\", matrix_B, 0, 0, ROW_2 - 1, COL_2 - 1); vector<vector<int> > result_matrix( multiply_matrix(matrix_A, matrix_B)); print(\"Result Array\", result_matrix, 0, 0, ROW_1 - 1, COL_2 - 1);} // Time Complexity: O(n^3)// Code Contributed By: lucasletum", "e": 8194, "s": 2795, "text": null }, { "code": "//Java program to find the resultant//product matrix for a given pair of matrices//using Divide and Conquer Approach import java.io.*;import java.util.*; class GFG { static int ROW_1 = 4,COL_1 = 4, ROW_2 = 4, COL_2 = 4; public static void printMat(int[][] a, int r, int c){ for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ System.out.print(a[i][j]+\" \"); } System.out.println(\"\"); } System.out.println(\"\"); } public static void print(String display, int[][] matrix,int start_row, int start_column, int end_row,int end_column) { System.out.println(display + \" =>\\n\"); for (int i = start_row; i <= end_row; i++) { for (int j = start_column; j <= end_column; j++) { //cout << setw(10); System.out.print(matrix[i][j]+\" \"); } System.out.println(\"\"); } System.out.println(\"\"); } public static void add_matrix(int[][] matrix_A,int[][] matrix_B,int[][] matrix_C, int split_index) { for (int i = 0; i < split_index; i++){ for (int j = 0; j < split_index; j++){ matrix_C[i][j] = matrix_A[i][j] + matrix_B[i][j]; } } } public static void initWithZeros(int a[][], int r, int c){ for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ a[i][j]=0; } } } public static int[][] multiply_matrix(int[][] matrix_A,int[][] matrix_B) { int col_1 = matrix_A[0].length; int row_1 = matrix_A.length; int col_2 = matrix_B[0].length; int row_2 = matrix_B.length; if (col_1 != row_2) { System.out.println(\"\\nError: The number of columns in Matrix A must be equal to the number of rows in Matrix B\\n\"); int temp[][] = new int[1][1]; temp[0][0]=0; return temp; } int[] result_matrix_row = new int[col_2]; Arrays.fill(result_matrix_row,0); int[][] result_matrix = new int[row_1][col_2]; initWithZeros(result_matrix,row_1,col_2); if (col_1 == 1){ result_matrix[0][0] = matrix_A[0][0] * matrix_B[0][0]; }else { int split_index = col_1 / 2; int[] row_vector = new int[split_index]; Arrays.fill(row_vector,0); int[][] result_matrix_00 = new int[split_index][split_index]; int[][] result_matrix_01 = new int[split_index][split_index]; int[][] result_matrix_10 = new int[split_index][split_index]; int[][] result_matrix_11 = new int[split_index][split_index]; initWithZeros(result_matrix_00,split_index,split_index); initWithZeros(result_matrix_01,split_index,split_index); initWithZeros(result_matrix_10,split_index,split_index); initWithZeros(result_matrix_11,split_index,split_index); int[][] a00 = new int[split_index][split_index]; int[][] a01 = new int[split_index][split_index]; int[][] a10 = new int[split_index][split_index]; int[][] a11 = new int[split_index][split_index]; int[][] b00 = new int[split_index][split_index]; int[][] b01 = new int[split_index][split_index]; int[][] b10 = new int[split_index][split_index]; int[][] b11 = new int[split_index][split_index]; initWithZeros(a00,split_index,split_index); initWithZeros(a01,split_index,split_index); initWithZeros(a10,split_index,split_index); initWithZeros(a11,split_index,split_index); initWithZeros(b00,split_index,split_index); initWithZeros(b01,split_index,split_index); initWithZeros(b10,split_index,split_index); initWithZeros(b11,split_index,split_index); for (int i = 0; i < split_index; i++){ for (int j = 0; j < split_index; j++) { a00[i][j] = matrix_A[i][j]; a01[i][j] = matrix_A[i][j + split_index]; a10[i][j] = matrix_A[split_index + i][j]; a11[i][j] = matrix_A[i + split_index][j + split_index]; b00[i][j] = matrix_B[i][j]; b01[i][j] = matrix_B[i][j + split_index]; b10[i][j] = matrix_B[split_index + i][j]; b11[i][j] = matrix_B[i + split_index][j + split_index]; } } add_matrix(multiply_matrix(a00, b00),multiply_matrix(a01, b10),result_matrix_00, split_index); add_matrix(multiply_matrix(a00, b01),multiply_matrix(a01, b11),result_matrix_01, split_index); add_matrix(multiply_matrix(a10, b00),multiply_matrix(a11, b10),result_matrix_10, split_index); add_matrix(multiply_matrix(a10, b01),multiply_matrix(a11, b11),result_matrix_11, split_index); for (int i = 0; i < split_index; i++){ for (int j = 0; j < split_index; j++) { result_matrix[i][j] = result_matrix_00[i][j]; result_matrix[i][j + split_index] = result_matrix_01[i][j]; result_matrix[split_index + i][j] = result_matrix_10[i][j]; result_matrix[i + split_index] [j + split_index] = result_matrix_11[i][j]; } } } return result_matrix; } public static void main (String[] args) { int[][] matrix_A = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 2, 2, 2, 2 } }; System.out.println(\"Array A =>\"); printMat(matrix_A,4,4); int[][] matrix_B = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 2, 2, 2, 2 } }; System.out.println(\"Array B =>\"); printMat(matrix_B,4,4); int[][] result_matrix = multiply_matrix(matrix_A, matrix_B); System.out.println(\"Result Array =>\"); printMat(result_matrix,4,4); }}// Time Complexity: O(n^3)//This code is contributed by shruti456rawal", "e": 13656, "s": 8194, "text": null }, { "code": null, "e": 14190, "s": 13656, "text": "Array A =>\n 1 1 1 1\n 2 2 2 2\n 3 3 3 3\n 2 2 2 2\n\n\nArray B =>\n 1 1 1 1\n 2 2 2 2\n 3 3 3 3\n 2 2 2 2\n\n\nResult Array =>\n 8 8 8 8\n 16 16 16 16\n 24 24 24 24\n 16 16 16 16" }, { "code": null, "e": 14368, "s": 14190, "text": "In the above method, we do 8 multiplications for matrices of size N/2 x N/2 and 4 additions. Addition of two matrices takes O(N2) time. So the time complexity can be written as " }, { "code": null, "e": 14513, "s": 14368, "text": "T(N) = 8T(N/2) + O(N2) \n\nFrom Master's Theorem, time complexity of above method is O(N3)\nwhich is unfortunately same as the above naive method." }, { "code": null, "e": 14588, "s": 14513, "text": "Simple Divide and Conquer also leads to O(N3), can there be a better way? " }, { "code": null, "e": 15060, "s": 14588, "text": "In the above divide and conquer method, the main component for high time complexity is 8 recursive calls. The idea of Strassen’s method is to reduce the number of recursive calls to 7. Strassen’s method is similar to above simple divide and conquer method in the sense that this method also divide matrices to sub-matrices of size N/2 x N/2 as shown in the above diagram, but in Strassen’s method, the four sub-matrices of result are calculated using following formulae. " }, { "code": null, "e": 15097, "s": 15060, "text": "Time Complexity of Strassen’s Method" }, { "code": null, "e": 15194, "s": 15097, "text": "Addition and Subtraction of two matrices takes O(N2) time. So time complexity can be written as " }, { "code": null, "e": 15321, "s": 15194, "text": "T(N) = 7T(N/2) + O(N2)\n\nFrom Master's Theorem, time complexity of above method is \nO(NLog7) which is approximately O(N2.8074)" }, { "code": null, "e": 15417, "s": 15321, "text": "Generally Strassen’s Method is not preferred for practical applications for following reasons. " }, { "code": null, "e": 15794, "s": 15417, "text": "The constants used in Strassen’s method are high and for a typical application Naive method works better. For Sparse matrices, there are better methods especially designed for them. The submatrices in recursion take extra space. Because of the limited precision of computer arithmetic on noninteger values, larger errors accumulate in Strassen’s algorithm than in Naive Method" }, { "code": null, "e": 15901, "s": 15794, "text": "The constants used in Strassen’s method are high and for a typical application Naive method works better. " }, { "code": null, "e": 15978, "s": 15901, "text": "For Sparse matrices, there are better methods especially designed for them. " }, { "code": null, "e": 16026, "s": 15978, "text": "The submatrices in recursion take extra space. " }, { "code": null, "e": 16174, "s": 16026, "text": "Because of the limited precision of computer arithmetic on noninteger values, larger errors accumulate in Strassen’s algorithm than in Naive Method" }, { "code": null, "e": 16190, "s": 16174, "text": "Implementation:" }, { "code": null, "e": 16194, "s": 16190, "text": "C++" }, { "code": null, "e": 16202, "s": 16194, "text": "Python3" }, { "code": "#include <bits/stdc++.h>using namespace std; #define ROW_1 4#define COL_1 4 #define ROW_2 4#define COL_2 4 void print(string display, vector<vector<int> > matrix, int start_row, int start_column, int end_row, int end_column){ cout << endl << display << \" =>\" << endl; for (int i = start_row; i <= end_row; i++) { for (int j = start_column; j <= end_column; j++) { cout << setw(10); cout << matrix[i][j]; } cout << endl; } cout << endl; return;} vector<vector<int> >add_matrix(vector<vector<int> > matrix_A, vector<vector<int> > matrix_B, int split_index, int multiplier = 1){ for (auto i = 0; i < split_index; i++) for (auto j = 0; j < split_index; j++) matrix_A[i][j] = matrix_A[i][j] + (multiplier * matrix_B[i][j]); return matrix_A;} vector<vector<int> >multiply_matrix(vector<vector<int> > matrix_A, vector<vector<int> > matrix_B){ int col_1 = matrix_A[0].size(); int row_1 = matrix_A.size(); int col_2 = matrix_B[0].size(); int row_2 = matrix_B.size(); if (col_1 != row_2) { cout << \"\\nError: The number of columns in Matrix \" \"A must be equal to the number of rows in \" \"Matrix B\\n\"; return {}; } vector<int> result_matrix_row(col_2, 0); vector<vector<int> > result_matrix(row_1, result_matrix_row); if (col_1 == 1) result_matrix[0][0] = matrix_A[0][0] * matrix_B[0][0]; else { int split_index = col_1 / 2; vector<int> row_vector(split_index, 0); vector<vector<int> > a00(split_index, row_vector); vector<vector<int> > a01(split_index, row_vector); vector<vector<int> > a10(split_index, row_vector); vector<vector<int> > a11(split_index, row_vector); vector<vector<int> > b00(split_index, row_vector); vector<vector<int> > b01(split_index, row_vector); vector<vector<int> > b10(split_index, row_vector); vector<vector<int> > b11(split_index, row_vector); for (auto i = 0; i < split_index; i++) for (auto j = 0; j < split_index; j++) { a00[i][j] = matrix_A[i][j]; a01[i][j] = matrix_A[i][j + split_index]; a10[i][j] = matrix_A[split_index + i][j]; a11[i][j] = matrix_A[i + split_index] [j + split_index]; b00[i][j] = matrix_B[i][j]; b01[i][j] = matrix_B[i][j + split_index]; b10[i][j] = matrix_B[split_index + i][j]; b11[i][j] = matrix_B[i + split_index] [j + split_index]; } vector<vector<int> > p(multiply_matrix( a00, add_matrix(b01, b11, split_index, -1))); vector<vector<int> > q(multiply_matrix( add_matrix(a00, a01, split_index), b11)); vector<vector<int> > r(multiply_matrix( add_matrix(a10, a11, split_index), b00)); vector<vector<int> > s(multiply_matrix( a11, add_matrix(b10, b00, split_index, -1))); vector<vector<int> > t(multiply_matrix( add_matrix(a00, a11, split_index), add_matrix(b00, b11, split_index))); vector<vector<int> > u(multiply_matrix( add_matrix(a01, a11, split_index, -1), add_matrix(b10, b11, split_index))); vector<vector<int> > v(multiply_matrix( add_matrix(a00, a10, split_index, -1), add_matrix(b00, b01, split_index))); vector<vector<int> > result_matrix_00(add_matrix( add_matrix(add_matrix(t, s, split_index), u, split_index), q, split_index, -1)); vector<vector<int> > result_matrix_01( add_matrix(p, q, split_index)); vector<vector<int> > result_matrix_10( add_matrix(r, s, split_index)); vector<vector<int> > result_matrix_11(add_matrix( add_matrix(add_matrix(t, p, split_index), r, split_index, -1), v, split_index, -1)); for (auto i = 0; i < split_index; i++) for (auto j = 0; j < split_index; j++) { result_matrix[i][j] = result_matrix_00[i][j]; result_matrix[i][j + split_index] = result_matrix_01[i][j]; result_matrix[split_index + i][j] = result_matrix_10[i][j]; result_matrix[i + split_index] [j + split_index] = result_matrix_11[i][j]; } a00.clear(); a01.clear(); a10.clear(); a11.clear(); b00.clear(); b01.clear(); b10.clear(); b11.clear(); p.clear(); q.clear(); r.clear(); s.clear(); t.clear(); u.clear(); v.clear(); result_matrix_00.clear(); result_matrix_01.clear(); result_matrix_10.clear(); result_matrix_11.clear(); } return result_matrix;} int main(){ vector<vector<int> > matrix_A = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 2, 2, 2, 2 } }; print(\"Array A\", matrix_A, 0, 0, ROW_1 - 1, COL_1 - 1); vector<vector<int> > matrix_B = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 2, 2, 2, 2 } }; print(\"Array B\", matrix_B, 0, 0, ROW_2 - 1, COL_2 - 1); vector<vector<int> > result_matrix( multiply_matrix(matrix_A, matrix_B)); print(\"Result Array\", result_matrix, 0, 0, ROW_1 - 1, COL_2 - 1);} // Time Complexity: T(N) = 7T(N/2) + O(N^2) => O(N^Log7)// which is approximately O(N^2.8074) Code Contributed By:// lucasletum", "e": 22187, "s": 16202, "text": null }, { "code": "# Version 3.6 import numpy as np def split(matrix): \"\"\" Splits a given matrix into quarters. Input: nxn matrix Output: tuple containing 4 n/2 x n/2 matrices corresponding to a, b, c, d \"\"\" row, col = matrix.shape row2, col2 = row//2, col//2 return matrix[:row2, :col2], matrix[:row2, col2:], matrix[row2:, :col2], matrix[row2:, col2:] def strassen(x, y): \"\"\" Computes matrix product by divide and conquer approach, recursively. Input: nxn matrices x and y Output: nxn matrix, product of x and y \"\"\" # Base case when size of matrices is 1x1 if len(x) == 1: return x * y # Splitting the matrices into quadrants. This will be done recursively # until the base case is reached. a, b, c, d = split(x) e, f, g, h = split(y) # Computing the 7 products, recursively (p1, p2...p7) p1 = strassen(a, f - h) p2 = strassen(a + b, h) p3 = strassen(c + d, e) p4 = strassen(d, g - e) p5 = strassen(a + d, e + h) p6 = strassen(b - d, g + h) p7 = strassen(a - c, e + f) # Computing the values of the 4 quadrants of the final matrix c c11 = p5 + p4 - p2 + p6 c12 = p1 + p2 c21 = p3 + p4 c22 = p1 + p5 - p3 - p7 # Combining the 4 quadrants into a single matrix by stacking horizontally and vertically. c = np.vstack((np.hstack((c11, c12)), np.hstack((c21, c22)))) return c", "e": 23612, "s": 22187, "text": null }, { "code": null, "e": 24146, "s": 23612, "text": "Array A =>\n 1 1 1 1\n 2 2 2 2\n 3 3 3 3\n 2 2 2 2\n\n\nArray B =>\n 1 1 1 1\n 2 2 2 2\n 3 3 3 3\n 2 2 2 2\n\n\nResult Array =>\n 8 8 8 8\n 16 16 16 16\n 24 24 24 24\n 16 16 16 16" }, { "code": null, "e": 24195, "s": 24146, "text": "Easy way to remember Strassen’s Matrix Equation " }, { "code": null, "e": 25119, "s": 24195, "text": "Strassen’s Matrix Multiplication | Divide and Conquer | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersStrassen’s Matrix Multiplication | Divide and Conquer | 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 / 4:37•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=E-QtwPi620I\" 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": 25460, "s": 25121, "text": "References: Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest https://www.youtube.com/watch?v=LOLebQ8nKHA https://www.youtube.com/watch?v=QXY4RskLQcIPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 25473, "s": 25460, "text": "PrayushDawda" }, { "code": null, "e": 25480, "s": 25473, "text": "rrrtnx" }, { "code": null, "e": 25492, "s": 25480, "text": "anikaseth98" }, { "code": null, "e": 25511, "s": 25492, "text": "shivanisinghss2110" }, { "code": null, "e": 25521, "s": 25511, "text": "rutvik_56" }, { "code": null, "e": 25530, "s": 25521, "text": "noob2000" }, { "code": null, "e": 25546, "s": 25530, "text": "amartyaghoshgfg" }, { "code": null, "e": 25557, "s": 25546, "text": "lucasletum" }, { "code": null, "e": 25572, "s": 25557, "text": "shruti456rawal" }, { "code": null, "e": 25589, "s": 25572, "text": "hardikkoriintern" }, { "code": null, "e": 25608, "s": 25589, "text": "Divide and Conquer" }, { "code": null, "e": 25615, "s": 25608, "text": "Matrix" }, { "code": null, "e": 25634, "s": 25615, "text": "Divide and Conquer" }, { "code": null, "e": 25641, "s": 25634, "text": "Matrix" }, { "code": null, "e": 25739, "s": 25641, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25750, "s": 25739, "text": "Merge Sort" }, { "code": null, "e": 25760, "s": 25750, "text": "QuickSort" }, { "code": null, "e": 25774, "s": 25760, "text": "Binary Search" }, { "code": null, "e": 25830, "s": 25774, "text": "Count Inversions in an array | Set 1 (Using Merge Sort)" }, { "code": null, "e": 25877, "s": 25830, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 25912, "s": 25877, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 25948, "s": 25912, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 25992, "s": 25948, "text": "Program to find largest element in an array" }, { "code": null, "e": 26023, "s": 25992, "text": "Rat in a Maze | Backtracking-2" } ]
What is the benefit of zerofill in MySQL?
ZEROFILL pads the displayed value of the field with zeros up to the display width set in the column definition. Let us understand the role of zero fill in MySQL using an example. Creating a table with two columns, one has zerofill and the second one does not. The query to create a table. mysql> create table ZeroFillDemo -> ( -> First int(18) zerofill, -> Second int(18) -> ); Query OK, 0 rows affected (0.63 sec) We can insert records in the table with the help of INSERT command. The query is as follows. mysql> insert into ZeroFillDemo values(1,1); Query OK, 1 row affected (0.13 sec) mysql> insert into ZeroFillDemo values(12,12); Query OK, 1 row affected (0.15 sec) mysql> insert into ZeroFillDemo values(123,123); Query OK, 1 row affected (0.10 sec) mysql> insert into ZeroFillDemo values(123456789,123456789); Query OK, 1 row affected (0.20 sec) Now, we can check the benefits of zerofill column with the help of select command. The query is as follows. mysql> select *from ZeroFillDemo; The following is the output. +--------------------+-----------+ | First | Second | +--------------------+-----------+ | 000000000000000001 | 1 | | 000000000000000012 | 12 | | 000000000000000123 | 123 | | 000000000123456789 | 123456789 | +--------------------+-----------+ 4 rows in set (0.00 sec) Look at the sample output,zero is filled at the beginning.
[ { "code": null, "e": 1351, "s": 1062, "text": "ZEROFILL pads the displayed value of the field with zeros up to the display width set in the column definition. Let us understand the role of zero fill in MySQL using an example. Creating a table with two columns, one has zerofill and the second one does not. The query to create a table." }, { "code": null, "e": 1489, "s": 1351, "text": "mysql> create table ZeroFillDemo\n -> (\n -> First int(18) zerofill,\n -> Second int(18)\n -> );\nQuery OK, 0 rows affected (0.63 sec)" }, { "code": null, "e": 1582, "s": 1489, "text": "We can insert records in the table with the help of INSERT command. The query is as follows." }, { "code": null, "e": 1934, "s": 1582, "text": "mysql> insert into ZeroFillDemo values(1,1);\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into ZeroFillDemo values(12,12);\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into ZeroFillDemo values(123,123);\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into ZeroFillDemo values(123456789,123456789);\nQuery OK, 1 row affected (0.20 sec)" }, { "code": null, "e": 2017, "s": 1934, "text": "Now, we can check the benefits of zerofill column with the help of select command." }, { "code": null, "e": 2042, "s": 2017, "text": "The query is as follows." }, { "code": null, "e": 2076, "s": 2042, "text": "mysql> select *from ZeroFillDemo;" }, { "code": null, "e": 2105, "s": 2076, "text": "The following is the output." }, { "code": null, "e": 2411, "s": 2105, "text": "+--------------------+-----------+\n| First | Second |\n+--------------------+-----------+\n| 000000000000000001 | 1 |\n| 000000000000000012 | 12 |\n| 000000000000000123 | 123 |\n| 000000000123456789 | 123456789 |\n+--------------------+-----------+\n4 rows in set (0.00 sec)\n" }, { "code": null, "e": 2470, "s": 2411, "text": "Look at the sample output,zero is filled at the beginning." } ]
Amazon Interview experience | Set 324 (For SDE2) - GeeksforGeeks
08 Jul, 2019 I got a call from an consultant for recruitment drive in Delhi. First round (1 hour 30 minutes): online writtenIt was online written round on a platform called Stockroom.io. Two string a haystack and needle is given find at what all indexes needle occurs in haystack as an anagram(0 based indexing)INPUT: str1 = "ABACDABCABA" , str2 = "BA" OUTPUT: 0,15,8,9 Expected time complexity is O(n). The only thing to pay attention was that ASCII characters starts from A.Given A company’s hierarchy where each employee reports to exactly one manager. and one manager can be reported by multiple employees, implement necessary setter getter functions in object oriented way. also write a helper instance methods to return lowest common manager for two given employeesanswer to this question was simple but had to write object oriented code and zip it then upload it. Two string a haystack and needle is given find at what all indexes needle occurs in haystack as an anagram(0 based indexing)INPUT: str1 = "ABACDABCABA" , str2 = "BA" OUTPUT: 0,15,8,9 Expected time complexity is O(n). The only thing to pay attention was that ASCII characters starts from A. INPUT: str1 = "ABACDABCABA" , str2 = "BA" OUTPUT: 0,15,8,9 Expected time complexity is O(n). The only thing to pay attention was that ASCII characters starts from A. Given A company’s hierarchy where each employee reports to exactly one manager. and one manager can be reported by multiple employees, implement necessary setter getter functions in object oriented way. also write a helper instance methods to return lowest common manager for two given employeesanswer to this question was simple but had to write object oriented code and zip it then upload it. Second round(1 hour): Design round This was most critical and important round. Design a geographically partitioned multi-player card game, that supports multiple players, multiple games at a time. Each game will have one contractor like ones we have in a bar, He can play a game or just watch it. integrate payment systems.First HLD was required, use cases, flow diagram. then a low level design was required all necessary classes where will u use polymorphism, where inheritance, multithreading, synchronised approach if needed, socket connections. Other things that surfaced and he asked as interview goes : round robin load balancer, hash-map based load balancer, two layer caching, nosql db, design patterns, solid principles, ACID property, CAP theorem etc. Interviewer was a senior person and knew a lot. I was nervous in this round but answered well. First HLD was required, use cases, flow diagram. then a low level design was required all necessary classes where will u use polymorphism, where inheritance, multithreading, synchronised approach if needed, socket connections. Other things that surfaced and he asked as interview goes : round robin load balancer, hash-map based load balancer, two layer caching, nosql db, design patterns, solid principles, ACID property, CAP theorem etc. Interviewer was a senior person and knew a lot. I was nervous in this round but answered well. Many behavioral questions Third round (1 hour): technical Many behavioral and “what if you were in a situation” questionsGiven an array of words which comes in a dictionary of some language in the same order.tell if its possible?ans. represent characters of words as a graph and find out if graph is cyclic (cycle in directed graph)the interviewer was very supportive. He gave me few important hints in terms of question understanding. Many behavioral and “what if you were in a situation” questions Given an array of words which comes in a dictionary of some language in the same order.tell if its possible?ans. represent characters of words as a graph and find out if graph is cyclic (cycle in directed graph)the interviewer was very supportive. He gave me few important hints in terms of question understanding. Fourth round (1 hour): technical He asked me what you like , I said array questions He started laughing. given an array of integers and two types of queries point update and range sum?ans: I said binary indexed tree then he asked for other ways I said segment tree, He asked more , I said prefix array or sqrt decomposition.he asked me to write code for the same. made some variations like lazy propagation. he asked me to write code for the same. made some variations like lazy propagation. topological sorting. given a words of dictionary tell alphabet ordering. many behavioural questions Hr came and told me that we are done for the day one more interview is there which was on next day.Hr was very supportive she gave me some constructive feedback and told me to get prepared well and come next day as next day waswith a Bar Raiser. Fifth round (1 hour): technical+ design + behavioural, Bar Raiser asked tree related questions , how to represent and model a tree.Design a Netflix type system. start from HLD to LLD. detailed discussed happened on thisdiscussion on search, video serving, authentication, encryption, dns lookup, which caching strategy would you chose?serving multi quality video etc.few behavioural questions. asked tree related questions , how to represent and model a tree. Design a Netflix type system. start from HLD to LLD. detailed discussed happened on thisdiscussion on search, video serving, authentication, encryption, dns lookup, which caching strategy would you chose?serving multi quality video etc. few behavioural questions. Few things to remember: for technical go through geekgsforgeeks practice test and interview experiencesfor design have a look at carreercupreview OS concepts.recruiters and hr is very supportiveprepare for behavioural questions well.prepare “do you want to ask any questions?” for technical go through geekgsforgeeks practice test and interview experiences for design have a look at carreercup review OS concepts. recruiters and hr is very supportive prepare for behavioural questions well. prepare “do you want to ask any questions?” If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Amazon Experienced Interview Experiences Amazon 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 Difference between ANN, CNN and RNN
[ { "code": null, "e": 26477, "s": 26449, "text": "\n08 Jul, 2019" }, { "code": null, "e": 26541, "s": 26477, "text": "I got a call from an consultant for recruitment drive in Delhi." }, { "code": null, "e": 26651, "s": 26541, "text": "First round (1 hour 30 minutes): online writtenIt was online written round on a platform called Stockroom.io." }, { "code": null, "e": 27335, "s": 26651, "text": "Two string a haystack and needle is given find at what all indexes needle occurs in haystack as an anagram(0 based indexing)INPUT: str1 = \"ABACDABCABA\" , str2 = \"BA\"\nOUTPUT: 0,15,8,9\nExpected time complexity is O(n). The only thing to pay attention was that ASCII characters starts from A.Given A company’s hierarchy where each employee reports to exactly one manager. and one manager can be reported by multiple employees, implement necessary setter getter functions in object oriented way. also write a helper instance methods to return lowest common manager for two given employeesanswer to this question was simple but had to write object oriented code and zip it then upload it." }, { "code": null, "e": 27625, "s": 27335, "text": "Two string a haystack and needle is given find at what all indexes needle occurs in haystack as an anagram(0 based indexing)INPUT: str1 = \"ABACDABCABA\" , str2 = \"BA\"\nOUTPUT: 0,15,8,9\nExpected time complexity is O(n). The only thing to pay attention was that ASCII characters starts from A." }, { "code": null, "e": 27685, "s": 27625, "text": "INPUT: str1 = \"ABACDABCABA\" , str2 = \"BA\"\nOUTPUT: 0,15,8,9\n" }, { "code": null, "e": 27792, "s": 27685, "text": "Expected time complexity is O(n). The only thing to pay attention was that ASCII characters starts from A." }, { "code": null, "e": 28187, "s": 27792, "text": "Given A company’s hierarchy where each employee reports to exactly one manager. and one manager can be reported by multiple employees, implement necessary setter getter functions in object oriented way. also write a helper instance methods to return lowest common manager for two given employeesanswer to this question was simple but had to write object oriented code and zip it then upload it." }, { "code": null, "e": 28266, "s": 28187, "text": "Second round(1 hour): Design round This was most critical and important round." }, { "code": null, "e": 29045, "s": 28266, "text": "Design a geographically partitioned multi-player card game, that supports multiple players, multiple games at a time. Each game will have one contractor like ones we have in a bar, He can play a game or just watch it. integrate payment systems.First HLD was required, use cases, flow diagram. then a low level design was required all necessary classes where will u use polymorphism, where inheritance, multithreading, synchronised approach if needed, socket connections. Other things that surfaced and he asked as interview goes : round robin load balancer, hash-map based load balancer, two layer caching, nosql db, design patterns, solid principles, ACID property, CAP theorem etc. Interviewer was a senior person and knew a lot. I was nervous in this round but answered well." }, { "code": null, "e": 29580, "s": 29045, "text": "First HLD was required, use cases, flow diagram. then a low level design was required all necessary classes where will u use polymorphism, where inheritance, multithreading, synchronised approach if needed, socket connections. Other things that surfaced and he asked as interview goes : round robin load balancer, hash-map based load balancer, two layer caching, nosql db, design patterns, solid principles, ACID property, CAP theorem etc. Interviewer was a senior person and knew a lot. I was nervous in this round but answered well." }, { "code": null, "e": 29606, "s": 29580, "text": "Many behavioral questions" }, { "code": null, "e": 29638, "s": 29606, "text": "Third round (1 hour): technical" }, { "code": null, "e": 30016, "s": 29638, "text": "Many behavioral and “what if you were in a situation” questionsGiven an array of words which comes in a dictionary of some language in the same order.tell if its possible?ans. represent characters of words as a graph and find out if graph is cyclic (cycle in directed graph)the interviewer was very supportive. He gave me few important hints in terms of question understanding." }, { "code": null, "e": 30080, "s": 30016, "text": "Many behavioral and “what if you were in a situation” questions" }, { "code": null, "e": 30395, "s": 30080, "text": "Given an array of words which comes in a dictionary of some language in the same order.tell if its possible?ans. represent characters of words as a graph and find out if graph is cyclic (cycle in directed graph)the interviewer was very supportive. He gave me few important hints in terms of question understanding." }, { "code": null, "e": 30501, "s": 30395, "text": "Fourth round (1 hour): technical He asked me what you like , I said array questions He started laughing." }, { "code": null, "e": 30804, "s": 30501, "text": "given an array of integers and two types of queries point update and range sum?ans: I said binary indexed tree then he asked for other ways I said segment tree, He asked more , I said prefix array or sqrt decomposition.he asked me to write code for the same. made some variations like lazy propagation." }, { "code": null, "e": 30888, "s": 30804, "text": "he asked me to write code for the same. made some variations like lazy propagation." }, { "code": null, "e": 30961, "s": 30888, "text": "topological sorting. given a words of dictionary tell alphabet ordering." }, { "code": null, "e": 30988, "s": 30961, "text": "many behavioural questions" }, { "code": null, "e": 31234, "s": 30988, "text": "Hr came and told me that we are done for the day one more interview is there which was on next day.Hr was very supportive she gave me some constructive feedback and told me to get prepared well and come next day as next day waswith a Bar Raiser." }, { "code": null, "e": 31300, "s": 31234, "text": "Fifth round (1 hour): technical+ design + behavioural, Bar Raiser" }, { "code": null, "e": 31628, "s": 31300, "text": "asked tree related questions , how to represent and model a tree.Design a Netflix type system. start from HLD to LLD. detailed discussed happened on thisdiscussion on search, video serving, authentication, encryption, dns lookup, which caching strategy would you chose?serving multi quality video etc.few behavioural questions." }, { "code": null, "e": 31694, "s": 31628, "text": "asked tree related questions , how to represent and model a tree." }, { "code": null, "e": 31931, "s": 31694, "text": "Design a Netflix type system. start from HLD to LLD. detailed discussed happened on thisdiscussion on search, video serving, authentication, encryption, dns lookup, which caching strategy would you chose?serving multi quality video etc." }, { "code": null, "e": 31958, "s": 31931, "text": "few behavioural questions." }, { "code": null, "e": 31982, "s": 31958, "text": "Few things to remember:" }, { "code": null, "e": 32235, "s": 31982, "text": "for technical go through geekgsforgeeks practice test and interview experiencesfor design have a look at carreercupreview OS concepts.recruiters and hr is very supportiveprepare for behavioural questions well.prepare “do you want to ask any questions?”" }, { "code": null, "e": 32315, "s": 32235, "text": "for technical go through geekgsforgeeks practice test and interview experiences" }, { "code": null, "e": 32352, "s": 32315, "text": "for design have a look at carreercup" }, { "code": null, "e": 32372, "s": 32352, "text": "review OS concepts." }, { "code": null, "e": 32409, "s": 32372, "text": "recruiters and hr is very supportive" }, { "code": null, "e": 32449, "s": 32409, "text": "prepare for behavioural questions well." }, { "code": null, "e": 32493, "s": 32449, "text": "prepare “do you want to ask any questions?”" }, { "code": null, "e": 32714, "s": 32493, "text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 32838, "s": 32714, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 32845, "s": 32838, "text": "Amazon" }, { "code": null, "e": 32857, "s": 32845, "text": "Experienced" }, { "code": null, "e": 32879, "s": 32857, "text": "Interview Experiences" }, { "code": null, "e": 32886, "s": 32879, "text": "Amazon" }, { "code": null, "e": 32984, "s": 32886, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33049, "s": 32984, "text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022" }, { "code": null, "e": 33131, "s": 33049, "text": "Goldman Sachs Interview Experience for Technology Analyst (1.8 Years Experienced)" }, { "code": null, "e": 33208, "s": 33131, "text": "Amazon Interview Experience for System Development Engineer (Exp - 6 months)" }, { "code": null, "e": 33271, "s": 33208, "text": "FactSet Interview Experience (Off-Campus) 8 Months Experienced" }, { "code": null, "e": 33312, "s": 33271, "text": "Walmart Interview Experience for SDE-III" }, { "code": null, "e": 33339, "s": 33312, "text": "Amazon Interview Questions" }, { "code": null, "e": 33399, "s": 33339, "text": "Commonly Asked Java Programming Interview Questions | Set 2" }, { "code": null, "e": 33450, "s": 33399, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 33492, "s": 33450, "text": "Amazon AWS Interview Experience for SDE-1" } ]
How to Build a Book Library App using Google Books API in Android? - GeeksforGeeks
21 Jan, 2021 If you are looking for building a book library app and you want to load a huge data of books then for adding this feature, you have to use a simple API which is provided by Google, and of course, it’s free. In this article, we will take a look at the implementation of this API in our Android App. We will be building a simple application in which we will be searching different types of books and we will get to see the list of books related to that topic in our RecyclerView. For searching these books we will be using a free API provided by Google which holds a huge collection of books. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Add the dependency for Volley in your Gradle files Navigate to the app > Gradle Scripts > build.gradle file and add below dependency in the dependencies section. implementation ‘com.android.volley:volley:1.1.1’ implementation ‘com.squareup.picasso:picasso:2.71828’ After adding the below dependencies in your gradle file now sync your project and now we will move towards our activity_main.xml file. As we will be using volley to fetch data from our API and Picasso image loading library to load images from URL. Step 3: Adding permissions for the Internet Navigate to the app > AndroidManifest.xml and add the below permissions to it. XML <uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> As we will be loading the books from API so we have to request Internet permissions from the user. For that add the permissions for the internet in AndroidManifest.xml. Step 4: Working with the activity_main.xml file Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <LinearLayout android:id="@+id/idLLsearch" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:weightSum="5"> <!--edit text for getting the search query for book from user--> <EditText android:id="@+id/idEdtSearchBooks" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="4" /> <!--image button for our search button --> <ImageButton android:id="@+id/idBtnSearch" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:src="@drawable/ic_search" /> </LinearLayout> <!--recycler view for displaying our list of books--> <androidx.recyclerview.widget.RecyclerView android:id="@+id/idRVBooks" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/idLLsearch" /> <!--progressbar for displaying our loading indicator--> <ProgressBar android:id="@+id/idLoadingPB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:visibility="gone" /> </RelativeLayout> Step 5: Creating a Modal Class for storing our data from the API. For creating a new Modal class. Navigate to the app > java > your app’s package name > Right-click on it and Click on New > Java class and give a name to our java class as BookInfo and add below code to it. Comments are added in the code to get to know in more detail. Java import java.util.ArrayList; public class BookInfo { // creating string, int and array list // variables for our book details private String title; private String subtitle; private ArrayList<String> authors; private String publisher; private String publishedDate; private String description; private int pageCount; private String thumbnail; private String previewLink; private String infoLink; private String buyLink; // creating getter and setter methods public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSubtitle() { return subtitle; } public void setSubtitle(String subtitle) { this.subtitle = subtitle; } public ArrayList<String> getAuthors() { return authors; } public void setAuthors(ArrayList<String> authors) { this.authors = authors; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public String getPublishedDate() { return publishedDate; } public void setPublishedDate(String publishedDate) { this.publishedDate = publishedDate; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getPageCount() { return pageCount; } public void setPageCount(int pageCount) { this.pageCount = pageCount; } public String getThumbnail() { return thumbnail; } public void setThumbnail(String thumbnail) { this.thumbnail = thumbnail; } public String getPreviewLink() { return previewLink; } public void setPreviewLink(String previewLink) { this.previewLink = previewLink; } public String getInfoLink() { return infoLink; } public void setInfoLink(String infoLink) { this.infoLink = infoLink; } public String getBuyLink() { return buyLink; } public void setBuyLink(String buyLink) { this.buyLink = buyLink; } // creating a constructor class for our BookInfo public BookInfo(String title, String subtitle, ArrayList<String> authors, String publisher, String publishedDate, String description, int pageCount, String thumbnail, String previewLink, String infoLink, String buyLink) { this.title = title; this.subtitle = subtitle; this.authors = authors; this.publisher = publisher; this.publishedDate = publishedDate; this.description = description; this.pageCount = pageCount; this.thumbnail = thumbnail; this.previewLink = previewLink; this.infoLink = infoLink; this.buyLink = buyLink; }} Step 6: Create a new layout resource file Go to the app > res > layout > right-click > New > Layout Resource File and name the file as book_rv_item and add the following code to this file. XML <?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="4dp" app:cardCornerRadius="8dp" app:cardElevation="8dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:id="@+id/idIVbook" android:layout_width="130dp" android:layout_height="160dp" android:layout_margin="10dp" /> <TextView android:id="@+id/idTVBookTitle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_toEndOf="@id/idIVbook" android:padding="3dp" android:text="Book Title" android:textColor="@color/black" android:textSize="11sp" /> <TextView android:id="@+id/idTVpublisher" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVBookTitle" android:layout_marginTop="3dp" android:layout_toEndOf="@id/idIVbook" android:padding="3dp" android:text="Publisher" android:textColor="@color/black" android:textSize="11sp" /> <TextView android:id="@+id/idTVPageCount" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVpublisher" android:layout_marginTop="3dp" android:layout_toEndOf="@id/idIVbook" android:padding="3dp" android:text="Page count" android:textColor="@color/black" android:textSize="11sp" /> <TextView android:id="@+id/idTVDate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/idTVPageCount" android:layout_alignParentEnd="true" android:layout_marginEnd="5dp" android:padding="3dp" android:text="date" android:textColor="@color/black" android:textSize="11sp" /> </RelativeLayout> </androidx.cardview.widget.CardView> Step 7: Creating an Adapter class for setting our data to the item of RecyclerView Navigate to the app > java > your app’s package name > Right-click on it Click on New > Java class and name it as BookAdapter and add below code to it. Comments are added in the code to get to know in more detail. Java import android.content.Context;import android.content.Intent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class BookAdapter extends RecyclerView.Adapter<BookAdapter.BookViewHolder> { // creating variables for arraylist and context. private ArrayList<BookInfo> bookInfoArrayList; private Context mcontext; // creating constructor for array list and context. public BookAdapter(ArrayList<BookInfo> bookInfoArrayList, Context mcontext) { this.bookInfoArrayList = bookInfoArrayList; this.mcontext = mcontext; } @NonNull @Override public BookViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // inflating our layout for item of recycler view item. View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.book_rv_item, parent, false); return new BookViewHolder(view); } @Override public void onBindViewHolder(@NonNull BookViewHolder holder, int position) { // inside on bind view holder method we are // setting ou data to each UI component. BookInfo bookInfo = bookInfoArrayList.get(position); holder.nameTV.setText(bookInfo.getTitle()); holder.publisherTV.setText(bookInfo.getPublisher()); holder.pageCountTV.setText("No of Pages : " + bookInfo.getPageCount()); holder.dateTV.setText(bookInfo.getPublishedDate()); // below line is use to set image from URL in our image view. Picasso.get().load(bookInfo.getThumbnail()).into(holder.bookIV); // below line is use to add on click listener for our item of recycler view. holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // inside on click listener method we are calling a new activity // and passing all the data of that item in next intent. Intent i = new Intent(mcontext, BookDetails.class); i.putExtra("title", bookInfo.getTitle()); i.putExtra("subtitle", bookInfo.getSubtitle()); i.putExtra("authors", bookInfo.getAuthors()); i.putExtra("publisher", bookInfo.getPublisher()); i.putExtra("publishedDate", bookInfo.getPublishedDate()); i.putExtra("description", bookInfo.getDescription()); i.putExtra("pageCount", bookInfo.getPageCount()); i.putExtra("thumbnail", bookInfo.getThumbnail()); i.putExtra("previewLink", bookInfo.getPreviewLink()); i.putExtra("infoLink", bookInfo.getInfoLink()); i.putExtra("buyLink", bookInfo.getBuyLink()); // after passing that data we are // starting our new intent. mcontext.startActivity(i); } }); } @Override public int getItemCount() { // inside get item count method we // are returning the size of our array list. return bookInfoArrayList.size(); } public class BookViewHolder extends RecyclerView.ViewHolder { // below line is use to initialize // our text view and image views. TextView nameTV, publisherTV, pageCountTV, dateTV; ImageView bookIV; public BookViewHolder(View itemView) { super(itemView); nameTV = itemView.findViewById(R.id.idTVBookTitle); publisherTV = itemView.findViewById(R.id.idTVpublisher); pageCountTV = itemView.findViewById(R.id.idTVPageCount); dateTV = itemView.findViewById(R.id.idTVDate); bookIV = itemView.findViewById(R.id.idIVbook); } }} Step 8: Creating a new Activity for displaying our Book Info in detail Navigate to the app > java > your app’s package name > Right-click on it and click on New > Activity > Select Empty Activity and name it as BookDetails. Make sure to select Empty Activity. Working with the activity_book_details.xml file: Go to the activity_book_details.xml file and refer to the following code. Below is the code for the activity_book_details.xml file. XML <?xml version="1.0" encoding="utf-8"?><ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".BookDetails"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <!--Image view for displaying our book image--> <ImageView android:id="@+id/idIVbook" android:layout_width="130dp" android:layout_height="160dp" android:layout_margin="18dp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:orientation="vertical"> <!--Text view for displaying book publisher--> <TextView android:id="@+id/idTVpublisher" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="4dp" android:text="Publisher" android:textColor="@color/black" android:textSize="15sp" /> <!--text view for displaying number of pages of book--> <TextView android:id="@+id/idTVNoOfPages" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="4dp" android:padding="4dp" android:text="Number of Pages" android:textColor="@color/black" android:textSize="15sp" /> <!--text view for displaying book publish date--> <TextView android:id="@+id/idTVPublishDate" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="4dp" android:padding="4dp" android:text="Publish Date" android:textColor="@color/black" android:textSize="15sp" /> </LinearLayout> </LinearLayout> <!--text view for displaying book title--> <TextView android:id="@+id/idTVTitle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:padding="4dp" android:text="title" android:textColor="@color/black" android:textSize="15sp" /> <!--text view for displaying book subtitle--> <TextView android:id="@+id/idTVSubTitle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:padding="4dp" android:text="subtitle" android:textColor="@color/black" android:textSize="12sp" /> <!--text view for displaying book description--> <TextView android:id="@+id/idTVDescription" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:padding="4dp" android:text="description" android:textColor="@color/black" android:textSize="12sp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:orientation="horizontal" android:weightSum="2"> <!--button for displaying book preview--> <Button android:id="@+id/idBtnPreview" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="4dp" android:layout_weight="1" android:text="Preview" android:textAllCaps="false" /> <!--button for opening buying page of the book--> <Button android:id="@+id/idBtnBuy" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="4dp" android:layout_weight="1" android:text="Buy" android:textAllCaps="false" /> </LinearLayout> </LinearLayout></ScrollView> Working with the BookDetails.java file: Go to the BookDetails.java file and refer to the following code. Below is the code for the BookDetails.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class BookDetails extends AppCompatActivity { // creating variables for strings,text view, image views and button. String title, subtitle, publisher, publishedDate, description, thumbnail, previewLink, infoLink, buyLink; int pageCount; private ArrayList<String> authors; TextView titleTV, subtitleTV, publisherTV, descTV, pageTV, publishDateTV; Button previewBtn, buyBtn; private ImageView bookIV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_book_details); // initializing our views.. titleTV = findViewById(R.id.idTVTitle); subtitleTV = findViewById(R.id.idTVSubTitle); publisherTV = findViewById(R.id.idTVpublisher); descTV = findViewById(R.id.idTVDescription); pageTV = findViewById(R.id.idTVNoOfPages); publishDateTV = findViewById(R.id.idTVPublishDate); previewBtn = findViewById(R.id.idBtnPreview); buyBtn = findViewById(R.id.idBtnBuy); bookIV = findViewById(R.id.idIVbook); // getting the data which we have passed from our adapter class. title = getIntent().getStringExtra("title"); subtitle = getIntent().getStringExtra("subtitle"); publisher = getIntent().getStringExtra("publisher"); publishedDate = getIntent().getStringExtra("publishedDate"); description = getIntent().getStringExtra("description"); pageCount = getIntent().getIntExtra("pageCount", 0); thumbnail = getIntent().getStringExtra("thumbnail"); previewLink = getIntent().getStringExtra("previewLink"); infoLink = getIntent().getStringExtra("infoLink"); buyLink = getIntent().getStringExtra("buyLink"); // after getting the data we are setting // that data to our text views and image view. titleTV.setText(title); subtitleTV.setText(subtitle); publisherTV.setText(publisher); publishDateTV.setText("Published On : " + publishedDate); descTV.setText(description); pageTV.setText("No Of Pages : " + pageCount); Picasso.get().load(thumbnail).into(bookIV); // adding on click listener for our preview button. previewBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (previewLink.isEmpty()) { // below toast message is displayed when preview link is not present. Toast.makeText(BookDetails.this, "No preview Link present", Toast.LENGTH_SHORT).show(); return; } // if the link is present we are opening // that link via an intent. Uri uri = Uri.parse(previewLink); Intent i = new Intent(Intent.ACTION_VIEW, uri); startActivity(i); } }); // initializing on click listener for buy button. buyBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (buyLink.isEmpty()) { // below toast message is displaying when buy link is empty. Toast.makeText(BookDetails.this, "No buy page present for this book", Toast.LENGTH_SHORT).show(); return; } // if the link is present we are opening // the link via an intent. Uri uri = Uri.parse(buyLink); Intent i = new Intent(Intent.ACTION_VIEW, uri); startActivity(i); } }); }} Step 9: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.view.View;import android.widget.EditText;import android.widget.ImageButton;import android.widget.ProgressBar;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonObjectRequest;import com.android.volley.toolbox.Volley; import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // creating variables for our request queue, // array list, progressbar, edittext, // image button and our recycler view. private RequestQueue mRequestQueue; private ArrayList<BookInfo> bookInfoArrayList; private ProgressBar progressBar; private EditText searchEdt; private ImageButton searchBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our views. progressBar = findViewById(R.id.idLoadingPB); searchEdt = findViewById(R.id.idEdtSearchBooks); searchBtn = findViewById(R.id.idBtnSearch); // initializing on click listener for our button. searchBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { progressBar.setVisibility(View.VISIBLE); // checking if our edittext field is empty or not. if (searchEdt.getText().toString().isEmpty()) { searchEdt.setError("Please enter search query"); return; } // if the search query is not empty then we are // calling get book info method to load all // the books from the API. getBooksInfo(searchEdt.getText().toString()); } }); } private void getBooksInfo(String query) { // creating a new array list. bookInfoArrayList = new ArrayList<>(); // below line is use to initialize // the variable for our request queue. mRequestQueue = Volley.newRequestQueue(MainActivity.this); // below line is use to clear cache this // will be use when our data is being updated. mRequestQueue.getCache().clear(); // below is the url for getting data from API in json format. String url = "https://www.googleapis.com/books/v1/volumes?q=" + query; // below line we are creating a new request queue. RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // below line is use to make json object request inside that we // are passing url, get method and getting json object. . JsonObjectRequest booksObjrequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { progressBar.setVisibility(View.GONE); // inside on response method we are extracting all our json data. try { JSONArray itemsArray = response.getJSONArray("items"); for (int i = 0; i < itemsArray.length(); i++) { JSONObject itemsObj = itemsArray.getJSONObject(i); JSONObject volumeObj = itemsObj.getJSONObject("volumeInfo"); String title = volumeObj.optString("title"); String subtitle = volumeObj.optString("subtitle"); JSONArray authorsArray = volumeObj.getJSONArray("authors"); String publisher = volumeObj.optString("publisher"); String publishedDate = volumeObj.optString("publishedDate"); String description = volumeObj.optString("description"); int pageCount = volumeObj.optInt("pageCount"); JSONObject imageLinks = volumeObj.optJSONObject("imageLinks"); String thumbnail = imageLinks.optString("thumbnail"); String previewLink = volumeObj.optString("previewLink"); String infoLink = volumeObj.optString("infoLink"); JSONObject saleInfoObj = itemsObj.optJSONObject("saleInfo"); String buyLink = saleInfoObj.optString("buyLink"); ArrayList<String> authorsArrayList = new ArrayList<>(); if (authorsArray.length() != 0) { for (int j = 0; j < authorsArray.length(); j++) { authorsArrayList.add(authorsArray.optString(i)); } } // after extracting all the data we are // saving this data in our modal class. BookInfo bookInfo = new BookInfo(title, subtitle, authorsArrayList, publisher, publishedDate, description, pageCount, thumbnail, previewLink, infoLink, buyLink); // below line is use to pass our modal // class in our array list. bookInfoArrayList.add(bookInfo); // below line is use to pass our // array list in adapter class. BookAdapter adapter = new BookAdapter(bookInfoArrayList, MainActivity.this); // below line is use to add linear layout // manager for our recycler view. LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, RecyclerView.VERTICAL, false); RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.idRVBooks); // in below line we are setting layout manager and // adapter to our recycler view. mRecyclerView.setLayoutManager(linearLayoutManager); mRecyclerView.setAdapter(adapter); } } catch (JSONException e) { e.printStackTrace(); // displaying a toast message when we get any error from API Toast.makeText(MainActivity.this, "No Data Found" + e, Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // also displaying error message in toast. Toast.makeText(MainActivity.this, "Error found is " + error, Toast.LENGTH_SHORT).show(); } }); // at last we are adding our json object // request in our request queue. queue.add(booksObjrequest); }} Check out the project on the below link: https://github.com/ChaitanyaMunje/LibraryApp android Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 26381, "s": 26353, "text": "\n21 Jan, 2021" }, { "code": null, "e": 26680, "s": 26381, "text": "If you are looking for building a book library app and you want to load a huge data of books then for adding this feature, you have to use a simple API which is provided by Google, and of course, it’s free. In this article, we will take a look at the implementation of this API in our Android App. " }, { "code": null, "e": 27140, "s": 26680, "text": "We will be building a simple application in which we will be searching different types of books and we will get to see the list of books related to that topic in our RecyclerView. For searching these books we will be using a free API provided by Google which holds a huge collection of books. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 27169, "s": 27140, "text": "Step 1: Create a New Project" }, { "code": null, "e": 27331, "s": 27169, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 27390, "s": 27331, "text": "Step 2: Add the dependency for Volley in your Gradle files" }, { "code": null, "e": 27502, "s": 27390, "text": "Navigate to the app > Gradle Scripts > build.gradle file and add below dependency in the dependencies section. " }, { "code": null, "e": 27551, "s": 27502, "text": "implementation ‘com.android.volley:volley:1.1.1’" }, { "code": null, "e": 27606, "s": 27551, "text": "implementation ‘com.squareup.picasso:picasso:2.71828’ " }, { "code": null, "e": 27857, "s": 27606, "text": "After adding the below dependencies in your gradle file now sync your project and now we will move towards our activity_main.xml file. As we will be using volley to fetch data from our API and Picasso image loading library to load images from URL. " }, { "code": null, "e": 27902, "s": 27857, "text": "Step 3: Adding permissions for the Internet " }, { "code": null, "e": 27982, "s": 27902, "text": "Navigate to the app > AndroidManifest.xml and add the below permissions to it. " }, { "code": null, "e": 27986, "s": 27982, "text": "XML" }, { "code": "<uses-permission android:name=\"android.permission.INTERNET\" /><uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" />", "e": 28123, "s": 27986, "text": null }, { "code": null, "e": 28293, "s": 28123, "text": "As we will be loading the books from API so we have to request Internet permissions from the user. For that add the permissions for the internet in AndroidManifest.xml. " }, { "code": null, "e": 28341, "s": 28293, "text": "Step 4: Working with the activity_main.xml file" }, { "code": null, "e": 28457, "s": 28341, "text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file." }, { "code": null, "e": 28461, "s": 28457, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <LinearLayout android:id=\"@+id/idLLsearch\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\" android:weightSum=\"5\"> <!--edit text for getting the search query for book from user--> <EditText android:id=\"@+id/idEdtSearchBooks\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_weight=\"4\" /> <!--image button for our search button --> <ImageButton android:id=\"@+id/idBtnSearch\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:src=\"@drawable/ic_search\" /> </LinearLayout> <!--recycler view for displaying our list of books--> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/idRVBooks\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_below=\"@id/idLLsearch\" /> <!--progressbar for displaying our loading indicator--> <ProgressBar android:id=\"@+id/idLoadingPB\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:visibility=\"gone\" /> </RelativeLayout>", "e": 30112, "s": 28461, "text": null }, { "code": null, "e": 30179, "s": 30112, "text": "Step 5: Creating a Modal Class for storing our data from the API. " }, { "code": null, "e": 30449, "s": 30179, "text": "For creating a new Modal class. Navigate to the app > java > your app’s package name > Right-click on it and Click on New > Java class and give a name to our java class as BookInfo and add below code to it. Comments are added in the code to get to know in more detail. " }, { "code": null, "e": 30454, "s": 30449, "text": "Java" }, { "code": "import java.util.ArrayList; public class BookInfo { // creating string, int and array list // variables for our book details private String title; private String subtitle; private ArrayList<String> authors; private String publisher; private String publishedDate; private String description; private int pageCount; private String thumbnail; private String previewLink; private String infoLink; private String buyLink; // creating getter and setter methods public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSubtitle() { return subtitle; } public void setSubtitle(String subtitle) { this.subtitle = subtitle; } public ArrayList<String> getAuthors() { return authors; } public void setAuthors(ArrayList<String> authors) { this.authors = authors; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public String getPublishedDate() { return publishedDate; } public void setPublishedDate(String publishedDate) { this.publishedDate = publishedDate; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getPageCount() { return pageCount; } public void setPageCount(int pageCount) { this.pageCount = pageCount; } public String getThumbnail() { return thumbnail; } public void setThumbnail(String thumbnail) { this.thumbnail = thumbnail; } public String getPreviewLink() { return previewLink; } public void setPreviewLink(String previewLink) { this.previewLink = previewLink; } public String getInfoLink() { return infoLink; } public void setInfoLink(String infoLink) { this.infoLink = infoLink; } public String getBuyLink() { return buyLink; } public void setBuyLink(String buyLink) { this.buyLink = buyLink; } // creating a constructor class for our BookInfo public BookInfo(String title, String subtitle, ArrayList<String> authors, String publisher, String publishedDate, String description, int pageCount, String thumbnail, String previewLink, String infoLink, String buyLink) { this.title = title; this.subtitle = subtitle; this.authors = authors; this.publisher = publisher; this.publishedDate = publishedDate; this.description = description; this.pageCount = pageCount; this.thumbnail = thumbnail; this.previewLink = previewLink; this.infoLink = infoLink; this.buyLink = buyLink; }}", "e": 33384, "s": 30454, "text": null }, { "code": null, "e": 33426, "s": 33384, "text": "Step 6: Create a new layout resource file" }, { "code": null, "e": 33573, "s": 33426, "text": "Go to the app > res > layout > right-click > New > Layout Resource File and name the file as book_rv_item and add the following code to this file." }, { "code": null, "e": 33577, "s": 33573, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"4dp\" app:cardCornerRadius=\"8dp\" app:cardElevation=\"8dp\"> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <ImageView android:id=\"@+id/idIVbook\" android:layout_width=\"130dp\" android:layout_height=\"160dp\" android:layout_margin=\"10dp\" /> <TextView android:id=\"@+id/idTVBookTitle\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"10dp\" android:layout_toEndOf=\"@id/idIVbook\" android:padding=\"3dp\" android:text=\"Book Title\" android:textColor=\"@color/black\" android:textSize=\"11sp\" /> <TextView android:id=\"@+id/idTVpublisher\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVBookTitle\" android:layout_marginTop=\"3dp\" android:layout_toEndOf=\"@id/idIVbook\" android:padding=\"3dp\" android:text=\"Publisher\" android:textColor=\"@color/black\" android:textSize=\"11sp\" /> <TextView android:id=\"@+id/idTVPageCount\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVpublisher\" android:layout_marginTop=\"3dp\" android:layout_toEndOf=\"@id/idIVbook\" android:padding=\"3dp\" android:text=\"Page count\" android:textColor=\"@color/black\" android:textSize=\"11sp\" /> <TextView android:id=\"@+id/idTVDate\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVPageCount\" android:layout_alignParentEnd=\"true\" android:layout_marginEnd=\"5dp\" android:padding=\"3dp\" android:text=\"date\" android:textColor=\"@color/black\" android:textSize=\"11sp\" /> </RelativeLayout> </androidx.cardview.widget.CardView>", "e": 36044, "s": 33577, "text": null }, { "code": null, "e": 36127, "s": 36044, "text": "Step 7: Creating an Adapter class for setting our data to the item of RecyclerView" }, { "code": null, "e": 36342, "s": 36127, "text": "Navigate to the app > java > your app’s package name > Right-click on it Click on New > Java class and name it as BookAdapter and add below code to it. Comments are added in the code to get to know in more detail. " }, { "code": null, "e": 36347, "s": 36342, "text": "Java" }, { "code": "import android.content.Context;import android.content.Intent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class BookAdapter extends RecyclerView.Adapter<BookAdapter.BookViewHolder> { // creating variables for arraylist and context. private ArrayList<BookInfo> bookInfoArrayList; private Context mcontext; // creating constructor for array list and context. public BookAdapter(ArrayList<BookInfo> bookInfoArrayList, Context mcontext) { this.bookInfoArrayList = bookInfoArrayList; this.mcontext = mcontext; } @NonNull @Override public BookViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // inflating our layout for item of recycler view item. View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.book_rv_item, parent, false); return new BookViewHolder(view); } @Override public void onBindViewHolder(@NonNull BookViewHolder holder, int position) { // inside on bind view holder method we are // setting ou data to each UI component. BookInfo bookInfo = bookInfoArrayList.get(position); holder.nameTV.setText(bookInfo.getTitle()); holder.publisherTV.setText(bookInfo.getPublisher()); holder.pageCountTV.setText(\"No of Pages : \" + bookInfo.getPageCount()); holder.dateTV.setText(bookInfo.getPublishedDate()); // below line is use to set image from URL in our image view. Picasso.get().load(bookInfo.getThumbnail()).into(holder.bookIV); // below line is use to add on click listener for our item of recycler view. holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // inside on click listener method we are calling a new activity // and passing all the data of that item in next intent. Intent i = new Intent(mcontext, BookDetails.class); i.putExtra(\"title\", bookInfo.getTitle()); i.putExtra(\"subtitle\", bookInfo.getSubtitle()); i.putExtra(\"authors\", bookInfo.getAuthors()); i.putExtra(\"publisher\", bookInfo.getPublisher()); i.putExtra(\"publishedDate\", bookInfo.getPublishedDate()); i.putExtra(\"description\", bookInfo.getDescription()); i.putExtra(\"pageCount\", bookInfo.getPageCount()); i.putExtra(\"thumbnail\", bookInfo.getThumbnail()); i.putExtra(\"previewLink\", bookInfo.getPreviewLink()); i.putExtra(\"infoLink\", bookInfo.getInfoLink()); i.putExtra(\"buyLink\", bookInfo.getBuyLink()); // after passing that data we are // starting our new intent. mcontext.startActivity(i); } }); } @Override public int getItemCount() { // inside get item count method we // are returning the size of our array list. return bookInfoArrayList.size(); } public class BookViewHolder extends RecyclerView.ViewHolder { // below line is use to initialize // our text view and image views. TextView nameTV, publisherTV, pageCountTV, dateTV; ImageView bookIV; public BookViewHolder(View itemView) { super(itemView); nameTV = itemView.findViewById(R.id.idTVBookTitle); publisherTV = itemView.findViewById(R.id.idTVpublisher); pageCountTV = itemView.findViewById(R.id.idTVPageCount); dateTV = itemView.findViewById(R.id.idTVDate); bookIV = itemView.findViewById(R.id.idIVbook); } }}", "e": 40321, "s": 36347, "text": null }, { "code": null, "e": 40393, "s": 40321, "text": "Step 8: Creating a new Activity for displaying our Book Info in detail " }, { "code": null, "e": 40583, "s": 40393, "text": "Navigate to the app > java > your app’s package name > Right-click on it and click on New > Activity > Select Empty Activity and name it as BookDetails. Make sure to select Empty Activity. " }, { "code": null, "e": 40632, "s": 40583, "text": "Working with the activity_book_details.xml file:" }, { "code": null, "e": 40764, "s": 40632, "text": "Go to the activity_book_details.xml file and refer to the following code. Below is the code for the activity_book_details.xml file." }, { "code": null, "e": 40768, "s": 40764, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><ScrollView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".BookDetails\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\"> <!--Image view for displaying our book image--> <ImageView android:id=\"@+id/idIVbook\" android:layout_width=\"130dp\" android:layout_height=\"160dp\" android:layout_margin=\"18dp\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"20dp\" android:orientation=\"vertical\"> <!--Text view for displaying book publisher--> <TextView android:id=\"@+id/idTVpublisher\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:padding=\"4dp\" android:text=\"Publisher\" android:textColor=\"@color/black\" android:textSize=\"15sp\" /> <!--text view for displaying number of pages of book--> <TextView android:id=\"@+id/idTVNoOfPages\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"4dp\" android:padding=\"4dp\" android:text=\"Number of Pages\" android:textColor=\"@color/black\" android:textSize=\"15sp\" /> <!--text view for displaying book publish date--> <TextView android:id=\"@+id/idTVPublishDate\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"4dp\" android:padding=\"4dp\" android:text=\"Publish Date\" android:textColor=\"@color/black\" android:textSize=\"15sp\" /> </LinearLayout> </LinearLayout> <!--text view for displaying book title--> <TextView android:id=\"@+id/idTVTitle\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"8dp\" android:padding=\"4dp\" android:text=\"title\" android:textColor=\"@color/black\" android:textSize=\"15sp\" /> <!--text view for displaying book subtitle--> <TextView android:id=\"@+id/idTVSubTitle\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"8dp\" android:padding=\"4dp\" android:text=\"subtitle\" android:textColor=\"@color/black\" android:textSize=\"12sp\" /> <!--text view for displaying book description--> <TextView android:id=\"@+id/idTVDescription\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"8dp\" android:padding=\"4dp\" android:text=\"description\" android:textColor=\"@color/black\" android:textSize=\"12sp\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"8dp\" android:orientation=\"horizontal\" android:weightSum=\"2\"> <!--button for displaying book preview--> <Button android:id=\"@+id/idBtnPreview\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"4dp\" android:layout_weight=\"1\" android:text=\"Preview\" android:textAllCaps=\"false\" /> <!--button for opening buying page of the book--> <Button android:id=\"@+id/idBtnBuy\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"4dp\" android:layout_weight=\"1\" android:text=\"Buy\" android:textAllCaps=\"false\" /> </LinearLayout> </LinearLayout></ScrollView>", "e": 45607, "s": 40768, "text": null }, { "code": null, "e": 45647, "s": 45607, "text": "Working with the BookDetails.java file:" }, { "code": null, "e": 45835, "s": 45647, "text": "Go to the BookDetails.java file and refer to the following code. Below is the code for the BookDetails.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 45840, "s": 45835, "text": "Java" }, { "code": "import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class BookDetails extends AppCompatActivity { // creating variables for strings,text view, image views and button. String title, subtitle, publisher, publishedDate, description, thumbnail, previewLink, infoLink, buyLink; int pageCount; private ArrayList<String> authors; TextView titleTV, subtitleTV, publisherTV, descTV, pageTV, publishDateTV; Button previewBtn, buyBtn; private ImageView bookIV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_book_details); // initializing our views.. titleTV = findViewById(R.id.idTVTitle); subtitleTV = findViewById(R.id.idTVSubTitle); publisherTV = findViewById(R.id.idTVpublisher); descTV = findViewById(R.id.idTVDescription); pageTV = findViewById(R.id.idTVNoOfPages); publishDateTV = findViewById(R.id.idTVPublishDate); previewBtn = findViewById(R.id.idBtnPreview); buyBtn = findViewById(R.id.idBtnBuy); bookIV = findViewById(R.id.idIVbook); // getting the data which we have passed from our adapter class. title = getIntent().getStringExtra(\"title\"); subtitle = getIntent().getStringExtra(\"subtitle\"); publisher = getIntent().getStringExtra(\"publisher\"); publishedDate = getIntent().getStringExtra(\"publishedDate\"); description = getIntent().getStringExtra(\"description\"); pageCount = getIntent().getIntExtra(\"pageCount\", 0); thumbnail = getIntent().getStringExtra(\"thumbnail\"); previewLink = getIntent().getStringExtra(\"previewLink\"); infoLink = getIntent().getStringExtra(\"infoLink\"); buyLink = getIntent().getStringExtra(\"buyLink\"); // after getting the data we are setting // that data to our text views and image view. titleTV.setText(title); subtitleTV.setText(subtitle); publisherTV.setText(publisher); publishDateTV.setText(\"Published On : \" + publishedDate); descTV.setText(description); pageTV.setText(\"No Of Pages : \" + pageCount); Picasso.get().load(thumbnail).into(bookIV); // adding on click listener for our preview button. previewBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (previewLink.isEmpty()) { // below toast message is displayed when preview link is not present. Toast.makeText(BookDetails.this, \"No preview Link present\", Toast.LENGTH_SHORT).show(); return; } // if the link is present we are opening // that link via an intent. Uri uri = Uri.parse(previewLink); Intent i = new Intent(Intent.ACTION_VIEW, uri); startActivity(i); } }); // initializing on click listener for buy button. buyBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (buyLink.isEmpty()) { // below toast message is displaying when buy link is empty. Toast.makeText(BookDetails.this, \"No buy page present for this book\", Toast.LENGTH_SHORT).show(); return; } // if the link is present we are opening // the link via an intent. Uri uri = Uri.parse(buyLink); Intent i = new Intent(Intent.ACTION_VIEW, uri); startActivity(i); } }); }}", "e": 49859, "s": 45840, "text": null }, { "code": null, "e": 49907, "s": 49859, "text": "Step 9: Working with the MainActivity.java file" }, { "code": null, "e": 50097, "s": 49907, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 50102, "s": 50097, "text": "Java" }, { "code": "import android.os.Bundle;import android.view.View;import android.widget.EditText;import android.widget.ImageButton;import android.widget.ProgressBar;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonObjectRequest;import com.android.volley.toolbox.Volley; import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // creating variables for our request queue, // array list, progressbar, edittext, // image button and our recycler view. private RequestQueue mRequestQueue; private ArrayList<BookInfo> bookInfoArrayList; private ProgressBar progressBar; private EditText searchEdt; private ImageButton searchBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our views. progressBar = findViewById(R.id.idLoadingPB); searchEdt = findViewById(R.id.idEdtSearchBooks); searchBtn = findViewById(R.id.idBtnSearch); // initializing on click listener for our button. searchBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { progressBar.setVisibility(View.VISIBLE); // checking if our edittext field is empty or not. if (searchEdt.getText().toString().isEmpty()) { searchEdt.setError(\"Please enter search query\"); return; } // if the search query is not empty then we are // calling get book info method to load all // the books from the API. getBooksInfo(searchEdt.getText().toString()); } }); } private void getBooksInfo(String query) { // creating a new array list. bookInfoArrayList = new ArrayList<>(); // below line is use to initialize // the variable for our request queue. mRequestQueue = Volley.newRequestQueue(MainActivity.this); // below line is use to clear cache this // will be use when our data is being updated. mRequestQueue.getCache().clear(); // below is the url for getting data from API in json format. String url = \"https://www.googleapis.com/books/v1/volumes?q=\" + query; // below line we are creating a new request queue. RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // below line is use to make json object request inside that we // are passing url, get method and getting json object. . JsonObjectRequest booksObjrequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { progressBar.setVisibility(View.GONE); // inside on response method we are extracting all our json data. try { JSONArray itemsArray = response.getJSONArray(\"items\"); for (int i = 0; i < itemsArray.length(); i++) { JSONObject itemsObj = itemsArray.getJSONObject(i); JSONObject volumeObj = itemsObj.getJSONObject(\"volumeInfo\"); String title = volumeObj.optString(\"title\"); String subtitle = volumeObj.optString(\"subtitle\"); JSONArray authorsArray = volumeObj.getJSONArray(\"authors\"); String publisher = volumeObj.optString(\"publisher\"); String publishedDate = volumeObj.optString(\"publishedDate\"); String description = volumeObj.optString(\"description\"); int pageCount = volumeObj.optInt(\"pageCount\"); JSONObject imageLinks = volumeObj.optJSONObject(\"imageLinks\"); String thumbnail = imageLinks.optString(\"thumbnail\"); String previewLink = volumeObj.optString(\"previewLink\"); String infoLink = volumeObj.optString(\"infoLink\"); JSONObject saleInfoObj = itemsObj.optJSONObject(\"saleInfo\"); String buyLink = saleInfoObj.optString(\"buyLink\"); ArrayList<String> authorsArrayList = new ArrayList<>(); if (authorsArray.length() != 0) { for (int j = 0; j < authorsArray.length(); j++) { authorsArrayList.add(authorsArray.optString(i)); } } // after extracting all the data we are // saving this data in our modal class. BookInfo bookInfo = new BookInfo(title, subtitle, authorsArrayList, publisher, publishedDate, description, pageCount, thumbnail, previewLink, infoLink, buyLink); // below line is use to pass our modal // class in our array list. bookInfoArrayList.add(bookInfo); // below line is use to pass our // array list in adapter class. BookAdapter adapter = new BookAdapter(bookInfoArrayList, MainActivity.this); // below line is use to add linear layout // manager for our recycler view. LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, RecyclerView.VERTICAL, false); RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.idRVBooks); // in below line we are setting layout manager and // adapter to our recycler view. mRecyclerView.setLayoutManager(linearLayoutManager); mRecyclerView.setAdapter(adapter); } } catch (JSONException e) { e.printStackTrace(); // displaying a toast message when we get any error from API Toast.makeText(MainActivity.this, \"No Data Found\" + e, Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // also displaying error message in toast. Toast.makeText(MainActivity.this, \"Error found is \" + error, Toast.LENGTH_SHORT).show(); } }); // at last we are adding our json object // request in our request queue. queue.add(booksObjrequest); }}", "e": 57394, "s": 50102, "text": null }, { "code": null, "e": 57480, "s": 57394, "text": "Check out the project on the below link: https://github.com/ChaitanyaMunje/LibraryApp" }, { "code": null, "e": 57488, "s": 57480, "text": "android" }, { "code": null, "e": 57512, "s": 57488, "text": "Technical Scripter 2020" }, { "code": null, "e": 57520, "s": 57512, "text": "Android" }, { "code": null, "e": 57525, "s": 57520, "text": "Java" }, { "code": null, "e": 57544, "s": 57525, "text": "Technical Scripter" }, { "code": null, "e": 57549, "s": 57544, "text": "Java" }, { "code": null, "e": 57557, "s": 57549, "text": "Android" }, { "code": null, "e": 57655, "s": 57557, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 57693, "s": 57655, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 57732, "s": 57693, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 57782, "s": 57732, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 57824, "s": 57782, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 57875, "s": 57824, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 57890, "s": 57875, "text": "Arrays in Java" }, { "code": null, "e": 57934, "s": 57890, "text": "Split() String method in Java with examples" }, { "code": null, "e": 57956, "s": 57934, "text": "For-each loop in Java" }, { "code": null, "e": 58007, "s": 57956, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
How to add Custom Events in Pygame? - GeeksforGeeks
17 Jun, 2021 In this article, we will see how to add custom events in PyGame. PyGame library can be installed using the below command: pip install pygame Although PyGame comes with a set of events (Eg: KEYDOWN and KEYUP), it allows us to create our own additional custom events according to the requirements of our game. Custom events increase the control and flexibility we have over our game. A custom event is the same as creating a User-defined event. Syntax: <event_name> = pygame.USEREVENT + 1 Example: # Here ADDITION and SUBTRACTION is the event name ADDITION = pygame.USEREVENT + 1 SUBTRACTION = pygame.USEREVENT + 2 Now, how do we publish our custom events once they are created? This can be done in two ways: Using pygame.event.post() method. Using pygame.time.set_timer() method. We can directly post our events using pygame.event.post() method. This method adds our event to the end of the events on the queue. In order to execute this, we need to convert our event to Pygame’s event type inorder to match the attributes of the post method and avoid errors. Syntax: # Step 1 – Convert event into event datatype of pygame ADD_event = pygame.event.Event(event) # Step 2 – Post the event pygame.event.post(ADD_event) # event_name as parameter Broadcasting the event periodically by using PyGame timers. Here, we’ll be using another method to publish the event by using set_timer() function, which takes two parameters, a user event name and time interval in milliseconds. Syntax: # event_name, time in ms pygame.time.set_timer(event, duration) Note: In this, we don’t need to convert the user-defined event into PyGame event datatype. Now to create a plot with custom events firstly the attributes for the screen should be set as per requirement. Then create an event and convert it to PyGame event datatype. Now add code for your operations that will generate a custom event. In the given implementation both of the approaches have been handled. Program : Python3 # Python program to add Custom Eventsimport pygame pygame.init() # Setting up the screen and timerscreen = pygame.display.set_mode((500, 500))timer = pygame.time.Clock() # set titlepygame.display.set_caption('Custom Events') # defining coloursWHITE = (255, 255, 255)RED = (255, 0, 0)GREEN = (0, 255, 0)BLUE = (0, 0, 255) # Keep a track of active variablebg_active_color = WHITEscreen.fill(WHITE) # custom user event to change colorCHANGE_COLOR = pygame.USEREVENT + 1 # custom user event to inflate defalte# boxON_BOX = pygame.USEREVENT + 2 # creating Rectanglebox = pygame.Rect((225, 225, 50, 50))grow = True # posting a event to switch color after # every 500mspygame.time.set_timer(CHANGE_COLOR, 500) running = Truewhile running: # checks which all events are posted # and based on that perform required # operations for event in pygame.event.get(): # switching colours after every # 500ms if event.type == CHANGE_COLOR: if bg_active_color == GREEN: screen.fill(GREEN) bg_active_color = WHITE elif bg_active_color == WHITE: screen.fill(WHITE) bg_active_color = GREEN if event.type == ON_BOX: # to inflate and deflate box if grow: box.inflate_ip(3, 3) grow = box.width < 75 else: box.inflate_ip(-3, -3) grow = box.width < 50 if event.type == pygame.QUIT: # for quitting the program running = False # Posting event when the cursor is on top # of the box if box.collidepoint(pygame.mouse.get_pos()): pygame.event.post(pygame.event.Event(ON_BOX)) # Drawing rectangle on the screen pygame.draw.rect(screen, RED, box) # Updating Screen pygame.display.update() # Setting Frames per Second timer.tick(30) pygame.quit() Output : In the above implementation, we have used the .post() method to inflate/deflate the box when the cursor is on the top of the box and .set_timer() method to switch background color after every 500ms. Picked Python-PyGame Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25581, "s": 25553, "text": "\n17 Jun, 2021" }, { "code": null, "e": 25647, "s": 25581, "text": "In this article, we will see how to add custom events in PyGame. " }, { "code": null, "e": 25704, "s": 25647, "text": "PyGame library can be installed using the below command:" }, { "code": null, "e": 25723, "s": 25704, "text": "pip install pygame" }, { "code": null, "e": 26025, "s": 25723, "text": "Although PyGame comes with a set of events (Eg: KEYDOWN and KEYUP), it allows us to create our own additional custom events according to the requirements of our game. Custom events increase the control and flexibility we have over our game. A custom event is the same as creating a User-defined event." }, { "code": null, "e": 26033, "s": 26025, "text": "Syntax:" }, { "code": null, "e": 26069, "s": 26033, "text": "<event_name> = pygame.USEREVENT + 1" }, { "code": null, "e": 26078, "s": 26069, "text": "Example:" }, { "code": null, "e": 26128, "s": 26078, "text": "# Here ADDITION and SUBTRACTION is the event name" }, { "code": null, "e": 26161, "s": 26128, "text": "ADDITION = pygame.USEREVENT + 1 " }, { "code": null, "e": 26196, "s": 26161, "text": "SUBTRACTION = pygame.USEREVENT + 2" }, { "code": null, "e": 26290, "s": 26196, "text": "Now, how do we publish our custom events once they are created? This can be done in two ways:" }, { "code": null, "e": 26324, "s": 26290, "text": "Using pygame.event.post() method." }, { "code": null, "e": 26362, "s": 26324, "text": "Using pygame.time.set_timer() method." }, { "code": null, "e": 26641, "s": 26362, "text": "We can directly post our events using pygame.event.post() method. This method adds our event to the end of the events on the queue. In order to execute this, we need to convert our event to Pygame’s event type inorder to match the attributes of the post method and avoid errors." }, { "code": null, "e": 26649, "s": 26641, "text": "Syntax:" }, { "code": null, "e": 26705, "s": 26649, "text": "# Step 1 – Convert event into event datatype of pygame " }, { "code": null, "e": 26743, "s": 26705, "text": "ADD_event = pygame.event.Event(event)" }, { "code": null, "e": 26769, "s": 26743, "text": "# Step 2 – Post the event" }, { "code": null, "e": 26827, "s": 26769, "text": "pygame.event.post(ADD_event) # event_name as parameter" }, { "code": null, "e": 27056, "s": 26827, "text": "Broadcasting the event periodically by using PyGame timers. Here, we’ll be using another method to publish the event by using set_timer() function, which takes two parameters, a user event name and time interval in milliseconds." }, { "code": null, "e": 27064, "s": 27056, "text": "Syntax:" }, { "code": null, "e": 27089, "s": 27064, "text": "# event_name, time in ms" }, { "code": null, "e": 27131, "s": 27089, "text": "pygame.time.set_timer(event, duration) " }, { "code": null, "e": 27222, "s": 27131, "text": "Note: In this, we don’t need to convert the user-defined event into PyGame event datatype." }, { "code": null, "e": 27464, "s": 27222, "text": "Now to create a plot with custom events firstly the attributes for the screen should be set as per requirement. Then create an event and convert it to PyGame event datatype. Now add code for your operations that will generate a custom event." }, { "code": null, "e": 27534, "s": 27464, "text": "In the given implementation both of the approaches have been handled." }, { "code": null, "e": 27545, "s": 27534, "text": "Program : " }, { "code": null, "e": 27553, "s": 27545, "text": "Python3" }, { "code": "# Python program to add Custom Eventsimport pygame pygame.init() # Setting up the screen and timerscreen = pygame.display.set_mode((500, 500))timer = pygame.time.Clock() # set titlepygame.display.set_caption('Custom Events') # defining coloursWHITE = (255, 255, 255)RED = (255, 0, 0)GREEN = (0, 255, 0)BLUE = (0, 0, 255) # Keep a track of active variablebg_active_color = WHITEscreen.fill(WHITE) # custom user event to change colorCHANGE_COLOR = pygame.USEREVENT + 1 # custom user event to inflate defalte# boxON_BOX = pygame.USEREVENT + 2 # creating Rectanglebox = pygame.Rect((225, 225, 50, 50))grow = True # posting a event to switch color after # every 500mspygame.time.set_timer(CHANGE_COLOR, 500) running = Truewhile running: # checks which all events are posted # and based on that perform required # operations for event in pygame.event.get(): # switching colours after every # 500ms if event.type == CHANGE_COLOR: if bg_active_color == GREEN: screen.fill(GREEN) bg_active_color = WHITE elif bg_active_color == WHITE: screen.fill(WHITE) bg_active_color = GREEN if event.type == ON_BOX: # to inflate and deflate box if grow: box.inflate_ip(3, 3) grow = box.width < 75 else: box.inflate_ip(-3, -3) grow = box.width < 50 if event.type == pygame.QUIT: # for quitting the program running = False # Posting event when the cursor is on top # of the box if box.collidepoint(pygame.mouse.get_pos()): pygame.event.post(pygame.event.Event(ON_BOX)) # Drawing rectangle on the screen pygame.draw.rect(screen, RED, box) # Updating Screen pygame.display.update() # Setting Frames per Second timer.tick(30) pygame.quit()", "e": 29510, "s": 27553, "text": null }, { "code": null, "e": 29520, "s": 29510, "text": "Output : " }, { "code": null, "e": 29721, "s": 29520, "text": "In the above implementation, we have used the .post() method to inflate/deflate the box when the cursor is on the top of the box and .set_timer() method to switch background color after every 500ms. " }, { "code": null, "e": 29728, "s": 29721, "text": "Picked" }, { "code": null, "e": 29742, "s": 29728, "text": "Python-PyGame" }, { "code": null, "e": 29749, "s": 29742, "text": "Python" }, { "code": null, "e": 29847, "s": 29749, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29879, "s": 29847, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29921, "s": 29879, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29963, "s": 29921, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30019, "s": 29963, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30046, "s": 30019, "text": "Python Classes and Objects" }, { "code": null, "e": 30077, "s": 30046, "text": "Python | os.path.join() method" }, { "code": null, "e": 30116, "s": 30077, "text": "Python | Get unique values from a list" }, { "code": null, "e": 30145, "s": 30116, "text": "Create a directory in Python" }, { "code": null, "e": 30167, "s": 30145, "text": "Defaultdict in Python" } ]
Program to Print Pyramid Pattern using numbers - GeeksforGeeks
22 Apr, 2021 Given a number N denoting the number of rows. The task is to print the zigzag pattern with N rows as shown in the below examples.Examples: Input : 2 Output : 1 2 3 Input : 5 Output : 1 2 6 3 7 10 4 8 11 13 5 9 12 14 15 Approach: 1. Use a for loop for printing the number of rows. 2. Use two for loops for printing space and pattern. 3. Calculate starting value for each row with variable t.Below is the implementation of above approach: C++ C Java Python3 C# PHP Javascript // C++ Program to print pyramid// pattern using numbers#include <iostream>using namespace std;// Function to print pyramid patternclass gfg{ public : void printPattern(int n) { int t; // outer loop to print rows for (int i = 1; i <= n; i++) { // inner loop to print spaces for (int j = i; j < n; j++) printf("\t"); // calculate initial value t = i; // inner loop to print pattern for (int k = 1; k <= i; k++) { printf("%d\t\t", t); t = t + n - k; } printf("\n"); } }}; // Driver codeint main(){ gfg g; int n = 6; g.printPattern(n); return 0;}//this code is contributed by Soumik // C Program to print pyramid// pattern using numbers#include <stdio.h> // Function to print pyramid patternvoid printPattern(int n){ int t; // outer loop to print rows for (int i = 1; i <= n; i++) { // inner loop to print spaces for (int j = i; j < n; j++) printf("\t"); // calculate initial value t = i; // inner loop to print pattern for (int k = 1; k <= i; k++) { printf("%d\t\t", t); t = t + n - k; } printf("\n"); }} // Driver codeint main(){ int n = 6; printPattern(n); return 0;} // Java Program to print pyramid// pattern using numbersclass GFG{// Function to print pyramid patternstatic void printPattern(int n){ int t; // outer loop to print rows for (int i = 1; i <= n; i++) { // inner loop to print spaces for (int j = i; j < n; j++) System.out.print("\t"); // calculate initial value t = i; // inner loop to print pattern for (int k = 1; k <= i; k++) { System.out.print(t + "\t\t"); t = t + n - k; } System.out.println(); }} // Driver codepublic static void main(String []args){ int n = 6; printPattern(n);}} // This code is contributed by iAyushRaj # Python3 Program to print pyramid# pattern using numbers # Function to print pyramid patterndef printPattern(n): # outer loop to print rows for i in range(1, n + 1): # inner loop to print spaces for j in range(i, n): print("\t", end = "") # calculate initial value t = i # inner loop to print pattern for k in range (1, i + 1): print(t, "\t", "\t", end = "") t = t + n - k print() # Driver coden = 6printPattern(n) # This code is contributed# by iAyushRaj // C# Program to print pyramid// pattern using numbersusing System; class GFG{// Function to print pyramid patternstatic void printPattern(int n){ int t; // outer loop to print rows for (int i = 1; i <= n; i++) { // inner loop to print spaces for (int j = i; j < n; j++) Console.Write("\t"); // calculate initial value t = i; // inner loop to print pattern for (int k = 1; k <= i; k++) { Console.Write(t + "\t\t"); t = t + n - k; } Console.WriteLine(); }} // Driver codepublic static void Main(){ int n = 6; printPattern(n);}} // This code is contributed by iAyushRaj <?php// PHP Program to print pyramid// pattern using numbers // Function to print pyramid patternfunction printPattern($n){ // outer loop to print rows for ($i = 1; $i <= $n; $i++) { // inner loop to print spaces for ($j = $i; $j < $n; $j++) echo "\t"; // calculate initial value $t = $i; // inner loop to print pattern for ($k = 1; $k <= $i; $k++) { echo "$t \t\t"; $t = $t + $n - $k; } echo "\n"; }} // Driver code$n = 6;printPattern($n); // This code is contributed// by iAyushRaj?> <script> // JavaScript Program to print pyramid // pattern using numbers // Function to print pyramid pattern function printPattern(n) { var t; // outer loop to print rows for (var i = 1; i <= n; i++) { // inner loop to print spaces for (var j = i; j < n; j++) document.write(" "); // calculate initial value t = i; // inner loop to print pattern for (var k = 1; k <= i; k++) { document.write(t + " "); t = t + n - k; } document.write("<br>"); } } // Driver code var n = 6; printPattern(n); </script> 1 2 7 3 8 12 4 9 13 16 5 10 14 17 19 6 11 15 18 20 21 iAyushRaj SoumikMondal rdtank pattern-printing Technical Scripter 2018 C Programs Technical Scripter pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File Header files in C/C++ and its uses Program to print ASCII Value of a character How to return multiple values from a function in C or C++? How to Append a Character to a String in C C program to sort an array in ascending order time() function in C C Program to Swap two Numbers Producer Consumer Problem in C Program to find Prime Numbers Between given Interval
[ { "code": null, "e": 25616, "s": 25588, "text": "\n22 Apr, 2021" }, { "code": null, "e": 25757, "s": 25616, "text": "Given a number N denoting the number of rows. The task is to print the zigzag pattern with N rows as shown in the below examples.Examples: " }, { "code": null, "e": 25992, "s": 25757, "text": "Input : 2 \nOutput : 1\n 2 3\n\nInput : 5\nOutput : 1\n 2 6\n 3 7 10\n 4 8 11 13\n 5 9 12 14 15" }, { "code": null, "e": 26212, "s": 25992, "text": "Approach: 1. Use a for loop for printing the number of rows. 2. Use two for loops for printing space and pattern. 3. Calculate starting value for each row with variable t.Below is the implementation of above approach: " }, { "code": null, "e": 26216, "s": 26212, "text": "C++" }, { "code": null, "e": 26218, "s": 26216, "text": "C" }, { "code": null, "e": 26223, "s": 26218, "text": "Java" }, { "code": null, "e": 26231, "s": 26223, "text": "Python3" }, { "code": null, "e": 26234, "s": 26231, "text": "C#" }, { "code": null, "e": 26238, "s": 26234, "text": "PHP" }, { "code": null, "e": 26249, "s": 26238, "text": "Javascript" }, { "code": "// C++ Program to print pyramid// pattern using numbers#include <iostream>using namespace std;// Function to print pyramid patternclass gfg{ public : void printPattern(int n) { int t; // outer loop to print rows for (int i = 1; i <= n; i++) { // inner loop to print spaces for (int j = i; j < n; j++) printf(\"\\t\"); // calculate initial value t = i; // inner loop to print pattern for (int k = 1; k <= i; k++) { printf(\"%d\\t\\t\", t); t = t + n - k; } printf(\"\\n\"); } }}; // Driver codeint main(){ gfg g; int n = 6; g.printPattern(n); return 0;}//this code is contributed by Soumik", "e": 26945, "s": 26249, "text": null }, { "code": "// C Program to print pyramid// pattern using numbers#include <stdio.h> // Function to print pyramid patternvoid printPattern(int n){ int t; // outer loop to print rows for (int i = 1; i <= n; i++) { // inner loop to print spaces for (int j = i; j < n; j++) printf(\"\\t\"); // calculate initial value t = i; // inner loop to print pattern for (int k = 1; k <= i; k++) { printf(\"%d\\t\\t\", t); t = t + n - k; } printf(\"\\n\"); }} // Driver codeint main(){ int n = 6; printPattern(n); return 0;}", "e": 27547, "s": 26945, "text": null }, { "code": "// Java Program to print pyramid// pattern using numbersclass GFG{// Function to print pyramid patternstatic void printPattern(int n){ int t; // outer loop to print rows for (int i = 1; i <= n; i++) { // inner loop to print spaces for (int j = i; j < n; j++) System.out.print(\"\\t\"); // calculate initial value t = i; // inner loop to print pattern for (int k = 1; k <= i; k++) { System.out.print(t + \"\\t\\t\"); t = t + n - k; } System.out.println(); }} // Driver codepublic static void main(String []args){ int n = 6; printPattern(n);}} // This code is contributed by iAyushRaj", "e": 28244, "s": 27547, "text": null }, { "code": "# Python3 Program to print pyramid# pattern using numbers # Function to print pyramid patterndef printPattern(n): # outer loop to print rows for i in range(1, n + 1): # inner loop to print spaces for j in range(i, n): print(\"\\t\", end = \"\") # calculate initial value t = i # inner loop to print pattern for k in range (1, i + 1): print(t, \"\\t\", \"\\t\", end = \"\") t = t + n - k print() # Driver coden = 6printPattern(n) # This code is contributed# by iAyushRaj", "e": 28814, "s": 28244, "text": null }, { "code": "// C# Program to print pyramid// pattern using numbersusing System; class GFG{// Function to print pyramid patternstatic void printPattern(int n){ int t; // outer loop to print rows for (int i = 1; i <= n; i++) { // inner loop to print spaces for (int j = i; j < n; j++) Console.Write(\"\\t\"); // calculate initial value t = i; // inner loop to print pattern for (int k = 1; k <= i; k++) { Console.Write(t + \"\\t\\t\"); t = t + n - k; } Console.WriteLine(); }} // Driver codepublic static void Main(){ int n = 6; printPattern(n);}} // This code is contributed by iAyushRaj", "e": 29503, "s": 28814, "text": null }, { "code": "<?php// PHP Program to print pyramid// pattern using numbers // Function to print pyramid patternfunction printPattern($n){ // outer loop to print rows for ($i = 1; $i <= $n; $i++) { // inner loop to print spaces for ($j = $i; $j < $n; $j++) echo \"\\t\"; // calculate initial value $t = $i; // inner loop to print pattern for ($k = 1; $k <= $i; $k++) { echo \"$t \\t\\t\"; $t = $t + $n - $k; } echo \"\\n\"; }} // Driver code$n = 6;printPattern($n); // This code is contributed// by iAyushRaj?>", "e": 30113, "s": 29503, "text": null }, { "code": "<script> // JavaScript Program to print pyramid // pattern using numbers // Function to print pyramid pattern function printPattern(n) { var t; // outer loop to print rows for (var i = 1; i <= n; i++) { // inner loop to print spaces for (var j = i; j < n; j++) document.write(\" \"); // calculate initial value t = i; // inner loop to print pattern for (var k = 1; k <= i; k++) { document.write(t + \" \"); t = t + n - k; } document.write(\"<br>\"); } } // Driver code var n = 6; printPattern(n); </script>", "e": 30805, "s": 30113, "text": null }, { "code": null, "e": 31065, "s": 30805, "text": " 1 \n 2 7 \n 3 8 12 \n 4 9 13 16 \n 5 10 14 17 19 \n6 11 15 18 20 21" }, { "code": null, "e": 31077, "s": 31067, "text": "iAyushRaj" }, { "code": null, "e": 31090, "s": 31077, "text": "SoumikMondal" }, { "code": null, "e": 31097, "s": 31090, "text": "rdtank" }, { "code": null, "e": 31114, "s": 31097, "text": "pattern-printing" }, { "code": null, "e": 31138, "s": 31114, "text": "Technical Scripter 2018" }, { "code": null, "e": 31149, "s": 31138, "text": "C Programs" }, { "code": null, "e": 31168, "s": 31149, "text": "Technical Scripter" }, { "code": null, "e": 31185, "s": 31168, "text": "pattern-printing" }, { "code": null, "e": 31283, "s": 31185, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31324, "s": 31283, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 31359, "s": 31324, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 31403, "s": 31359, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 31462, "s": 31403, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 31505, "s": 31462, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 31551, "s": 31505, "text": "C program to sort an array in ascending order" }, { "code": null, "e": 31572, "s": 31551, "text": "time() function in C" }, { "code": null, "e": 31602, "s": 31572, "text": "C Program to Swap two Numbers" }, { "code": null, "e": 31633, "s": 31602, "text": "Producer Consumer Problem in C" } ]
Packages in Perl - GeeksforGeeks
11 Feb, 2019 A Perl package is a collection of code which resides in its own namespace. Perl module is a package defined in a file having the same name as that of the package and having extension .pm. Two different modules may contain a variable or a function of the same name. Any variable which is not contained in any package belongs to the main package. Therefore, all the variables being used, belong to the ‘main’ package. With the declaration of additional packages, it is maintained that variables in different packages do not interfere with each other. Example : Calculator.pm package Calculator; # Defining sub-routine for Additionsub addition{ # Initializing Variables a & b $a = $_[0]; $b = $_[1]; # Performing the operation $a = $a + $b; # Function to print the Sum print "\n***Addition is $a";} # Defining sub-routine for Subtractionsub subtraction{ # Initializing Variables a & b $a = $_[0]; $b = $_[1]; # Performing the operation $a = $a - $b; # Function to print the difference print "\n***Subtraction is $a";}1; Here, the name of the file is “Calculator.pm” stored in the directory Calculator. Notice that 1; is written at the end of the code to return a true value to the interpreter. Perl accepts anything which is true instead of 1. Examples: Test.pl #!/usr/bin/perl # Using the Package 'Calculator'use Calculator; print "Enter two numbers to add"; # Defining values to the variables$a = 10;$b = 20; # Subroutine callCalculator::addition($a, $b); print "\nEnter two numbers to subtract"; # Defining values to the variables$a = 30;$b = 10; # Subroutine callCalculator::subtraction($a, $b); Output: Examples: Test_out_package.pl outside Calculator directory #!/usr/bin/perl use GFG::Calculator; # Directory_name::module_name print "Enter two numbers to add"; # Defining values to the variables$a = 10;$b = 20; # Subroutine callCalculator::addition($a, $b); print "\nEnter two numbers to subtract"; # Defining values to the variables$a = 30;$b = 10; # Subroutine callCalculator::subtraction($a, $b); Output: #!/usr/bin/perl package Message; # Variable Creation$username; # Defining subroutinesub Hello{ print "Hello $username\n";}1; Perl file to access the module is as belowExamples: variable.pl #!/usr/bin/perl # Using Message.pm packageuse Message; # Defining value to variable$Message::username = "ABC"; # Subroutine callMessage::Hello(); Output: #!/usr/bin/perl # Predefined BEGIN blockBEGIN{ print "In the begin block\n";} # Predefined END blockEND{ print "In the end block\n";} print "Hello Perl;\n"; Output: In the begin block Hello Perl; In the end block Picked Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | split() Function Perl | push() Function Perl | chomp() Function Perl | grep() Function Perl | substr() function Perl | exists() Function Perl Tutorial - Learn Perl With Examples Perl | Removing leading and trailing white spaces (trim) Use of print() and say() in Perl Perl | length() Function
[ { "code": null, "e": 26525, "s": 26497, "text": "\n11 Feb, 2019" }, { "code": null, "e": 27075, "s": 26525, "text": "A Perl package is a collection of code which resides in its own namespace. Perl module is a package defined in a file having the same name as that of the package and having extension .pm. Two different modules may contain a variable or a function of the same name. Any variable which is not contained in any package belongs to the main package. Therefore, all the variables being used, belong to the ‘main’ package. With the declaration of additional packages, it is maintained that variables in different packages do not interfere with each other. " }, { "code": null, "e": 27099, "s": 27075, "text": "Example : Calculator.pm" }, { "code": "package Calculator; # Defining sub-routine for Additionsub addition{ # Initializing Variables a & b $a = $_[0]; $b = $_[1]; # Performing the operation $a = $a + $b; # Function to print the Sum print \"\\n***Addition is $a\";} # Defining sub-routine for Subtractionsub subtraction{ # Initializing Variables a & b $a = $_[0]; $b = $_[1]; # Performing the operation $a = $a - $b; # Function to print the difference print \"\\n***Subtraction is $a\";}1;", "e": 27611, "s": 27099, "text": null }, { "code": null, "e": 27836, "s": 27611, "text": "Here, the name of the file is “Calculator.pm” stored in the directory Calculator. Notice that 1; is written at the end of the code to return a true value to the interpreter. Perl accepts anything which is true instead of 1. " }, { "code": null, "e": 27854, "s": 27836, "text": "Examples: Test.pl" }, { "code": "#!/usr/bin/perl # Using the Package 'Calculator'use Calculator; print \"Enter two numbers to add\"; # Defining values to the variables$a = 10;$b = 20; # Subroutine callCalculator::addition($a, $b); print \"\\nEnter two numbers to subtract\"; # Defining values to the variables$a = 30;$b = 10; # Subroutine callCalculator::subtraction($a, $b);", "e": 28199, "s": 27854, "text": null }, { "code": null, "e": 28208, "s": 28199, "text": "Output: " }, { "code": null, "e": 28267, "s": 28208, "text": "Examples: Test_out_package.pl outside Calculator directory" }, { "code": "#!/usr/bin/perl use GFG::Calculator; # Directory_name::module_name print \"Enter two numbers to add\"; # Defining values to the variables$a = 10;$b = 20; # Subroutine callCalculator::addition($a, $b); print \"\\nEnter two numbers to subtract\"; # Defining values to the variables$a = 30;$b = 10; # Subroutine callCalculator::subtraction($a, $b);", "e": 28615, "s": 28267, "text": null }, { "code": null, "e": 28624, "s": 28615, "text": "Output: " }, { "code": "#!/usr/bin/perl package Message; # Variable Creation$username; # Defining subroutinesub Hello{ print \"Hello $username\\n\";}1;", "e": 28753, "s": 28624, "text": null }, { "code": null, "e": 28817, "s": 28753, "text": "Perl file to access the module is as belowExamples: variable.pl" }, { "code": "#!/usr/bin/perl # Using Message.pm packageuse Message; # Defining value to variable$Message::username = \"ABC\"; # Subroutine callMessage::Hello();", "e": 28966, "s": 28817, "text": null }, { "code": null, "e": 28975, "s": 28966, "text": "Output: " }, { "code": "#!/usr/bin/perl # Predefined BEGIN blockBEGIN{ print \"In the begin block\\n\";} # Predefined END blockEND{ print \"In the end block\\n\";} print \"Hello Perl;\\n\";", "e": 29141, "s": 28975, "text": null }, { "code": null, "e": 29149, "s": 29141, "text": "Output:" }, { "code": null, "e": 29197, "s": 29149, "text": "In the begin block\nHello Perl;\nIn the end block" }, { "code": null, "e": 29204, "s": 29197, "text": "Picked" }, { "code": null, "e": 29209, "s": 29204, "text": "Perl" }, { "code": null, "e": 29214, "s": 29209, "text": "Perl" }, { "code": null, "e": 29312, "s": 29214, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29336, "s": 29312, "text": "Perl | split() Function" }, { "code": null, "e": 29359, "s": 29336, "text": "Perl | push() Function" }, { "code": null, "e": 29383, "s": 29359, "text": "Perl | chomp() Function" }, { "code": null, "e": 29406, "s": 29383, "text": "Perl | grep() Function" }, { "code": null, "e": 29431, "s": 29406, "text": "Perl | substr() function" }, { "code": null, "e": 29456, "s": 29431, "text": "Perl | exists() Function" }, { "code": null, "e": 29497, "s": 29456, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 29554, "s": 29497, "text": "Perl | Removing leading and trailing white spaces (trim)" }, { "code": null, "e": 29587, "s": 29554, "text": "Use of print() and say() in Perl" } ]
How to display a PySpark DataFrame in table format ? - GeeksforGeeks
27 Jul, 2021 In this article, we are going to display the data of the PySpark dataframe in table format. We are going to use show() function and toPandas function to display the dataframe in the required format. show(): Used to display the dataframe. Syntax: dataframe.show( n, vertical = True, truncate = n) where, dataframe is the input dataframeN is the number of rows to be displayed from the top ,if n is not specified it will print entire rows in the dataframevertical parameter specifies the data in the dataframe displayed in vertical format if it is true, otherwise it will display in horizontal format like a dataframetruncate is a parameter us used to trim the values in the dataframe given as a number to trim dataframe is the input dataframe N is the number of rows to be displayed from the top ,if n is not specified it will print entire rows in the dataframe vertical parameter specifies the data in the dataframe displayed in vertical format if it is true, otherwise it will display in horizontal format like a dataframe truncate is a parameter us used to trim the values in the dataframe given as a number to trim toPanads(): Pandas stand for a panel data structure which is used to represent data in a two-dimensional format like a table. Syntax: dataframe.toPandas() where, dataframe is the input dataframe Let’s create a sample dataframe. Python3 # importing moduleimport pyspark # importing sparksession from# pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving# an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee data with 5 row valuesdata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 2"], ["3", "bobby", "company 3"], ["4", "rohith", "company 2"], ["5", "gnanesh", "company 1"]] # specify column namescolumns = ['Employee ID', 'Employee NAME', 'Company Name'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) print(dataframe) Output: DataFrame[Employee ID: string, Employee NAME: string, Company Name: string] Example 1: Using show() function without parameters. It will result in the entire dataframe as we have. Python3 # Display df using show()dataframe.show() Output: Example 2: Using show() function with n as a parameter, which displays top n rows. Syntax: DataFrame.show(n) Where, n is a row Code: Python3 # show() function to get 2 rowsdataframe.show(2) Output: Example 3: Using show() function with vertical = True as parameter. Display the records in the dataframe vertically. Syntax: DataFrame.show(vertical) vertical can be either true and false. Code: Python3 # display dataframe evrticallydataframe.show(vertical = True) Output: Example 4: Using show() function with truncate as a parameter. Display first one letter in each value of all the columns Python3 # display dataframe with truncatedataframe.show(truncate = 1) Output: Example 5: Using show() with all parameters. Python3 # display dataframe with all parametersdataframe.show(n=3,vertical=True,truncate=2) Output: Example 6: Using toPandas() method, which converts it to Pandas Dataframe which perfectly looks like a table. Python3 # display dataframe by using topandas() functiondataframe.toPandas() Output: gulshankumarar231 Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25421, "s": 25393, "text": "\n27 Jul, 2021" }, { "code": null, "e": 25620, "s": 25421, "text": "In this article, we are going to display the data of the PySpark dataframe in table format. We are going to use show() function and toPandas function to display the dataframe in the required format." }, { "code": null, "e": 25659, "s": 25620, "text": "show(): Used to display the dataframe." }, { "code": null, "e": 25717, "s": 25659, "text": "Syntax: dataframe.show( n, vertical = True, truncate = n)" }, { "code": null, "e": 25724, "s": 25717, "text": "where," }, { "code": null, "e": 26130, "s": 25724, "text": "dataframe is the input dataframeN is the number of rows to be displayed from the top ,if n is not specified it will print entire rows in the dataframevertical parameter specifies the data in the dataframe displayed in vertical format if it is true, otherwise it will display in horizontal format like a dataframetruncate is a parameter us used to trim the values in the dataframe given as a number to trim" }, { "code": null, "e": 26163, "s": 26130, "text": "dataframe is the input dataframe" }, { "code": null, "e": 26282, "s": 26163, "text": "N is the number of rows to be displayed from the top ,if n is not specified it will print entire rows in the dataframe" }, { "code": null, "e": 26445, "s": 26282, "text": "vertical parameter specifies the data in the dataframe displayed in vertical format if it is true, otherwise it will display in horizontal format like a dataframe" }, { "code": null, "e": 26539, "s": 26445, "text": "truncate is a parameter us used to trim the values in the dataframe given as a number to trim" }, { "code": null, "e": 26665, "s": 26539, "text": "toPanads(): Pandas stand for a panel data structure which is used to represent data in a two-dimensional format like a table." }, { "code": null, "e": 26694, "s": 26665, "text": "Syntax: dataframe.toPandas()" }, { "code": null, "e": 26734, "s": 26694, "text": "where, dataframe is the input dataframe" }, { "code": null, "e": 26767, "s": 26734, "text": "Let’s create a sample dataframe." }, { "code": null, "e": 26775, "s": 26767, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from# pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving# an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee data with 5 row valuesdata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 2\"], [\"3\", \"bobby\", \"company 3\"], [\"4\", \"rohith\", \"company 2\"], [\"5\", \"gnanesh\", \"company 1\"]] # specify column namescolumns = ['Employee ID', 'Employee NAME', 'Company Name'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) print(dataframe)", "e": 27423, "s": 26775, "text": null }, { "code": null, "e": 27431, "s": 27423, "text": "Output:" }, { "code": null, "e": 27507, "s": 27431, "text": "DataFrame[Employee ID: string, Employee NAME: string, Company Name: string]" }, { "code": null, "e": 27611, "s": 27507, "text": "Example 1: Using show() function without parameters. It will result in the entire dataframe as we have." }, { "code": null, "e": 27619, "s": 27611, "text": "Python3" }, { "code": "# Display df using show()dataframe.show()", "e": 27661, "s": 27619, "text": null }, { "code": null, "e": 27669, "s": 27661, "text": "Output:" }, { "code": null, "e": 27752, "s": 27669, "text": "Example 2: Using show() function with n as a parameter, which displays top n rows." }, { "code": null, "e": 27778, "s": 27752, "text": "Syntax: DataFrame.show(n)" }, { "code": null, "e": 27796, "s": 27778, "text": "Where, n is a row" }, { "code": null, "e": 27802, "s": 27796, "text": "Code:" }, { "code": null, "e": 27810, "s": 27802, "text": "Python3" }, { "code": "# show() function to get 2 rowsdataframe.show(2)", "e": 27859, "s": 27810, "text": null }, { "code": null, "e": 27867, "s": 27859, "text": "Output:" }, { "code": null, "e": 27878, "s": 27867, "text": "Example 3:" }, { "code": null, "e": 27984, "s": 27878, "text": "Using show() function with vertical = True as parameter. Display the records in the dataframe vertically." }, { "code": null, "e": 28017, "s": 27984, "text": "Syntax: DataFrame.show(vertical)" }, { "code": null, "e": 28056, "s": 28017, "text": "vertical can be either true and false." }, { "code": null, "e": 28062, "s": 28056, "text": "Code:" }, { "code": null, "e": 28070, "s": 28062, "text": "Python3" }, { "code": "# display dataframe evrticallydataframe.show(vertical = True)", "e": 28132, "s": 28070, "text": null }, { "code": null, "e": 28140, "s": 28132, "text": "Output:" }, { "code": null, "e": 28261, "s": 28140, "text": "Example 4: Using show() function with truncate as a parameter. Display first one letter in each value of all the columns" }, { "code": null, "e": 28269, "s": 28261, "text": "Python3" }, { "code": "# display dataframe with truncatedataframe.show(truncate = 1)", "e": 28331, "s": 28269, "text": null }, { "code": null, "e": 28339, "s": 28331, "text": "Output:" }, { "code": null, "e": 28384, "s": 28339, "text": "Example 5: Using show() with all parameters." }, { "code": null, "e": 28392, "s": 28384, "text": "Python3" }, { "code": "# display dataframe with all parametersdataframe.show(n=3,vertical=True,truncate=2)", "e": 28476, "s": 28392, "text": null }, { "code": null, "e": 28484, "s": 28476, "text": "Output:" }, { "code": null, "e": 28594, "s": 28484, "text": "Example 6: Using toPandas() method, which converts it to Pandas Dataframe which perfectly looks like a table." }, { "code": null, "e": 28602, "s": 28594, "text": "Python3" }, { "code": "# display dataframe by using topandas() functiondataframe.toPandas()", "e": 28671, "s": 28602, "text": null }, { "code": null, "e": 28679, "s": 28671, "text": "Output:" }, { "code": null, "e": 28697, "s": 28679, "text": "gulshankumarar231" }, { "code": null, "e": 28704, "s": 28697, "text": "Picked" }, { "code": null, "e": 28719, "s": 28704, "text": "Python-Pyspark" }, { "code": null, "e": 28726, "s": 28719, "text": "Python" }, { "code": null, "e": 28824, "s": 28726, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28842, "s": 28824, "text": "Python Dictionary" }, { "code": null, "e": 28877, "s": 28842, "text": "Read a file line by line in Python" }, { "code": null, "e": 28909, "s": 28877, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28931, "s": 28909, "text": "Enumerate() in Python" }, { "code": null, "e": 28973, "s": 28931, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29003, "s": 28973, "text": "Iterate over a list in Python" }, { "code": null, "e": 29029, "s": 29003, "text": "Python String | replace()" }, { "code": null, "e": 29058, "s": 29029, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29102, "s": 29058, "text": "Reading and Writing to text files in Python" } ]
Perl | File Locking - GeeksforGeeks
26 Jan, 2019 File locking, or locking in general, is just one of the various solutions proposed to deal with problems associated with resource sharing.File locking is a method to preserving the security and integrity of any document. The main motive of file locking is allowing people to commit changes to the document without creating a mess of it. When a file is trying to be changed by two or more users, there could be conflicts that arise. For example, let us consider a file containing the data of a project. The whole project team is allowed to modify the file. There will be a CGI script coded on the web to do the following. $file = "project.docx";$commit = $ENV{'QUERY_INFO'};open(FILE, "$file"); #opening the documentwhile() { if (m/^$commit$/) { print "Change already made\n"; exit; }}close(FILE);push(@newcommit, $commit);open(FILE, ">$file");print ...close(FILE);print "Commit made!";exit; Locking of a file is done at the system level, which means that the actual details of applying the lock is not something a user has to worry about. File locks are introduced to set temporary restrictions on certain files to limit how they can be shared among different processes. Depending on the nature of an operation, we come up with two types of locks. The first type is a shared lock, and another one is an exclusive lock. With respect to files, read access can be shared by multiple processes because read access does not result in any changes to the state of the shared resource. Therefore, a consistent view of the shared resource can be maintained.File locking can be done, in Perl, with the flock command. Syntax: flock [FILEHANDLE], [OPERATION] Here, OPERATION is a numeric value, it can be either 1, 2, 4, or 8.These numeric values have different meaning and are used to perform different operations such as: Perl uses numbers to represent the values: sub LOCK_SH { 1 } ## set as shared locksub LOCK_EX { 2 } ## set as exclusive locksub LOCK_NB { 4 } ## set lock without any blockssub LOCK_UN { 8 } ## unlock the FILEHANDLE SHARED LOCK:A shared lock can be applied when you simply want to read the file, as well as allowing others to read the same file alongside. Shared Lock not only sets a lock, but it checks for the existence of other locks first. This Lock doesn’t cover the existence check for all the locks but only for ‘Exclusive Lock’. If an Exclusive Lock exists, it waits until the lock is removed. After removal, it will get executed as Shared Lock. There might exist multiple Shared Locks at the same time.Syntax:flock(FILE, 1); #from the above code Syntax: flock(FILE, 1); #from the above code EXCLUSIVE LOCKAn exclusive lock is used when the file is to be used among a group of people, and everyone has got the permission to make a change. Only one exclusive lock will be on a file so that only one user/process at a time makes changes. In an exclusive lock, the rule is “I am the only one.” flock() looks for any other types of locks in the script. If found, it will hold on, till all of them have been removed from the script. At the right moment, it will lock the file.Syntax:flock(FILE, 2); #from the above code Syntax: flock(FILE, 2); #from the above code NON-BLOCKING LOCKA non-blocking lock informs the system not to wait for other locks to come off the file. It will return an error message if another lock has been found in the file.Syntax:flock(FILE, 4); #from the above code Syntax: flock(FILE, 4); #from the above code UNBLOCKINGUnblock any specified file- same as the close(FILE) function does.Syntax:flock(FILE, 8); #from the above codeBelow discussed is a problem which explains the use of flock() function: Problem:The major problem with the script explained in the above example is when it opens up the file – project.docx, clearing the first file and making it empty.Imagine Person A, B, C trying to make a commit at almost the same timing.Person A opens the file to check the data. Closes it, and starts to edit the data. (clearing the first file)Meanwhile, Person B opens the file to check/read and notices it is completely empty.That is a Clash! The whole system will be disrupted.Solution:This is where file locking is used. Person A, B, C are willing to make a commit to the document. Person A opens up the file, that moment(shared lock is activated), checks out all the data inside the file and closes it again(unlocking the file).Person A then wishes to commit changed to the file and re-opens the file to make edits( this is when the Exclusive lock comes into action). While person A is making a change to the file, Neither Person B or C can open up the file to read or write.Person A does his work, closes the file (unlocking it).Now if Person B had tried to open the file in the meantime, would have got an error -“File being accessed by some other candidate”.Thus creating no stepping of toes, and maintaining a good flow of work.flock() vs lockf()lockf() function is used to lock parts of a file unlike flock() which locks entire files at once. lockf() can not be used in the perl directly whereas Perl supports the flock system call natively but doesn’t applies on network locks.Perl also supports fcntl() system call which offers the most locking controls in Perl.My Personal Notes arrow_drop_upSave Syntax: flock(FILE, 8); #from the above code Below discussed is a problem which explains the use of flock() function: Problem:The major problem with the script explained in the above example is when it opens up the file – project.docx, clearing the first file and making it empty.Imagine Person A, B, C trying to make a commit at almost the same timing. Person A opens the file to check the data. Closes it, and starts to edit the data. (clearing the first file)Meanwhile, Person B opens the file to check/read and notices it is completely empty. That is a Clash! The whole system will be disrupted. Solution:This is where file locking is used. Person A, B, C are willing to make a commit to the document. Person A opens up the file, that moment(shared lock is activated), checks out all the data inside the file and closes it again(unlocking the file).Person A then wishes to commit changed to the file and re-opens the file to make edits( this is when the Exclusive lock comes into action). While person A is making a change to the file, Neither Person B or C can open up the file to read or write. Person A does his work, closes the file (unlocking it). Now if Person B had tried to open the file in the meantime, would have got an error -“File being accessed by some other candidate”.Thus creating no stepping of toes, and maintaining a good flow of work. perl-basics Picked Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl Tutorial - Learn Perl With Examples Perl | Basic Syntax of a Perl Program Perl | Inheritance in OOPs Perl | Multidimensional Hashes Perl | Opening and Reading a File Perl | ne operator Perl | Scope of Variables Perl | Hashes Perl | defined() Function Perl | Data Types
[ { "code": null, "e": 25339, "s": 25311, "text": "\n26 Jan, 2019" }, { "code": null, "e": 25771, "s": 25339, "text": "File locking, or locking in general, is just one of the various solutions proposed to deal with problems associated with resource sharing.File locking is a method to preserving the security and integrity of any document. The main motive of file locking is allowing people to commit changes to the document without creating a mess of it. When a file is trying to be changed by two or more users, there could be conflicts that arise." }, { "code": null, "e": 25960, "s": 25771, "text": "For example, let us consider a file containing the data of a project. The whole project team is allowed to modify the file. There will be a CGI script coded on the web to do the following." }, { "code": "$file = \"project.docx\";$commit = $ENV{'QUERY_INFO'};open(FILE, \"$file\"); #opening the documentwhile() { if (m/^$commit$/) { print \"Change already made\\n\"; exit; }}close(FILE);push(@newcommit, $commit);open(FILE, \">$file\");print ...close(FILE);print \"Commit made!\";exit;", "e": 26238, "s": 25960, "text": null }, { "code": null, "e": 26954, "s": 26238, "text": "Locking of a file is done at the system level, which means that the actual details of applying the lock is not something a user has to worry about. File locks are introduced to set temporary restrictions on certain files to limit how they can be shared among different processes. Depending on the nature of an operation, we come up with two types of locks. The first type is a shared lock, and another one is an exclusive lock. With respect to files, read access can be shared by multiple processes because read access does not result in any changes to the state of the shared resource. Therefore, a consistent view of the shared resource can be maintained.File locking can be done, in Perl, with the flock command." }, { "code": null, "e": 26962, "s": 26954, "text": "Syntax:" }, { "code": null, "e": 26994, "s": 26962, "text": "flock [FILEHANDLE], [OPERATION]" }, { "code": null, "e": 27159, "s": 26994, "text": "Here, OPERATION is a numeric value, it can be either 1, 2, 4, or 8.These numeric values have different meaning and are used to perform different operations such as:" }, { "code": null, "e": 27202, "s": 27159, "text": "Perl uses numbers to represent the values:" }, { "code": null, "e": 27374, "s": 27202, "text": "sub LOCK_SH { 1 } ## set as shared locksub LOCK_EX { 2 } ## set as exclusive locksub LOCK_NB { 4 } ## set lock without any blockssub LOCK_UN { 8 } ## unlock the FILEHANDLE" }, { "code": null, "e": 27913, "s": 27374, "text": "SHARED LOCK:A shared lock can be applied when you simply want to read the file, as well as allowing others to read the same file alongside. Shared Lock not only sets a lock, but it checks for the existence of other locks first. This Lock doesn’t cover the existence check for all the locks but only for ‘Exclusive Lock’. If an Exclusive Lock exists, it waits until the lock is removed. After removal, it will get executed as Shared Lock. There might exist multiple Shared Locks at the same time.Syntax:flock(FILE, 1); #from the above code" }, { "code": null, "e": 27921, "s": 27913, "text": "Syntax:" }, { "code": null, "e": 27958, "s": 27921, "text": "flock(FILE, 1); #from the above code" }, { "code": null, "e": 28481, "s": 27958, "text": "EXCLUSIVE LOCKAn exclusive lock is used when the file is to be used among a group of people, and everyone has got the permission to make a change. Only one exclusive lock will be on a file so that only one user/process at a time makes changes. In an exclusive lock, the rule is “I am the only one.” flock() looks for any other types of locks in the script. If found, it will hold on, till all of them have been removed from the script. At the right moment, it will lock the file.Syntax:flock(FILE, 2); #from the above code" }, { "code": null, "e": 28489, "s": 28481, "text": "Syntax:" }, { "code": null, "e": 28526, "s": 28489, "text": "flock(FILE, 2); #from the above code" }, { "code": null, "e": 28751, "s": 28526, "text": "NON-BLOCKING LOCKA non-blocking lock informs the system not to wait for other locks to come off the file. It will return an error message if another lock has been found in the file.Syntax:flock(FILE, 4); #from the above code" }, { "code": null, "e": 28759, "s": 28751, "text": "Syntax:" }, { "code": null, "e": 28796, "s": 28759, "text": "flock(FILE, 4); #from the above code" }, { "code": null, "e": 30597, "s": 28796, "text": "UNBLOCKINGUnblock any specified file- same as the close(FILE) function does.Syntax:flock(FILE, 8); #from the above codeBelow discussed is a problem which explains the use of flock() function: Problem:The major problem with the script explained in the above example is when it opens up the file – project.docx, clearing the first file and making it empty.Imagine Person A, B, C trying to make a commit at almost the same timing.Person A opens the file to check the data. Closes it, and starts to edit the data. (clearing the first file)Meanwhile, Person B opens the file to check/read and notices it is completely empty.That is a Clash! The whole system will be disrupted.Solution:This is where file locking is used. Person A, B, C are willing to make a commit to the document. Person A opens up the file, that moment(shared lock is activated), checks out all the data inside the file and closes it again(unlocking the file).Person A then wishes to commit changed to the file and re-opens the file to make edits( this is when the Exclusive lock comes into action). While person A is making a change to the file, Neither Person B or C can open up the file to read or write.Person A does his work, closes the file (unlocking it).Now if Person B had tried to open the file in the meantime, would have got an error -“File being accessed by some other candidate”.Thus creating no stepping of toes, and maintaining a good flow of work.flock() vs lockf()lockf() function is used to lock parts of a file unlike flock() which locks entire files at once. lockf() can not be used in the perl directly whereas Perl supports the flock system call natively but doesn’t applies on network locks.Perl also supports fcntl() system call which offers the most locking controls in Perl.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 30605, "s": 30597, "text": "Syntax:" }, { "code": null, "e": 30642, "s": 30605, "text": "flock(FILE, 8); #from the above code" }, { "code": null, "e": 30951, "s": 30642, "text": "Below discussed is a problem which explains the use of flock() function: Problem:The major problem with the script explained in the above example is when it opens up the file – project.docx, clearing the first file and making it empty.Imagine Person A, B, C trying to make a commit at almost the same timing." }, { "code": null, "e": 31144, "s": 30951, "text": "Person A opens the file to check the data. Closes it, and starts to edit the data. (clearing the first file)Meanwhile, Person B opens the file to check/read and notices it is completely empty." }, { "code": null, "e": 31197, "s": 31144, "text": "That is a Clash! The whole system will be disrupted." }, { "code": null, "e": 31698, "s": 31197, "text": "Solution:This is where file locking is used. Person A, B, C are willing to make a commit to the document. Person A opens up the file, that moment(shared lock is activated), checks out all the data inside the file and closes it again(unlocking the file).Person A then wishes to commit changed to the file and re-opens the file to make edits( this is when the Exclusive lock comes into action). While person A is making a change to the file, Neither Person B or C can open up the file to read or write." }, { "code": null, "e": 31754, "s": 31698, "text": "Person A does his work, closes the file (unlocking it)." }, { "code": null, "e": 31957, "s": 31754, "text": "Now if Person B had tried to open the file in the meantime, would have got an error -“File being accessed by some other candidate”.Thus creating no stepping of toes, and maintaining a good flow of work." }, { "code": null, "e": 31969, "s": 31957, "text": "perl-basics" }, { "code": null, "e": 31976, "s": 31969, "text": "Picked" }, { "code": null, "e": 31981, "s": 31976, "text": "Perl" }, { "code": null, "e": 31986, "s": 31981, "text": "Perl" }, { "code": null, "e": 32084, "s": 31986, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32125, "s": 32084, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 32163, "s": 32125, "text": "Perl | Basic Syntax of a Perl Program" }, { "code": null, "e": 32190, "s": 32163, "text": "Perl | Inheritance in OOPs" }, { "code": null, "e": 32221, "s": 32190, "text": "Perl | Multidimensional Hashes" }, { "code": null, "e": 32255, "s": 32221, "text": "Perl | Opening and Reading a File" }, { "code": null, "e": 32274, "s": 32255, "text": "Perl | ne operator" }, { "code": null, "e": 32300, "s": 32274, "text": "Perl | Scope of Variables" }, { "code": null, "e": 32314, "s": 32300, "text": "Perl | Hashes" }, { "code": null, "e": 32340, "s": 32314, "text": "Perl | defined() Function" } ]
Convert Text file to JSON in Python - GeeksforGeeks
29 Dec, 2020 JSON (JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. This module comes in-built with Python standard modules, so there is no need to install it externally. See the following table given below to see serializing JSON i.e. the process of encoding JSON. To handle the data flow in a file, the JSON library in Python uses dump() function to convert the Python objects into their respective JSON object, so it makes easy to write data to files. Syntax: json.dump() Various parameters can be passed to this method. They help in improving the readability of the JSON file. They are : dict object : the dictionary which holds the key-value pairs. indent : the indentation suitable for readability(a numerical value). separator : How the objects must be separated from each other, how a value must be seperated from its key. The symbols like “, “, “:”, “;”, “.” are used sort_keys : If set to true, then the keys are sorted in ascending order Here the idea is to store the contents of the text as key-value pairs in the dictionary and then dump it into a JSON file. A simple example is explained below. The text file contains a single person’s details. The text1.txt file looks like: Now to convert this to JSON file the code below can be used: # Python program to convert text# file to JSON import json # the file to be converted to # json formatfilename = 'data.txt' # dictionary where the lines from# text will be storeddict1 = {} # creating dictionarywith open(filename) as fh: for line in fh: # reads each line and trims of extra the spaces # and gives only the valid words command, description = line.strip().split(None, 1) dict1[command] = description.strip() # creating json file# the JSON file is named as test1out_file = open("test1.json", "w")json.dump(dict1, out_file, indent = 4, sort_keys = False)out_file.close() When the above code is executed, if a JSON file exists in the given name it is written to it, otherwise, a new file is created in the destination path and the contents are written to it. Output: Note the below line of code: command, description = line.strip().split(None, 1) Here split(None, 1) is used to trim off all excess spaces between a key-value pair and ‘1’ denotes split only once in a line. This ensures in a key-value pair, the spaces in the value are not removed and those words are not split. Only the key is separated from its value. How to convert if multiple records are stored in the text file ?Let us consider the following text file which is an employee record containing 4 rows. The idea is to convert each employee’s detail into an intermediate dictionary and append that to one main resultant dictionary. For each intermediate dictionary a unique id is created and that serves as the key. Thus here the employee id and an intermediate dictionary make a key-value pair for the resultant dictionary to be dumped. # Python program to convert text# file to JSON import json # the file to be convertedfilename = 'data.txt' # resultant dictionarydict1 = {} # fields in the sample file fields =['name', 'designation', 'age', 'salary'] with open(filename) as fh: # count variable for employee id creation l = 1 for line in fh: # reading line by line from the text file description = list( line.strip().split(None, 4)) # for output see below print(description) # for automatic creation of id for each employee sno ='emp'+str(l) # loop variable i = 0 # intermediate dictionary dict2 = {} while i<len(fields): # creating dictionary for each employee dict2[fields[i]]= description[i] i = i + 1 # appending the record of each employee to # the main dictionary dict1[sno]= dict2 l = l + 1 # creating json file out_file = open("test2.json", "w")json.dump(dict1, out_file, indent = 4)out_file.close() The attributes associated with each column is stored in a separate list called ‘fields’. In the above code, Each line is split on the basis of space and converted into a dictionary. Each time the line print(attributes) get executed, it appears as given below. ['Lisa', 'programmer', '34', '54000'] ['Elis', 'Trainee', '24', '40000'] ['Rickson', 'HR', '30', '47000'] ['Kate', 'Manager', '54', '63000'] The JSON file created by this code looks like : nikhiltunk Python json-programs Python-json 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() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25543, "s": 25515, "text": "\n29 Dec, 2020" }, { "code": null, "e": 25943, "s": 25543, "text": "JSON (JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. This module comes in-built with Python standard modules, so there is no need to install it externally." }, { "code": null, "e": 26038, "s": 25943, "text": "See the following table given below to see serializing JSON i.e. the process of encoding JSON." }, { "code": null, "e": 26227, "s": 26038, "text": "To handle the data flow in a file, the JSON library in Python uses dump() function to convert the Python objects into their respective JSON object, so it makes easy to write data to files." }, { "code": null, "e": 26235, "s": 26227, "text": "Syntax:" }, { "code": null, "e": 26247, "s": 26235, "text": "json.dump()" }, { "code": null, "e": 26364, "s": 26247, "text": "Various parameters can be passed to this method. They help in improving the readability of the JSON file. They are :" }, { "code": null, "e": 26426, "s": 26364, "text": "dict object : the dictionary which holds the key-value pairs." }, { "code": null, "e": 26496, "s": 26426, "text": "indent : the indentation suitable for readability(a numerical value)." }, { "code": null, "e": 26649, "s": 26496, "text": "separator : How the objects must be separated from each other, how a value must be seperated from its key. The symbols like “, “, “:”, “;”, “.” are used" }, { "code": null, "e": 26721, "s": 26649, "text": "sort_keys : If set to true, then the keys are sorted in ascending order" }, { "code": null, "e": 26962, "s": 26721, "text": "Here the idea is to store the contents of the text as key-value pairs in the dictionary and then dump it into a JSON file. A simple example is explained below. The text file contains a single person’s details. The text1.txt file looks like:" }, { "code": null, "e": 27023, "s": 26962, "text": "Now to convert this to JSON file the code below can be used:" }, { "code": "# Python program to convert text# file to JSON import json # the file to be converted to # json formatfilename = 'data.txt' # dictionary where the lines from# text will be storeddict1 = {} # creating dictionarywith open(filename) as fh: for line in fh: # reads each line and trims of extra the spaces # and gives only the valid words command, description = line.strip().split(None, 1) dict1[command] = description.strip() # creating json file# the JSON file is named as test1out_file = open(\"test1.json\", \"w\")json.dump(dict1, out_file, indent = 4, sort_keys = False)out_file.close()", "e": 27653, "s": 27023, "text": null }, { "code": null, "e": 27840, "s": 27653, "text": "When the above code is executed, if a JSON file exists in the given name it is written to it, otherwise, a new file is created in the destination path and the contents are written to it." }, { "code": null, "e": 27848, "s": 27840, "text": "Output:" }, { "code": null, "e": 27877, "s": 27848, "text": "Note the below line of code:" }, { "code": null, "e": 27928, "s": 27877, "text": "command, description = line.strip().split(None, 1)" }, { "code": null, "e": 28201, "s": 27928, "text": "Here split(None, 1) is used to trim off all excess spaces between a key-value pair and ‘1’ denotes split only once in a line. This ensures in a key-value pair, the spaces in the value are not removed and those words are not split. Only the key is separated from its value." }, { "code": null, "e": 28352, "s": 28201, "text": "How to convert if multiple records are stored in the text file ?Let us consider the following text file which is an employee record containing 4 rows." }, { "code": null, "e": 28686, "s": 28352, "text": "The idea is to convert each employee’s detail into an intermediate dictionary and append that to one main resultant dictionary. For each intermediate dictionary a unique id is created and that serves as the key. Thus here the employee id and an intermediate dictionary make a key-value pair for the resultant dictionary to be dumped." }, { "code": "# Python program to convert text# file to JSON import json # the file to be convertedfilename = 'data.txt' # resultant dictionarydict1 = {} # fields in the sample file fields =['name', 'designation', 'age', 'salary'] with open(filename) as fh: # count variable for employee id creation l = 1 for line in fh: # reading line by line from the text file description = list( line.strip().split(None, 4)) # for output see below print(description) # for automatic creation of id for each employee sno ='emp'+str(l) # loop variable i = 0 # intermediate dictionary dict2 = {} while i<len(fields): # creating dictionary for each employee dict2[fields[i]]= description[i] i = i + 1 # appending the record of each employee to # the main dictionary dict1[sno]= dict2 l = l + 1 # creating json file out_file = open(\"test2.json\", \"w\")json.dump(dict1, out_file, indent = 4)out_file.close()", "e": 29827, "s": 28686, "text": null }, { "code": null, "e": 30087, "s": 29827, "text": "The attributes associated with each column is stored in a separate list called ‘fields’. In the above code, Each line is split on the basis of space and converted into a dictionary. Each time the line print(attributes) get executed, it appears as given below." }, { "code": null, "e": 30229, "s": 30087, "text": "['Lisa', 'programmer', '34', '54000']\n['Elis', 'Trainee', '24', '40000']\n['Rickson', 'HR', '30', '47000']\n['Kate', 'Manager', '54', '63000']\n" }, { "code": null, "e": 30277, "s": 30229, "text": "The JSON file created by this code looks like :" }, { "code": null, "e": 30288, "s": 30277, "text": "nikhiltunk" }, { "code": null, "e": 30309, "s": 30288, "text": "Python json-programs" }, { "code": null, "e": 30321, "s": 30309, "text": "Python-json" }, { "code": null, "e": 30328, "s": 30321, "text": "Python" }, { "code": null, "e": 30347, "s": 30328, "text": "Technical Scripter" }, { "code": null, "e": 30445, "s": 30347, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30463, "s": 30445, "text": "Python Dictionary" }, { "code": null, "e": 30498, "s": 30463, "text": "Read a file line by line in Python" }, { "code": null, "e": 30530, "s": 30498, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30552, "s": 30530, "text": "Enumerate() in Python" }, { "code": null, "e": 30594, "s": 30552, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30624, "s": 30594, "text": "Iterate over a list in Python" }, { "code": null, "e": 30650, "s": 30624, "text": "Python String | replace()" }, { "code": null, "e": 30679, "s": 30650, "text": "*args and **kwargs in Python" }, { "code": null, "e": 30723, "s": 30679, "text": "Reading and Writing to text files in Python" } ]
CSS Styling Images - GeeksforGeeks
11 Oct, 2021 Styling images in CSS works exactly the same way as styling any element using the Box Model of padding, borders, and margins for the content. There are many ways to set style in images which are listed below: Thumbnail images Rounded images Responsive Images Transparent Image Center an Image We will discuss all the ways for styling the image sequentially & will also understand them through the examples. Thumbnail images: The border property is used to create thumbnail images. Example: This example illustrates the use of the Styling image property for creating the thumbnail images. HTML <!DOCTYPE html><html><head> <title>Thumbnail image</title> <style> img { border: 1px solid black; border-radius: 5px; padding: 5px; } </style></head> <body> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png" alt="thumbnail-image" style="width:400px"></body></html> Output: Border-radius Property: The border-radius property is used to set the radius of border-image. This property can contain one, two, three, or four values. It is the combination of four properties: border-top-left-radius, border-top-right-radius, border-bottom-left-radius, border-bottom-right-radius. Example: This example illustrates the use of the Styling image property for creating rounded images. HTML <!DOCTYPE html><html><head> <style> img { border-radius: 50%; } </style></head> <body> <img src="https://media.geeksforgeeks.org/wp-content/uploads/forkandgeeksclassesV-min.png" alt="rounded-image" width="400" height="400"></body></html> Output: Responsive Images: The responsive image is used to adjust the image automatically to the specified box. Example: This example illustrates the use of the Styling image property for creating responsive images. HTML <!DOCTYPE html><html><head> <style> img { max-width: 100%; height: auto; } </style></head> <body> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png" alt="Responsive-image" width="1000" height="300"></body></html> Output: Transparent Image: The opacity property is used to set the image transparent. The opacity value lies between 0.0 to 1.0. Example: This example illustrates the use of the Styling image property for creating transparent images. HTML <!DOCTYPE html><html><head> <title>style image</title> <style> img { opacity: 0.5; } </style></head> <body> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png" alt="Transparent-image" width="100%"></body></html> Output: Center an Image: The images can be centered to box by using left-margin and right-margin properties. Example: This example illustrates the use of the Styling image property for positioning the image to the center. HTML <!DOCTYPE html><html><head> <title>style image</title> <style> img { display: block; margin-left: auto; margin-right: auto; } </style></head> <body> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png" alt="centered-image" style="width:50%"></body></html> Output: Supported Browsers: The browsers supported by Styling Images are listed below: Google Chrome Internet Explorer Microsoft Edge Firefox Opera Safari nidhi_biet bhaskargeeksforgeeks CSS-Properties Picked Technical Scripter 2018 CSS Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? 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": 24917, "s": 24889, "text": "\n11 Oct, 2021" }, { "code": null, "e": 25126, "s": 24917, "text": "Styling images in CSS works exactly the same way as styling any element using the Box Model of padding, borders, and margins for the content. There are many ways to set style in images which are listed below:" }, { "code": null, "e": 25143, "s": 25126, "text": "Thumbnail images" }, { "code": null, "e": 25158, "s": 25143, "text": "Rounded images" }, { "code": null, "e": 25176, "s": 25158, "text": "Responsive Images" }, { "code": null, "e": 25194, "s": 25176, "text": "Transparent Image" }, { "code": null, "e": 25210, "s": 25194, "text": "Center an Image" }, { "code": null, "e": 25324, "s": 25210, "text": "We will discuss all the ways for styling the image sequentially & will also understand them through the examples." }, { "code": null, "e": 25398, "s": 25324, "text": "Thumbnail images: The border property is used to create thumbnail images." }, { "code": null, "e": 25505, "s": 25398, "text": "Example: This example illustrates the use of the Styling image property for creating the thumbnail images." }, { "code": null, "e": 25510, "s": 25505, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>Thumbnail image</title> <style> img { border: 1px solid black; border-radius: 5px; padding: 5px; } </style></head> <body> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\" alt=\"thumbnail-image\" style=\"width:400px\"></body></html>", "e": 25856, "s": 25510, "text": null }, { "code": null, "e": 25864, "s": 25856, "text": "Output:" }, { "code": null, "e": 26164, "s": 25864, "text": "Border-radius Property: The border-radius property is used to set the radius of border-image. This property can contain one, two, three, or four values. It is the combination of four properties: border-top-left-radius, border-top-right-radius, border-bottom-left-radius, border-bottom-right-radius. " }, { "code": null, "e": 26265, "s": 26164, "text": "Example: This example illustrates the use of the Styling image property for creating rounded images." }, { "code": null, "e": 26270, "s": 26265, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <style> img { border-radius: 50%; } </style></head> <body> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/forkandgeeksclassesV-min.png\" alt=\"rounded-image\" width=\"400\" height=\"400\"></body></html>", "e": 26554, "s": 26270, "text": null }, { "code": null, "e": 26562, "s": 26554, "text": "Output:" }, { "code": null, "e": 26666, "s": 26562, "text": "Responsive Images: The responsive image is used to adjust the image automatically to the specified box." }, { "code": null, "e": 26770, "s": 26666, "text": "Example: This example illustrates the use of the Styling image property for creating responsive images." }, { "code": null, "e": 26775, "s": 26770, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <style> img { max-width: 100%; height: auto; } </style></head> <body> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\" alt=\"Responsive-image\" width=\"1000\" height=\"300\"></body></html>", "e": 27073, "s": 26775, "text": null }, { "code": null, "e": 27081, "s": 27073, "text": "Output:" }, { "code": null, "e": 27202, "s": 27081, "text": "Transparent Image: The opacity property is used to set the image transparent. The opacity value lies between 0.0 to 1.0." }, { "code": null, "e": 27307, "s": 27202, "text": "Example: This example illustrates the use of the Styling image property for creating transparent images." }, { "code": null, "e": 27312, "s": 27307, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>style image</title> <style> img { opacity: 0.5; } </style></head> <body> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\" alt=\"Transparent-image\" width=\"100%\"></body></html>", "e": 27596, "s": 27312, "text": null }, { "code": null, "e": 27605, "s": 27596, "text": "Output: " }, { "code": null, "e": 27706, "s": 27605, "text": "Center an Image: The images can be centered to box by using left-margin and right-margin properties." }, { "code": null, "e": 27819, "s": 27706, "text": "Example: This example illustrates the use of the Styling image property for positioning the image to the center." }, { "code": null, "e": 27824, "s": 27819, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>style image</title> <style> img { display: block; margin-left: auto; margin-right: auto; } </style></head> <body> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\" alt=\"centered-image\" style=\"width:50%\"></body></html>", "e": 28156, "s": 27824, "text": null }, { "code": null, "e": 28164, "s": 28156, "text": "Output:" }, { "code": null, "e": 28244, "s": 28164, "text": "Supported Browsers: The browsers supported by Styling Images are listed below: " }, { "code": null, "e": 28258, "s": 28244, "text": "Google Chrome" }, { "code": null, "e": 28276, "s": 28258, "text": "Internet Explorer" }, { "code": null, "e": 28291, "s": 28276, "text": "Microsoft Edge" }, { "code": null, "e": 28299, "s": 28291, "text": "Firefox" }, { "code": null, "e": 28305, "s": 28299, "text": "Opera" }, { "code": null, "e": 28312, "s": 28305, "text": "Safari" }, { "code": null, "e": 28323, "s": 28312, "text": "nidhi_biet" }, { "code": null, "e": 28344, "s": 28323, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 28359, "s": 28344, "text": "CSS-Properties" }, { "code": null, "e": 28366, "s": 28359, "text": "Picked" }, { "code": null, "e": 28390, "s": 28366, "text": "Technical Scripter 2018" }, { "code": null, "e": 28394, "s": 28390, "text": "CSS" }, { "code": null, "e": 28413, "s": 28394, "text": "Technical Scripter" }, { "code": null, "e": 28430, "s": 28413, "text": "Web Technologies" }, { "code": null, "e": 28528, "s": 28430, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28578, "s": 28528, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 28640, "s": 28578, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28688, "s": 28640, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28746, "s": 28688, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 28801, "s": 28746, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 28841, "s": 28801, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28874, "s": 28841, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28919, "s": 28874, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28962, "s": 28919, "text": "How to fetch data from an API in ReactJS ?" } ]
matplotlib.pyplot.prism() in Python - GeeksforGeeks
22 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. The prism() function in pyplot module of matplotlib library is used to set the colormap to “prism”. Syntax: matplotlib.pyplot.prism() Parameters: This method does not accepts any parameter. Returns: This method does not return any value. Below examples illustrate the matplotlib.pyplot.prism() function in matplotlib.pyplot: Example #1: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np ang = 40rad = 10radm = 0.35radii = np.linspace(radm, 0.95, rad) angles = np.linspace(0, 4 * np.pi, ang)angles = np.repeat(angles[..., np.newaxis], rad, axis = 1)angles[:, 1::2] += np.pi / ang x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten()z = (np.sin(4 * radii) * np.cos(4 * angles)).flatten() triang = tri.Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1), y[triang.triangles].mean(axis = 1)) < radm) tpc = plt.tripcolor(triang, z, shading ='flat')plt.colorbar(tpc)plt.prism()plt.title('matplotlib.pyplot.prism() function Example', fontweight ="bold")plt.show() Output: Example #2: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05x = np.arange(-4.0, 4.0, dx)y = np.arange(-4.0, 4.0, dy)X, Y = np.meshgrid(x, y) extent = np.min(x), np.max(x), np.min(y), np.max(y) Z1 = np.add.outer(range(8), range(8)) % 2plt.imshow(Z1, cmap ="binary_r", interpolation ='nearest', extent = extent, alpha = 1) def geeks(x, y): return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2)) Z2 = geeks(X, Y) plt.imshow(Z2, alpha = 0.7, interpolation ='bilinear', extent = extent)plt.prism()plt.title('matplotlib.pyplot.prism() function Example', fontweight ="bold")plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n22 Apr, 2020" }, { "code": null, "e": 25732, "s": 25537, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface." }, { "code": null, "e": 25832, "s": 25732, "text": "The prism() function in pyplot module of matplotlib library is used to set the colormap to “prism”." }, { "code": null, "e": 25840, "s": 25832, "text": "Syntax:" }, { "code": null, "e": 25867, "s": 25840, "text": "matplotlib.pyplot.prism()\n" }, { "code": null, "e": 25923, "s": 25867, "text": "Parameters: This method does not accepts any parameter." }, { "code": null, "e": 25971, "s": 25923, "text": "Returns: This method does not return any value." }, { "code": null, "e": 26058, "s": 25971, "text": "Below examples illustrate the matplotlib.pyplot.prism() function in matplotlib.pyplot:" }, { "code": null, "e": 26070, "s": 26058, "text": "Example #1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np ang = 40rad = 10radm = 0.35radii = np.linspace(radm, 0.95, rad) angles = np.linspace(0, 4 * np.pi, ang)angles = np.repeat(angles[..., np.newaxis], rad, axis = 1)angles[:, 1::2] += np.pi / ang x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten()z = (np.sin(4 * radii) * np.cos(4 * angles)).flatten() triang = tri.Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1), y[triang.triangles].mean(axis = 1)) < radm) tpc = plt.tripcolor(triang, z, shading ='flat')plt.colorbar(tpc)plt.prism()plt.title('matplotlib.pyplot.prism() function Example', fontweight =\"bold\")plt.show()", "e": 26914, "s": 26070, "text": null }, { "code": null, "e": 26922, "s": 26914, "text": "Output:" }, { "code": null, "e": 26934, "s": 26922, "text": "Example #2:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05x = np.arange(-4.0, 4.0, dx)y = np.arange(-4.0, 4.0, dy)X, Y = np.meshgrid(x, y) extent = np.min(x), np.max(x), np.min(y), np.max(y) Z1 = np.add.outer(range(8), range(8)) % 2plt.imshow(Z1, cmap =\"binary_r\", interpolation ='nearest', extent = extent, alpha = 1) def geeks(x, y): return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2)) Z2 = geeks(X, Y) plt.imshow(Z2, alpha = 0.7, interpolation ='bilinear', extent = extent)plt.prism()plt.title('matplotlib.pyplot.prism() function Example', fontweight =\"bold\")plt.show()", "e": 27733, "s": 26934, "text": null }, { "code": null, "e": 27741, "s": 27733, "text": "Output:" }, { "code": null, "e": 27759, "s": 27741, "text": "Python-matplotlib" }, { "code": null, "e": 27766, "s": 27759, "text": "Python" }, { "code": null, "e": 27864, "s": 27766, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27896, "s": 27864, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27938, "s": 27896, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27980, "s": 27938, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28007, "s": 27980, "text": "Python Classes and Objects" }, { "code": null, "e": 28063, "s": 28007, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28085, "s": 28063, "text": "Defaultdict in Python" }, { "code": null, "e": 28124, "s": 28085, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28155, "s": 28124, "text": "Python | os.path.join() method" }, { "code": null, "e": 28184, "s": 28155, "text": "Create a directory in Python" } ]
What is the difference between Array.slice() and Array.splice() in JavaScript ? - GeeksforGeeks
19 Feb, 2020 Javascript arrays are variables that can hold more than one value. There are many methods associated with these arrays. The methods slice() and splice() are widely used methods for array manipulations. There are various differences between them which are listed in the table below. Syntax: slice():array_name.slice(s, e) array_name.slice(s, e) splice():array_name.splice(i, n, item 1, item 2, .....item n) array_name.splice(i, n, item 1, item 2, .....item n) Examples for slice() methodExample 1: Both the start and end are specified. <script> var cars=['Benz', 'Innova', 'Breeza', 'Etios', 'Dzire']; var new_cars=cars.slice(1, 4); document.write("cars :", cars, "<br><br>"); document.write("new_cars :", new_cars);</script> Output: cars :Benz, Innova, Breeza, Etios, Dzire new_cars :Innova, Breeza, Etios Example 2: only the start is specified. The end is by default the length of the array. <script> var cars=['Benz', 'Innova', 'Breeza', 'Etios', 'Dzire']; var new_cars=cars.slice(2); document.write("cars :", cars, "<br><br>"); document.write("new_cars :", new_cars);</script> Output: cars :Benz, Innova, Breeza, Etios, Dzire new_cars :Breeza, Etios, Dzire Examples for splice() methodExample 1: Now let us just add some more items but not remove any item. <script> var cars=['Benz', 'Innova', 'Breeza', 'Etios', 'Dzire']; cars.splice(2, 0, 'ambassedor', 'BMW', 'Audi'); document.write("cars :", cars, "<br><br>");</script> Output: cars :Benz, Innova, ambassedor, BMW, Audi, Breeza, Etios, Dzire Example 2: Removing one element and not adding any new item <script> var cars=['Benz', 'Innova', 'ambassedor', 'BMW', 'Audi', 'Breeza', 'Etios', 'Dzire']; cars.splice(2, 1); document.write("cars :", cars, "<br><br>");</script> Output: cars :Benz, Innova, BMW, Audi, Breeza, Etios, Dzire Example 3: Removing more than one element and not adding any new item. <script> var cars=['Benz', 'Innova', 'ambassedor', 'BMW', 'Audi', 'Breeza', 'Etios', 'Dzire']; cars.splice(2, 3); document.write("cars :", cars, "<br><br>");</script> Output: cars :Benz, Innova, Breeza, Etios, Dzire While removing more than one element, in the above case, the starting index specified is ‘2’ and ‘3-elements’ are required to be removed, so it starts removing elements from the index itself. Thus the items in index 2, 3 and 4 are removed. PHP-function Picked Technical Scripter 2019 JavaScript Technical Scripter 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 Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? 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": 25695, "s": 25667, "text": "\n19 Feb, 2020" }, { "code": null, "e": 25977, "s": 25695, "text": "Javascript arrays are variables that can hold more than one value. There are many methods associated with these arrays. The methods slice() and splice() are widely used methods for array manipulations. There are various differences between them which are listed in the table below." }, { "code": null, "e": 25985, "s": 25977, "text": "Syntax:" }, { "code": null, "e": 26016, "s": 25985, "text": "slice():array_name.slice(s, e)" }, { "code": null, "e": 26039, "s": 26016, "text": "array_name.slice(s, e)" }, { "code": null, "e": 26101, "s": 26039, "text": "splice():array_name.splice(i, n, item 1, item 2, .....item n)" }, { "code": null, "e": 26154, "s": 26101, "text": "array_name.splice(i, n, item 1, item 2, .....item n)" }, { "code": null, "e": 26230, "s": 26154, "text": "Examples for slice() methodExample 1: Both the start and end are specified." }, { "code": "<script> var cars=['Benz', 'Innova', 'Breeza', 'Etios', 'Dzire']; var new_cars=cars.slice(1, 4); document.write(\"cars :\", cars, \"<br><br>\"); document.write(\"new_cars :\", new_cars);</script>", "e": 26433, "s": 26230, "text": null }, { "code": null, "e": 26441, "s": 26433, "text": "Output:" }, { "code": null, "e": 26514, "s": 26441, "text": "cars :Benz, Innova, Breeza, Etios, Dzire\nnew_cars :Innova, Breeza, Etios" }, { "code": null, "e": 26601, "s": 26514, "text": "Example 2: only the start is specified. The end is by default the length of the array." }, { "code": "<script> var cars=['Benz', 'Innova', 'Breeza', 'Etios', 'Dzire']; var new_cars=cars.slice(2); document.write(\"cars :\", cars, \"<br><br>\"); document.write(\"new_cars :\", new_cars);</script>", "e": 26800, "s": 26601, "text": null }, { "code": null, "e": 26808, "s": 26800, "text": "Output:" }, { "code": null, "e": 26881, "s": 26808, "text": "cars :Benz, Innova, Breeza, Etios, Dzire\n\nnew_cars :Breeza, Etios, Dzire" }, { "code": null, "e": 26981, "s": 26881, "text": "Examples for splice() methodExample 1: Now let us just add some more items but not remove any item." }, { "code": "<script> var cars=['Benz', 'Innova', 'Breeza', 'Etios', 'Dzire']; cars.splice(2, 0, 'ambassedor', 'BMW', 'Audi'); document.write(\"cars :\", cars, \"<br><br>\");</script>", "e": 27157, "s": 26981, "text": null }, { "code": null, "e": 27165, "s": 27157, "text": "Output:" }, { "code": null, "e": 27229, "s": 27165, "text": "cars :Benz, Innova, ambassedor, BMW, Audi, Breeza, Etios, Dzire" }, { "code": null, "e": 27289, "s": 27229, "text": "Example 2: Removing one element and not adding any new item" }, { "code": "<script> var cars=['Benz', 'Innova', 'ambassedor', 'BMW', 'Audi', 'Breeza', 'Etios', 'Dzire']; cars.splice(2, 1); document.write(\"cars :\", cars, \"<br><br>\");</script>", "e": 27465, "s": 27289, "text": null }, { "code": null, "e": 27473, "s": 27465, "text": "Output:" }, { "code": null, "e": 27526, "s": 27473, "text": "cars :Benz, Innova, BMW, Audi, Breeza, Etios, Dzire\n" }, { "code": null, "e": 27597, "s": 27526, "text": "Example 3: Removing more than one element and not adding any new item." }, { "code": "<script> var cars=['Benz', 'Innova', 'ambassedor', 'BMW', 'Audi', 'Breeza', 'Etios', 'Dzire']; cars.splice(2, 3); document.write(\"cars :\", cars, \"<br><br>\");</script>", "e": 27773, "s": 27597, "text": null }, { "code": null, "e": 27781, "s": 27773, "text": "Output:" }, { "code": null, "e": 27822, "s": 27781, "text": "cars :Benz, Innova, Breeza, Etios, Dzire" }, { "code": null, "e": 28062, "s": 27822, "text": "While removing more than one element, in the above case, the starting index specified is ‘2’ and ‘3-elements’ are required to be removed, so it starts removing elements from the index itself. Thus the items in index 2, 3 and 4 are removed." }, { "code": null, "e": 28075, "s": 28062, "text": "PHP-function" }, { "code": null, "e": 28082, "s": 28075, "text": "Picked" }, { "code": null, "e": 28106, "s": 28082, "text": "Technical Scripter 2019" }, { "code": null, "e": 28117, "s": 28106, "text": "JavaScript" }, { "code": null, "e": 28136, "s": 28117, "text": "Technical Scripter" }, { "code": null, "e": 28153, "s": 28136, "text": "Web Technologies" }, { "code": null, "e": 28251, "s": 28153, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28291, "s": 28251, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28336, "s": 28291, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28397, "s": 28336, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28469, "s": 28397, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28515, "s": 28469, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 28555, "s": 28515, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28588, "s": 28555, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28633, "s": 28588, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28676, "s": 28633, "text": "How to fetch data from an API in ReactJS ?" } ]
Find two numbers from their sum and XOR - GeeksforGeeks
09 Nov, 2020 Given the sum and xor of two numbers X and Y s.t. sum and xor , we need to find the numbers minimizing the value of X. Examples : Input : S = 17 X = 13 Output : a = 2 b = 15 Input : S = 1870807699 X = 259801747 Output : a = 805502976 b = 1065304723 Input : S = 1639 X = 1176 Output : No such numbers exist Variables Used:X ==> XOR of two numbersS ==> Sum of two numbersX[i] ==> Value of i-th bit in XS[i] ==> Value of i-th bit in S A simple solution is to generate all possible pairs with given XOR. To generate all pairs, we can follow below rules. If X[i] is 1, then both a[i] and b[i] should be different, we have two cases.If X[i] is 0, then both a[i] and b[i] should be same. we have two cases.So we generate 2^n possible pairs where n is number of bits in X. Then for every pair, we check if its sum is S or not.An efficient solution is based on below fact.S = X + 2*Awhere A = a AND bWe can verify above fact using the sum process. In sum, whenever we see both bits 1 (i.e., AND is 1), we make resultant bit 0 and add 1 as carry, which means every bit in AND is left shifted by 1 OR value of AND is multiplied by 2 and added.So we can find A = (S – X)/2.Once we find A, we can find all bits of ‘a’ and ‘b’ using below rules.If X[i] = 0 and A[i] = 0, then a[i] = b[i] = 0. Only one possibility for this bit.If X[i] = 0 and A[i] = 1, then a[i] = b[i] = 1. Only one possibility for this bit.If X[i] = 1 and A[i] = 0, then (a[i] = 1 and b[i] = 0) or (a[i] = 0 and b[i] = 1), we can pick any of the two.If X[i] = 1 and A[i] = 1, result not possible (Note X[i] = 1 means different bits)Let the summation be S and XOR be X.Below is the implementation of above approach:C++JavaPython3C#C++// CPP program to find two numbers with// given Sum and XOR such that value of// first number is minimum.#include <iostream>using namespace std; // Function that takes in the sum and XOR// of two numbers and generates the two // numbers such that the value of X is// minimizedvoid compute(unsigned long int S, unsigned long int X){ unsigned long int A = (S - X)/2; int a = 0, b = 0; // Traverse through all bits for (int i=0; i<8*sizeof(S); i++) { unsigned long int Xi = (X & (1 << i)); unsigned long int Ai = (A & (1 << i)); if (Xi == 0 && Ai == 0) { // Let us leave bits as 0. } else if (Xi == 0 && Ai > 0) { a = ((1 << i) | a); b = ((1 << i) | b); } else if (Xi > 0 && Ai == 0) { a = ((1 << i) | a); // We leave i-th bit of b as 0. } else // (Xi == 1 && Ai == 1) { cout << "Not Possible"; return; } } cout << "a = " << a << endl << "b = " << b;} // Driver functionint main(){ unsigned long int S = 17, X = 13; compute(S, X); return 0;}Java// Java program to find two numbers with // given Sum and XOR such that value of // first number is minimum. class GFG { // Function that takes in the sum and XOR // of two numbers and generates the two // numbers such that the value of X is // minimized static void compute(long S, long X) { long A = (S - X)/2; int a = 0, b = 0; final int LONG_FIELD_SIZE = 8; // Traverse through all bits for (int i=0; i<8*LONG_FIELD_SIZE; i++) { long Xi = (X & (1 << i)); long Ai = (A & (1 << i)); if (Xi == 0 && Ai == 0) { // Let us leave bits as 0. } else if (Xi == 0 && Ai > 0) { a = ((1 << i) | a); b = ((1 << i) | b); } else if (Xi > 0 && Ai == 0) { a = ((1 << i) | a); // We leave i-th bit of b as 0. } else // (Xi == 1 && Ai == 1) { System.out.println("Not Possible"); return; } } System.out.println("a = " + a +"\nb = " + b); } // Driver function public static void main(String[] args) { long S = 17, X = 13; compute(S, X); }}// This code is contributed by RAJPUT-JIPython3# Python program to find two numbers with# given Sum and XOR such that value of# first number is minimum. # Function that takes in the sum and XOR# of two numbers and generates the two # numbers such that the value of X is# minimizeddef compute(S, X): A = (S - X)//2 a = 0 b = 0 # Traverse through all bits for i in range(64): Xi = (X & (1 << i)) Ai = (A & (1 << i)) if (Xi == 0 and Ai == 0): # Let us leave bits as 0. pass elif (Xi == 0 and Ai > 0): a = ((1 << i) | a) b = ((1 << i) | b) elif (Xi > 0 and Ai == 0): a = ((1 << i) | a) # We leave i-th bit of b as 0. else: # (Xi == 1 and Ai == 1) print("Not Possible") return print("a = ",a) print("b =", b) # Driver functionS = 17X = 13compute(S, X) # This code is contributed by ankush_953C#// C# program to find two numbers with // given Sum and XOR such that value of // first number is minimum. using System; public class GFG { // Function that takes in the sum and XOR // of two numbers and generates the two // numbers such that the value of X is // minimized static void compute(long S, long X) { long A = (S - X)/2; int a = 0, b = 0; // Traverse through all bits for (int i=0; i<8*sizeof(long); i++) { long Xi = (X & (1 << i)); long Ai = (A & (1 << i)); if (Xi == 0 && Ai == 0) { // Let us leave bits as 0. } else if (Xi == 0 && Ai > 0) { a = ((1 << i) | a); b = ((1 << i) | b); } else if (Xi > 0 && Ai == 0) { a = ((1 << i) | a); // We leave i-th bit of b as 0. } else // (Xi == 1 && Ai == 1) { Console.WriteLine("Not Possible"); return; } } Console.WriteLine("a = " + a +"\nb = " + b); } // Driver function public static void Main() { long S = 17, X = 13; compute(S, X); }}// This code is contributed by RAJPUT-JIOutputa = 15 b = 2 Time complexity of the above approach where b is number of bits in S.YouTubeGeeksforGeeks507K subscribersFind two numbers from their sum and XOR | GeeksforGeeksInfoShoppingTap 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 laterShareCopy linkWatch on0:000:000:00 / 3:45•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=qapfPE5oBwA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>My Personal Notes arrow_drop_upSave If X[i] is 1, then both a[i] and b[i] should be different, we have two cases. If X[i] is 0, then both a[i] and b[i] should be same. we have two cases.So we generate 2^n possible pairs where n is number of bits in X. Then for every pair, we check if its sum is S or not.An efficient solution is based on below fact.S = X + 2*Awhere A = a AND bWe can verify above fact using the sum process. In sum, whenever we see both bits 1 (i.e., AND is 1), we make resultant bit 0 and add 1 as carry, which means every bit in AND is left shifted by 1 OR value of AND is multiplied by 2 and added.So we can find A = (S – X)/2.Once we find A, we can find all bits of ‘a’ and ‘b’ using below rules.If X[i] = 0 and A[i] = 0, then a[i] = b[i] = 0. Only one possibility for this bit.If X[i] = 0 and A[i] = 1, then a[i] = b[i] = 1. Only one possibility for this bit.If X[i] = 1 and A[i] = 0, then (a[i] = 1 and b[i] = 0) or (a[i] = 0 and b[i] = 1), we can pick any of the two.If X[i] = 1 and A[i] = 1, result not possible (Note X[i] = 1 means different bits)Let the summation be S and XOR be X.Below is the implementation of above approach:C++JavaPython3C#C++// CPP program to find two numbers with// given Sum and XOR such that value of// first number is minimum.#include <iostream>using namespace std; // Function that takes in the sum and XOR// of two numbers and generates the two // numbers such that the value of X is// minimizedvoid compute(unsigned long int S, unsigned long int X){ unsigned long int A = (S - X)/2; int a = 0, b = 0; // Traverse through all bits for (int i=0; i<8*sizeof(S); i++) { unsigned long int Xi = (X & (1 << i)); unsigned long int Ai = (A & (1 << i)); if (Xi == 0 && Ai == 0) { // Let us leave bits as 0. } else if (Xi == 0 && Ai > 0) { a = ((1 << i) | a); b = ((1 << i) | b); } else if (Xi > 0 && Ai == 0) { a = ((1 << i) | a); // We leave i-th bit of b as 0. } else // (Xi == 1 && Ai == 1) { cout << "Not Possible"; return; } } cout << "a = " << a << endl << "b = " << b;} // Driver functionint main(){ unsigned long int S = 17, X = 13; compute(S, X); return 0;}Java// Java program to find two numbers with // given Sum and XOR such that value of // first number is minimum. class GFG { // Function that takes in the sum and XOR // of two numbers and generates the two // numbers such that the value of X is // minimized static void compute(long S, long X) { long A = (S - X)/2; int a = 0, b = 0; final int LONG_FIELD_SIZE = 8; // Traverse through all bits for (int i=0; i<8*LONG_FIELD_SIZE; i++) { long Xi = (X & (1 << i)); long Ai = (A & (1 << i)); if (Xi == 0 && Ai == 0) { // Let us leave bits as 0. } else if (Xi == 0 && Ai > 0) { a = ((1 << i) | a); b = ((1 << i) | b); } else if (Xi > 0 && Ai == 0) { a = ((1 << i) | a); // We leave i-th bit of b as 0. } else // (Xi == 1 && Ai == 1) { System.out.println("Not Possible"); return; } } System.out.println("a = " + a +"\nb = " + b); } // Driver function public static void main(String[] args) { long S = 17, X = 13; compute(S, X); }}// This code is contributed by RAJPUT-JIPython3# Python program to find two numbers with# given Sum and XOR such that value of# first number is minimum. # Function that takes in the sum and XOR# of two numbers and generates the two # numbers such that the value of X is# minimizeddef compute(S, X): A = (S - X)//2 a = 0 b = 0 # Traverse through all bits for i in range(64): Xi = (X & (1 << i)) Ai = (A & (1 << i)) if (Xi == 0 and Ai == 0): # Let us leave bits as 0. pass elif (Xi == 0 and Ai > 0): a = ((1 << i) | a) b = ((1 << i) | b) elif (Xi > 0 and Ai == 0): a = ((1 << i) | a) # We leave i-th bit of b as 0. else: # (Xi == 1 and Ai == 1) print("Not Possible") return print("a = ",a) print("b =", b) # Driver functionS = 17X = 13compute(S, X) # This code is contributed by ankush_953C#// C# program to find two numbers with // given Sum and XOR such that value of // first number is minimum. using System; public class GFG { // Function that takes in the sum and XOR // of two numbers and generates the two // numbers such that the value of X is // minimized static void compute(long S, long X) { long A = (S - X)/2; int a = 0, b = 0; // Traverse through all bits for (int i=0; i<8*sizeof(long); i++) { long Xi = (X & (1 << i)); long Ai = (A & (1 << i)); if (Xi == 0 && Ai == 0) { // Let us leave bits as 0. } else if (Xi == 0 && Ai > 0) { a = ((1 << i) | a); b = ((1 << i) | b); } else if (Xi > 0 && Ai == 0) { a = ((1 << i) | a); // We leave i-th bit of b as 0. } else // (Xi == 1 && Ai == 1) { Console.WriteLine("Not Possible"); return; } } Console.WriteLine("a = " + a +"\nb = " + b); } // Driver function public static void Main() { long S = 17, X = 13; compute(S, X); }}// This code is contributed by RAJPUT-JIOutputa = 15 b = 2 Time complexity of the above approach where b is number of bits in S.YouTubeGeeksforGeeks507K subscribersFind two numbers from their sum and XOR | GeeksforGeeksInfoShoppingTap 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 laterShareCopy linkWatch on0:000:000:00 / 3:45•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=qapfPE5oBwA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>My Personal Notes arrow_drop_upSave So we generate 2^n possible pairs where n is number of bits in X. Then for every pair, we check if its sum is S or not. An efficient solution is based on below fact. S = X + 2*Awhere A = a AND b We can verify above fact using the sum process. In sum, whenever we see both bits 1 (i.e., AND is 1), we make resultant bit 0 and add 1 as carry, which means every bit in AND is left shifted by 1 OR value of AND is multiplied by 2 and added. So we can find A = (S – X)/2. Once we find A, we can find all bits of ‘a’ and ‘b’ using below rules. If X[i] = 0 and A[i] = 0, then a[i] = b[i] = 0. Only one possibility for this bit.If X[i] = 0 and A[i] = 1, then a[i] = b[i] = 1. Only one possibility for this bit.If X[i] = 1 and A[i] = 0, then (a[i] = 1 and b[i] = 0) or (a[i] = 0 and b[i] = 1), we can pick any of the two.If X[i] = 1 and A[i] = 1, result not possible (Note X[i] = 1 means different bits) If X[i] = 0 and A[i] = 0, then a[i] = b[i] = 0. Only one possibility for this bit. If X[i] = 0 and A[i] = 1, then a[i] = b[i] = 1. Only one possibility for this bit. If X[i] = 1 and A[i] = 0, then (a[i] = 1 and b[i] = 0) or (a[i] = 0 and b[i] = 1), we can pick any of the two. If X[i] = 1 and A[i] = 1, result not possible (Note X[i] = 1 means different bits) Let the summation be S and XOR be X. Below is the implementation of above approach: C++ Java Python3 C# // CPP program to find two numbers with// given Sum and XOR such that value of// first number is minimum.#include <iostream>using namespace std; // Function that takes in the sum and XOR// of two numbers and generates the two // numbers such that the value of X is// minimizedvoid compute(unsigned long int S, unsigned long int X){ unsigned long int A = (S - X)/2; int a = 0, b = 0; // Traverse through all bits for (int i=0; i<8*sizeof(S); i++) { unsigned long int Xi = (X & (1 << i)); unsigned long int Ai = (A & (1 << i)); if (Xi == 0 && Ai == 0) { // Let us leave bits as 0. } else if (Xi == 0 && Ai > 0) { a = ((1 << i) | a); b = ((1 << i) | b); } else if (Xi > 0 && Ai == 0) { a = ((1 << i) | a); // We leave i-th bit of b as 0. } else // (Xi == 1 && Ai == 1) { cout << "Not Possible"; return; } } cout << "a = " << a << endl << "b = " << b;} // Driver functionint main(){ unsigned long int S = 17, X = 13; compute(S, X); return 0;} // Java program to find two numbers with // given Sum and XOR such that value of // first number is minimum. class GFG { // Function that takes in the sum and XOR // of two numbers and generates the two // numbers such that the value of X is // minimized static void compute(long S, long X) { long A = (S - X)/2; int a = 0, b = 0; final int LONG_FIELD_SIZE = 8; // Traverse through all bits for (int i=0; i<8*LONG_FIELD_SIZE; i++) { long Xi = (X & (1 << i)); long Ai = (A & (1 << i)); if (Xi == 0 && Ai == 0) { // Let us leave bits as 0. } else if (Xi == 0 && Ai > 0) { a = ((1 << i) | a); b = ((1 << i) | b); } else if (Xi > 0 && Ai == 0) { a = ((1 << i) | a); // We leave i-th bit of b as 0. } else // (Xi == 1 && Ai == 1) { System.out.println("Not Possible"); return; } } System.out.println("a = " + a +"\nb = " + b); } // Driver function public static void main(String[] args) { long S = 17, X = 13; compute(S, X); }}// This code is contributed by RAJPUT-JI # Python program to find two numbers with# given Sum and XOR such that value of# first number is minimum. # Function that takes in the sum and XOR# of two numbers and generates the two # numbers such that the value of X is# minimizeddef compute(S, X): A = (S - X)//2 a = 0 b = 0 # Traverse through all bits for i in range(64): Xi = (X & (1 << i)) Ai = (A & (1 << i)) if (Xi == 0 and Ai == 0): # Let us leave bits as 0. pass elif (Xi == 0 and Ai > 0): a = ((1 << i) | a) b = ((1 << i) | b) elif (Xi > 0 and Ai == 0): a = ((1 << i) | a) # We leave i-th bit of b as 0. else: # (Xi == 1 and Ai == 1) print("Not Possible") return print("a = ",a) print("b =", b) # Driver functionS = 17X = 13compute(S, X) # This code is contributed by ankush_953 // C# program to find two numbers with // given Sum and XOR such that value of // first number is minimum. using System; public class GFG { // Function that takes in the sum and XOR // of two numbers and generates the two // numbers such that the value of X is // minimized static void compute(long S, long X) { long A = (S - X)/2; int a = 0, b = 0; // Traverse through all bits for (int i=0; i<8*sizeof(long); i++) { long Xi = (X & (1 << i)); long Ai = (A & (1 << i)); if (Xi == 0 && Ai == 0) { // Let us leave bits as 0. } else if (Xi == 0 && Ai > 0) { a = ((1 << i) | a); b = ((1 << i) | b); } else if (Xi > 0 && Ai == 0) { a = ((1 << i) | a); // We leave i-th bit of b as 0. } else // (Xi == 1 && Ai == 1) { Console.WriteLine("Not Possible"); return; } } Console.WriteLine("a = " + a +"\nb = " + b); } // Driver function public static void Main() { long S = 17, X = 13; compute(S, X); }}// This code is contributed by RAJPUT-JI a = 15 b = 2 Time complexity of the above approach where b is number of bits in S.YouTubeGeeksforGeeks507K subscribersFind two numbers from their sum and XOR | GeeksforGeeksInfoShoppingTap 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 laterShareCopy linkWatch on0:000:000:00 / 3:45•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=qapfPE5oBwA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> jit_t The_king_of_Knight kartik Rajput-Ji ankush_953 Bitwise-XOR Walmart Bit Magic Competitive Programming Walmart Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Little and Big Endian Mystery Cyclic Redundancy Check and Modulo-2 Division Binary representation of a given number Program to find whether a given number is power of 2 Josephus problem | Set 1 (A O(n) Solution) Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Fast I/O for Competitive Programming
[ { "code": null, "e": 26219, "s": 26191, "text": "\n09 Nov, 2020" }, { "code": null, "e": 26338, "s": 26219, "text": "Given the sum and xor of two numbers X and Y s.t. sum and xor , we need to find the numbers minimizing the value of X." }, { "code": null, "e": 26349, "s": 26338, "text": "Examples :" }, { "code": null, "e": 26571, "s": 26349, "text": "Input : S = 17\n X = 13\nOutput : a = 2\n b = 15\n\nInput : S = 1870807699 \n X = 259801747\nOutput : a = 805502976\n b = 1065304723\n\nInput : S = 1639\n X = 1176\nOutput : No such numbers exist\n" }, { "code": null, "e": 26697, "s": 26571, "text": "Variables Used:X ==> XOR of two numbersS ==> Sum of two numbersX[i] ==> Value of i-th bit in XS[i] ==> Value of i-th bit in S" }, { "code": null, "e": 26815, "s": 26697, "text": "A simple solution is to generate all possible pairs with given XOR. To generate all pairs, we can follow below rules." }, { "code": null, "e": 33446, "s": 26815, "text": "If X[i] is 1, then both a[i] and b[i] should be different, we have two cases.If X[i] is 0, then both a[i] and b[i] should be same. we have two cases.So we generate 2^n possible pairs where n is number of bits in X. Then for every pair, we check if its sum is S or not.An efficient solution is based on below fact.S = X + 2*Awhere A = a AND bWe can verify above fact using the sum process. In sum, whenever we see both bits 1 (i.e., AND is 1), we make resultant bit 0 and add 1 as carry, which means every bit in AND is left shifted by 1 OR value of AND is multiplied by 2 and added.So we can find A = (S – X)/2.Once we find A, we can find all bits of ‘a’ and ‘b’ using below rules.If X[i] = 0 and A[i] = 0, then a[i] = b[i] = 0. Only one possibility for this bit.If X[i] = 0 and A[i] = 1, then a[i] = b[i] = 1. Only one possibility for this bit.If X[i] = 1 and A[i] = 0, then (a[i] = 1 and b[i] = 0) or (a[i] = 0 and b[i] = 1), we can pick any of the two.If X[i] = 1 and A[i] = 1, result not possible (Note X[i] = 1 means different bits)Let the summation be S and XOR be X.Below is the implementation of above approach:C++JavaPython3C#C++// CPP program to find two numbers with// given Sum and XOR such that value of// first number is minimum.#include <iostream>using namespace std; // Function that takes in the sum and XOR// of two numbers and generates the two // numbers such that the value of X is// minimizedvoid compute(unsigned long int S, unsigned long int X){ unsigned long int A = (S - X)/2; int a = 0, b = 0; // Traverse through all bits for (int i=0; i<8*sizeof(S); i++) { unsigned long int Xi = (X & (1 << i)); unsigned long int Ai = (A & (1 << i)); if (Xi == 0 && Ai == 0) { // Let us leave bits as 0. } else if (Xi == 0 && Ai > 0) { a = ((1 << i) | a); b = ((1 << i) | b); } else if (Xi > 0 && Ai == 0) { a = ((1 << i) | a); // We leave i-th bit of b as 0. } else // (Xi == 1 && Ai == 1) { cout << \"Not Possible\"; return; } } cout << \"a = \" << a << endl << \"b = \" << b;} // Driver functionint main(){ unsigned long int S = 17, X = 13; compute(S, X); return 0;}Java// Java program to find two numbers with // given Sum and XOR such that value of // first number is minimum. class GFG { // Function that takes in the sum and XOR // of two numbers and generates the two // numbers such that the value of X is // minimized static void compute(long S, long X) { long A = (S - X)/2; int a = 0, b = 0; final int LONG_FIELD_SIZE = 8; // Traverse through all bits for (int i=0; i<8*LONG_FIELD_SIZE; i++) { long Xi = (X & (1 << i)); long Ai = (A & (1 << i)); if (Xi == 0 && Ai == 0) { // Let us leave bits as 0. } else if (Xi == 0 && Ai > 0) { a = ((1 << i) | a); b = ((1 << i) | b); } else if (Xi > 0 && Ai == 0) { a = ((1 << i) | a); // We leave i-th bit of b as 0. } else // (Xi == 1 && Ai == 1) { System.out.println(\"Not Possible\"); return; } } System.out.println(\"a = \" + a +\"\\nb = \" + b); } // Driver function public static void main(String[] args) { long S = 17, X = 13; compute(S, X); }}// This code is contributed by RAJPUT-JIPython3# Python program to find two numbers with# given Sum and XOR such that value of# first number is minimum. # Function that takes in the sum and XOR# of two numbers and generates the two # numbers such that the value of X is# minimizeddef compute(S, X): A = (S - X)//2 a = 0 b = 0 # Traverse through all bits for i in range(64): Xi = (X & (1 << i)) Ai = (A & (1 << i)) if (Xi == 0 and Ai == 0): # Let us leave bits as 0. pass elif (Xi == 0 and Ai > 0): a = ((1 << i) | a) b = ((1 << i) | b) elif (Xi > 0 and Ai == 0): a = ((1 << i) | a) # We leave i-th bit of b as 0. else: # (Xi == 1 and Ai == 1) print(\"Not Possible\") return print(\"a = \",a) print(\"b =\", b) # Driver functionS = 17X = 13compute(S, X) # This code is contributed by ankush_953C#// C# program to find two numbers with // given Sum and XOR such that value of // first number is minimum. using System; public class GFG { // Function that takes in the sum and XOR // of two numbers and generates the two // numbers such that the value of X is // minimized static void compute(long S, long X) { long A = (S - X)/2; int a = 0, b = 0; // Traverse through all bits for (int i=0; i<8*sizeof(long); i++) { long Xi = (X & (1 << i)); long Ai = (A & (1 << i)); if (Xi == 0 && Ai == 0) { // Let us leave bits as 0. } else if (Xi == 0 && Ai > 0) { a = ((1 << i) | a); b = ((1 << i) | b); } else if (Xi > 0 && Ai == 0) { a = ((1 << i) | a); // We leave i-th bit of b as 0. } else // (Xi == 1 && Ai == 1) { Console.WriteLine(\"Not Possible\"); return; } } Console.WriteLine(\"a = \" + a +\"\\nb = \" + b); } // Driver function public static void Main() { long S = 17, X = 13; compute(S, X); }}// This code is contributed by RAJPUT-JIOutputa = 15\nb = 2\nTime complexity of the above approach where b is number of bits in S.YouTubeGeeksforGeeks507K subscribersFind two numbers from their sum and XOR | GeeksforGeeksInfoShoppingTap 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 laterShareCopy linkWatch on0:000:000:00 / 3:45•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=qapfPE5oBwA\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 33524, "s": 33446, "text": "If X[i] is 1, then both a[i] and b[i] should be different, we have two cases." }, { "code": null, "e": 40078, "s": 33524, "text": "If X[i] is 0, then both a[i] and b[i] should be same. we have two cases.So we generate 2^n possible pairs where n is number of bits in X. Then for every pair, we check if its sum is S or not.An efficient solution is based on below fact.S = X + 2*Awhere A = a AND bWe can verify above fact using the sum process. In sum, whenever we see both bits 1 (i.e., AND is 1), we make resultant bit 0 and add 1 as carry, which means every bit in AND is left shifted by 1 OR value of AND is multiplied by 2 and added.So we can find A = (S – X)/2.Once we find A, we can find all bits of ‘a’ and ‘b’ using below rules.If X[i] = 0 and A[i] = 0, then a[i] = b[i] = 0. Only one possibility for this bit.If X[i] = 0 and A[i] = 1, then a[i] = b[i] = 1. Only one possibility for this bit.If X[i] = 1 and A[i] = 0, then (a[i] = 1 and b[i] = 0) or (a[i] = 0 and b[i] = 1), we can pick any of the two.If X[i] = 1 and A[i] = 1, result not possible (Note X[i] = 1 means different bits)Let the summation be S and XOR be X.Below is the implementation of above approach:C++JavaPython3C#C++// CPP program to find two numbers with// given Sum and XOR such that value of// first number is minimum.#include <iostream>using namespace std; // Function that takes in the sum and XOR// of two numbers and generates the two // numbers such that the value of X is// minimizedvoid compute(unsigned long int S, unsigned long int X){ unsigned long int A = (S - X)/2; int a = 0, b = 0; // Traverse through all bits for (int i=0; i<8*sizeof(S); i++) { unsigned long int Xi = (X & (1 << i)); unsigned long int Ai = (A & (1 << i)); if (Xi == 0 && Ai == 0) { // Let us leave bits as 0. } else if (Xi == 0 && Ai > 0) { a = ((1 << i) | a); b = ((1 << i) | b); } else if (Xi > 0 && Ai == 0) { a = ((1 << i) | a); // We leave i-th bit of b as 0. } else // (Xi == 1 && Ai == 1) { cout << \"Not Possible\"; return; } } cout << \"a = \" << a << endl << \"b = \" << b;} // Driver functionint main(){ unsigned long int S = 17, X = 13; compute(S, X); return 0;}Java// Java program to find two numbers with // given Sum and XOR such that value of // first number is minimum. class GFG { // Function that takes in the sum and XOR // of two numbers and generates the two // numbers such that the value of X is // minimized static void compute(long S, long X) { long A = (S - X)/2; int a = 0, b = 0; final int LONG_FIELD_SIZE = 8; // Traverse through all bits for (int i=0; i<8*LONG_FIELD_SIZE; i++) { long Xi = (X & (1 << i)); long Ai = (A & (1 << i)); if (Xi == 0 && Ai == 0) { // Let us leave bits as 0. } else if (Xi == 0 && Ai > 0) { a = ((1 << i) | a); b = ((1 << i) | b); } else if (Xi > 0 && Ai == 0) { a = ((1 << i) | a); // We leave i-th bit of b as 0. } else // (Xi == 1 && Ai == 1) { System.out.println(\"Not Possible\"); return; } } System.out.println(\"a = \" + a +\"\\nb = \" + b); } // Driver function public static void main(String[] args) { long S = 17, X = 13; compute(S, X); }}// This code is contributed by RAJPUT-JIPython3# Python program to find two numbers with# given Sum and XOR such that value of# first number is minimum. # Function that takes in the sum and XOR# of two numbers and generates the two # numbers such that the value of X is# minimizeddef compute(S, X): A = (S - X)//2 a = 0 b = 0 # Traverse through all bits for i in range(64): Xi = (X & (1 << i)) Ai = (A & (1 << i)) if (Xi == 0 and Ai == 0): # Let us leave bits as 0. pass elif (Xi == 0 and Ai > 0): a = ((1 << i) | a) b = ((1 << i) | b) elif (Xi > 0 and Ai == 0): a = ((1 << i) | a) # We leave i-th bit of b as 0. else: # (Xi == 1 and Ai == 1) print(\"Not Possible\") return print(\"a = \",a) print(\"b =\", b) # Driver functionS = 17X = 13compute(S, X) # This code is contributed by ankush_953C#// C# program to find two numbers with // given Sum and XOR such that value of // first number is minimum. using System; public class GFG { // Function that takes in the sum and XOR // of two numbers and generates the two // numbers such that the value of X is // minimized static void compute(long S, long X) { long A = (S - X)/2; int a = 0, b = 0; // Traverse through all bits for (int i=0; i<8*sizeof(long); i++) { long Xi = (X & (1 << i)); long Ai = (A & (1 << i)); if (Xi == 0 && Ai == 0) { // Let us leave bits as 0. } else if (Xi == 0 && Ai > 0) { a = ((1 << i) | a); b = ((1 << i) | b); } else if (Xi > 0 && Ai == 0) { a = ((1 << i) | a); // We leave i-th bit of b as 0. } else // (Xi == 1 && Ai == 1) { Console.WriteLine(\"Not Possible\"); return; } } Console.WriteLine(\"a = \" + a +\"\\nb = \" + b); } // Driver function public static void Main() { long S = 17, X = 13; compute(S, X); }}// This code is contributed by RAJPUT-JIOutputa = 15\nb = 2\nTime complexity of the above approach where b is number of bits in S.YouTubeGeeksforGeeks507K subscribersFind two numbers from their sum and XOR | GeeksforGeeksInfoShoppingTap 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 laterShareCopy linkWatch on0:000:000:00 / 3:45•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=qapfPE5oBwA\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 40198, "s": 40078, "text": "So we generate 2^n possible pairs where n is number of bits in X. Then for every pair, we check if its sum is S or not." }, { "code": null, "e": 40244, "s": 40198, "text": "An efficient solution is based on below fact." }, { "code": null, "e": 40273, "s": 40244, "text": "S = X + 2*Awhere A = a AND b" }, { "code": null, "e": 40515, "s": 40273, "text": "We can verify above fact using the sum process. In sum, whenever we see both bits 1 (i.e., AND is 1), we make resultant bit 0 and add 1 as carry, which means every bit in AND is left shifted by 1 OR value of AND is multiplied by 2 and added." }, { "code": null, "e": 40545, "s": 40515, "text": "So we can find A = (S – X)/2." }, { "code": null, "e": 40616, "s": 40545, "text": "Once we find A, we can find all bits of ‘a’ and ‘b’ using below rules." }, { "code": null, "e": 40973, "s": 40616, "text": "If X[i] = 0 and A[i] = 0, then a[i] = b[i] = 0. Only one possibility for this bit.If X[i] = 0 and A[i] = 1, then a[i] = b[i] = 1. Only one possibility for this bit.If X[i] = 1 and A[i] = 0, then (a[i] = 1 and b[i] = 0) or (a[i] = 0 and b[i] = 1), we can pick any of the two.If X[i] = 1 and A[i] = 1, result not possible (Note X[i] = 1 means different bits)" }, { "code": null, "e": 41056, "s": 40973, "text": "If X[i] = 0 and A[i] = 0, then a[i] = b[i] = 0. Only one possibility for this bit." }, { "code": null, "e": 41139, "s": 41056, "text": "If X[i] = 0 and A[i] = 1, then a[i] = b[i] = 1. Only one possibility for this bit." }, { "code": null, "e": 41250, "s": 41139, "text": "If X[i] = 1 and A[i] = 0, then (a[i] = 1 and b[i] = 0) or (a[i] = 0 and b[i] = 1), we can pick any of the two." }, { "code": null, "e": 41333, "s": 41250, "text": "If X[i] = 1 and A[i] = 1, result not possible (Note X[i] = 1 means different bits)" }, { "code": null, "e": 41370, "s": 41333, "text": "Let the summation be S and XOR be X." }, { "code": null, "e": 41417, "s": 41370, "text": "Below is the implementation of above approach:" }, { "code": null, "e": 41421, "s": 41417, "text": "C++" }, { "code": null, "e": 41426, "s": 41421, "text": "Java" }, { "code": null, "e": 41434, "s": 41426, "text": "Python3" }, { "code": null, "e": 41437, "s": 41434, "text": "C#" }, { "code": "// CPP program to find two numbers with// given Sum and XOR such that value of// first number is minimum.#include <iostream>using namespace std; // Function that takes in the sum and XOR// of two numbers and generates the two // numbers such that the value of X is// minimizedvoid compute(unsigned long int S, unsigned long int X){ unsigned long int A = (S - X)/2; int a = 0, b = 0; // Traverse through all bits for (int i=0; i<8*sizeof(S); i++) { unsigned long int Xi = (X & (1 << i)); unsigned long int Ai = (A & (1 << i)); if (Xi == 0 && Ai == 0) { // Let us leave bits as 0. } else if (Xi == 0 && Ai > 0) { a = ((1 << i) | a); b = ((1 << i) | b); } else if (Xi > 0 && Ai == 0) { a = ((1 << i) | a); // We leave i-th bit of b as 0. } else // (Xi == 1 && Ai == 1) { cout << \"Not Possible\"; return; } } cout << \"a = \" << a << endl << \"b = \" << b;} // Driver functionint main(){ unsigned long int S = 17, X = 13; compute(S, X); return 0;}", "e": 42606, "s": 41437, "text": null }, { "code": "// Java program to find two numbers with // given Sum and XOR such that value of // first number is minimum. class GFG { // Function that takes in the sum and XOR // of two numbers and generates the two // numbers such that the value of X is // minimized static void compute(long S, long X) { long A = (S - X)/2; int a = 0, b = 0; final int LONG_FIELD_SIZE = 8; // Traverse through all bits for (int i=0; i<8*LONG_FIELD_SIZE; i++) { long Xi = (X & (1 << i)); long Ai = (A & (1 << i)); if (Xi == 0 && Ai == 0) { // Let us leave bits as 0. } else if (Xi == 0 && Ai > 0) { a = ((1 << i) | a); b = ((1 << i) | b); } else if (Xi > 0 && Ai == 0) { a = ((1 << i) | a); // We leave i-th bit of b as 0. } else // (Xi == 1 && Ai == 1) { System.out.println(\"Not Possible\"); return; } } System.out.println(\"a = \" + a +\"\\nb = \" + b); } // Driver function public static void main(String[] args) { long S = 17, X = 13; compute(S, X); }}// This code is contributed by RAJPUT-JI", "e": 43834, "s": 42606, "text": null }, { "code": "# Python program to find two numbers with# given Sum and XOR such that value of# first number is minimum. # Function that takes in the sum and XOR# of two numbers and generates the two # numbers such that the value of X is# minimizeddef compute(S, X): A = (S - X)//2 a = 0 b = 0 # Traverse through all bits for i in range(64): Xi = (X & (1 << i)) Ai = (A & (1 << i)) if (Xi == 0 and Ai == 0): # Let us leave bits as 0. pass elif (Xi == 0 and Ai > 0): a = ((1 << i) | a) b = ((1 << i) | b) elif (Xi > 0 and Ai == 0): a = ((1 << i) | a) # We leave i-th bit of b as 0. else: # (Xi == 1 and Ai == 1) print(\"Not Possible\") return print(\"a = \",a) print(\"b =\", b) # Driver functionS = 17X = 13compute(S, X) # This code is contributed by ankush_953", "e": 44766, "s": 43834, "text": null }, { "code": "// C# program to find two numbers with // given Sum and XOR such that value of // first number is minimum. using System; public class GFG { // Function that takes in the sum and XOR // of two numbers and generates the two // numbers such that the value of X is // minimized static void compute(long S, long X) { long A = (S - X)/2; int a = 0, b = 0; // Traverse through all bits for (int i=0; i<8*sizeof(long); i++) { long Xi = (X & (1 << i)); long Ai = (A & (1 << i)); if (Xi == 0 && Ai == 0) { // Let us leave bits as 0. } else if (Xi == 0 && Ai > 0) { a = ((1 << i) | a); b = ((1 << i) | b); } else if (Xi > 0 && Ai == 0) { a = ((1 << i) | a); // We leave i-th bit of b as 0. } else // (Xi == 1 && Ai == 1) { Console.WriteLine(\"Not Possible\"); return; } } Console.WriteLine(\"a = \" + a +\"\\nb = \" + b); } // Driver function public static void Main() { long S = 17, X = 13; compute(S, X); }}// This code is contributed by RAJPUT-JI", "e": 45959, "s": 44766, "text": null }, { "code": null, "e": 45973, "s": 45959, "text": "a = 15\nb = 2\n" }, { "code": null, "e": 46881, "s": 45973, "text": "Time complexity of the above approach where b is number of bits in S.YouTubeGeeksforGeeks507K subscribersFind two numbers from their sum and XOR | GeeksforGeeksInfoShoppingTap 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 laterShareCopy linkWatch on0:000:000:00 / 3:45•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=qapfPE5oBwA\" 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": 46887, "s": 46881, "text": "jit_t" }, { "code": null, "e": 46906, "s": 46887, "text": "The_king_of_Knight" }, { "code": null, "e": 46913, "s": 46906, "text": "kartik" }, { "code": null, "e": 46923, "s": 46913, "text": "Rajput-Ji" }, { "code": null, "e": 46934, "s": 46923, "text": "ankush_953" }, { "code": null, "e": 46946, "s": 46934, "text": "Bitwise-XOR" }, { "code": null, "e": 46954, "s": 46946, "text": "Walmart" }, { "code": null, "e": 46964, "s": 46954, "text": "Bit Magic" }, { "code": null, "e": 46988, "s": 46964, "text": "Competitive Programming" }, { "code": null, "e": 46996, "s": 46988, "text": "Walmart" }, { "code": null, "e": 47006, "s": 46996, "text": "Bit Magic" }, { "code": null, "e": 47104, "s": 47006, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47134, "s": 47104, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 47180, "s": 47134, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 47220, "s": 47180, "text": "Binary representation of a given number" }, { "code": null, "e": 47273, "s": 47220, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 47316, "s": 47273, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 47359, "s": 47316, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 47402, "s": 47359, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 47443, "s": 47402, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 47521, "s": 47443, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
Matplotlib.pyplot.connect() in Python - GeeksforGeeks
03 May, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. This method is used to connect an event with string s to a function. Syntax: matplotlib.pyplot.connect(s, func) Parameters: This method accept the following parameters that are described below:s(str): One of the following events ids:1. ‘button_press_event’2. ‘button_release_event’3. ‘draw_event’4. ‘key_press_event’5. ‘key_release_event’6. ‘motion_notify_event’7. ‘pick_event’8. ‘resize_event’9. ‘scroll_event’10. ‘figure_enter_event’,11. ‘figure_leave_event’,12. ‘axes_enter_event’,13. ‘axes_leave_event’14. ‘close_event’.func(callable): The callback function to be executed, which must have the signature:def func(event: Event) -> Any Returns(cid): A connection id that can be used with FigureCanvasBase.mpl_disconnect. Example 1 : # matplotlib.pyplot.connect()from matplotlib.backend_bases import MouseButtonimport matplotlib.pyplot as pltimport numpy as np t = np.arange(0.0, 1.0, 0.01)s = np.sin(2 * np.pi * t)fig, ax = plt.subplots()ax.plot(t, s) def on_move(event): # get the x and y pixel coords x, y = event.x, event.y if event.inaxes: ax = event.inaxes # the axes instance print('data coords % f % f' % (event.xdata, event.ydata)) def on_click(event): if event.button is MouseButton.LEFT: print('disconnecting callback') plt.disconnect(binding_id) binding_id = plt.connect('motion_notify_event', on_move) plt.connect('button_press_event', on_click) plt.show() Output : Example 2 : from matplotlib.widgets import RectangleSelectorimport numpy as npimport matplotlib.pyplot as plt def line_select_callback(eclick, erelease): # Callback for line selection. # *eclick * and * erelease * # are the press and release events. x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata print("(% 3.2f, % 3.2f) --> (% 3.2f, % 3.2f)" % (x1, y1, x2, y2)) print(" The button you used were: % s % s" % (eclick.button, erelease.button)) def toggle_selector(event): print(' Key pressed.') if event.key in ['Q', 'q'] and toggle_selector.RS.active: print(' RectangleSelector deactivated.') toggle_selector.RS.set_active(False) print(' RectangleSelector activated.') toggle_selector.RS.set_active(True) # make a new plotting rangefig, current_ax = plt.subplots() # If N is large one can seeN = 100000 # improvement by use blitting ! # plt.plot(x, +np.sin(.2 * np.pi * x), # lw = 3.5, c ='b', alpha =.7) # plot somethingx = np.linspace(0.0, 10.0, N)plt.plot(x, +np.cos(.2 * np.pi * x), lw = 3.5, c ='c', alpha =.5)plt.plot(x, -np.sin(.2 * np.pi * x), lw = 3.5, c ='r', alpha =.3) print("\n click --> release") # drawtype is 'box' or 'line' or 'none'toggle_selector.RS = RectangleSelector(current_ax, line_select_callback, drawtype ='box', useblit = True, button =[1, 3], # don't use middle button minspanx = 5, minspany = 5, spancoords ='pixels', interactive = True) plt.connect('key_press_event', toggle_selector)plt.show() Output : Matplotlib Pyplot-class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n03 May, 2020" }, { "code": null, "e": 25732, "s": 25537, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface." }, { "code": null, "e": 25801, "s": 25732, "text": "This method is used to connect an event with string s to a function." }, { "code": null, "e": 25844, "s": 25801, "text": "Syntax: matplotlib.pyplot.connect(s, func)" }, { "code": null, "e": 26370, "s": 25844, "text": "Parameters: This method accept the following parameters that are described below:s(str): One of the following events ids:1. ‘button_press_event’2. ‘button_release_event’3. ‘draw_event’4. ‘key_press_event’5. ‘key_release_event’6. ‘motion_notify_event’7. ‘pick_event’8. ‘resize_event’9. ‘scroll_event’10. ‘figure_enter_event’,11. ‘figure_leave_event’,12. ‘axes_enter_event’,13. ‘axes_leave_event’14. ‘close_event’.func(callable): The callback function to be executed, which must have the signature:def func(event: Event) -> Any" }, { "code": null, "e": 26455, "s": 26370, "text": "Returns(cid): A connection id that can be used with FigureCanvasBase.mpl_disconnect." }, { "code": null, "e": 26467, "s": 26455, "text": "Example 1 :" }, { "code": "# matplotlib.pyplot.connect()from matplotlib.backend_bases import MouseButtonimport matplotlib.pyplot as pltimport numpy as np t = np.arange(0.0, 1.0, 0.01)s = np.sin(2 * np.pi * t)fig, ax = plt.subplots()ax.plot(t, s) def on_move(event): # get the x and y pixel coords x, y = event.x, event.y if event.inaxes: ax = event.inaxes # the axes instance print('data coords % f % f' % (event.xdata, event.ydata)) def on_click(event): if event.button is MouseButton.LEFT: print('disconnecting callback') plt.disconnect(binding_id) binding_id = plt.connect('motion_notify_event', on_move) plt.connect('button_press_event', on_click) plt.show()", "e": 27238, "s": 26467, "text": null }, { "code": null, "e": 27247, "s": 27238, "text": "Output :" }, { "code": null, "e": 27259, "s": 27247, "text": "Example 2 :" }, { "code": "from matplotlib.widgets import RectangleSelectorimport numpy as npimport matplotlib.pyplot as plt def line_select_callback(eclick, erelease): # Callback for line selection. # *eclick * and * erelease * # are the press and release events. x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata print(\"(% 3.2f, % 3.2f) --> (% 3.2f, % 3.2f)\" % (x1, y1, x2, y2)) print(\" The button you used were: % s % s\" % (eclick.button, erelease.button)) def toggle_selector(event): print(' Key pressed.') if event.key in ['Q', 'q'] and toggle_selector.RS.active: print(' RectangleSelector deactivated.') toggle_selector.RS.set_active(False) print(' RectangleSelector activated.') toggle_selector.RS.set_active(True) # make a new plotting rangefig, current_ax = plt.subplots() # If N is large one can seeN = 100000 # improvement by use blitting ! # plt.plot(x, +np.sin(.2 * np.pi * x), # lw = 3.5, c ='b', alpha =.7) # plot somethingx = np.linspace(0.0, 10.0, N)plt.plot(x, +np.cos(.2 * np.pi * x), lw = 3.5, c ='c', alpha =.5)plt.plot(x, -np.sin(.2 * np.pi * x), lw = 3.5, c ='r', alpha =.3) print(\"\\n click --> release\") # drawtype is 'box' or 'line' or 'none'toggle_selector.RS = RectangleSelector(current_ax, line_select_callback, drawtype ='box', useblit = True, button =[1, 3], # don't use middle button minspanx = 5, minspany = 5, spancoords ='pixels', interactive = True) plt.connect('key_press_event', toggle_selector)plt.show()", "e": 29093, "s": 27259, "text": null }, { "code": null, "e": 29102, "s": 29093, "text": "Output :" }, { "code": null, "e": 29126, "s": 29102, "text": "Matplotlib Pyplot-class" }, { "code": null, "e": 29144, "s": 29126, "text": "Python-matplotlib" }, { "code": null, "e": 29151, "s": 29144, "text": "Python" }, { "code": null, "e": 29249, "s": 29151, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29281, "s": 29249, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29323, "s": 29281, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29365, "s": 29323, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29392, "s": 29365, "text": "Python Classes and Objects" }, { "code": null, "e": 29448, "s": 29392, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29470, "s": 29448, "text": "Defaultdict in Python" }, { "code": null, "e": 29509, "s": 29470, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29540, "s": 29509, "text": "Python | os.path.join() method" }, { "code": null, "e": 29569, "s": 29540, "text": "Create a directory in Python" } ]
Flutter - Snackbar - GeeksforGeeks
15 May, 2022 Snackbar is a widget provided by flutter to display a dismissible pop-up message on your application. It is used to show users if certain actions take place in our applications. For example, if the user login process fails due to some reason, so to inform the user to try again we can use snackbar. It pops up on the screen, and it can also perform operations like undoing the action which has taken place. Snackbar displays the informative message for a very short period of time and when the time is completed it disappears on its own. The recommended onscreen time for a snackbar is 5-10s. It is provided in the material package of the flutter libraries. You need to import “package:flutter/material.dart” to use a snackbar. SnackBar({Key key, @required Widget content, Color backgroundColor, double elevation, EdgeInsetsGeometry margin, EdgeInsetsGeometry padding, double width, ShapeBorder shape, SnackBarBehavior behavior, SnackBarAction action, Duration duration: _snackBarDisplayDuration, Animation<double> animation, VoidCallback onVisible}) action: Action to perform based on snackbar.animation: Entry and the exit animation of snackbar.backgroundcolor: Snackbar background color behavior: Behavior and location of snackbar.content: Content of snackbar.duration: The amount of time snackbar should be displayed.elevation: Elevates the snackbar by increasing shadow.margin: Space around snackbar.onVisible: Called the first time that the snackbar is visible within a scaffold.padding: space around content inside snackbar.shape: Shape of snackbar.width: Width of snackbar. action: Action to perform based on snackbar. animation: Entry and the exit animation of snackbar. backgroundcolor: Snackbar background color behavior: Behavior and location of snackbar. content: Content of snackbar. duration: The amount of time snackbar should be displayed. elevation: Elevates the snackbar by increasing shadow. margin: Space around snackbar. onVisible: Called the first time that the snackbar is visible within a scaffold. padding: space around content inside snackbar. shape: Shape of snackbar. width: Width of snackbar. 1. Create a Scaffold Widget: A Snackbar is displayed inside a scaffold widget that is used to create the entire visible screen of your mobile application. It provides the appbar, title, and other properties of the body that all together makes up the widget tree. Scaffold( appBar: AppBar( title: Text(title), backgroundColor: Colors.green, ), ); 2. Create a Snackbar class: Create a stateless widget class that will represent your snackbar and the actions it is performing. Inside this class create a button it may be elevated, raised or flat, and assign a look to it, For Example: color, text, onhover effect etc. Create a final property and return Snackbar to it, that will hold all the actions that are going to be performed when the button is clicked. class snackBarDemo extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: RaisedButton( child: Text('Click Here!'), color: Colors.green, onPressed: () { final snackdemo = SnackBar( content: Text('Hii this is GFG\'s SnackBar'), backgroundColor: Colors.green, elevation: 10, behavior: SnackBarBehavior.floating, margin: EdgeInsets.all(5), ), }), ); } } 3. Display the Snackbar: Use the Scaffold Messenger class to display the information contained by your snackbar. It uses a context provided by the BuilContext argument. Here, snackdemo is the final property that holds the snackbar. Scaffold.of(context).showSnackBar(snackdemo); 4. Call your Class: Finally, Inside the body of the scaffold call the stateless class you created for your snackbar. Scaffold( appBar: AppBar( title: Text(title), backgroundColor: Colors.green, ), body: snackBarDemo(), ); } } File: main.dart Dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { static const header = 'GeeksforGeeks'; @override Widget build(BuildContext context) { return const MaterialApp( title: header, home: MyHomePage(title: header), ); }} class MyHomePage extends StatelessWidget { const MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(title), backgroundColor: Colors.green, ), body: snackBarDemo(), ); }} class snackBarDemo extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: RaisedButton( child: Text('Click Here!'), color: Colors.green, onPressed: () { final snackdemo = SnackBar( content: Text('Hii this is GFG\'s SnackBar'), backgroundColor: Colors.green, elevation: 10, behavior: SnackBarBehavior.floating, margin: EdgeInsets.all(5), ); Scaffold.of(context).showSnackBar(snackdemo); }), ); }} Output: rharshitaaa21 Flutter UI-components Flutter-widgets Android Dart Flutter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Flutter - DropDownButton Widget Listview.builder in Flutter Flutter - Asset Image Splash Screen in Flutter Flutter - Custom Bottom Navigation Bar
[ { "code": null, "e": 26381, "s": 26353, "text": "\n15 May, 2022" }, { "code": null, "e": 27109, "s": 26381, "text": "Snackbar is a widget provided by flutter to display a dismissible pop-up message on your application. It is used to show users if certain actions take place in our applications. For example, if the user login process fails due to some reason, so to inform the user to try again we can use snackbar. It pops up on the screen, and it can also perform operations like undoing the action which has taken place. Snackbar displays the informative message for a very short period of time and when the time is completed it disappears on its own. The recommended onscreen time for a snackbar is 5-10s. It is provided in the material package of the flutter libraries. You need to import “package:flutter/material.dart” to use a snackbar." }, { "code": null, "e": 27444, "s": 27109, "text": "SnackBar({Key key, \n@required Widget content, \nColor backgroundColor, \ndouble elevation, \nEdgeInsetsGeometry margin, \nEdgeInsetsGeometry padding, \ndouble width, \nShapeBorder shape, \nSnackBarBehavior behavior, \nSnackBarAction action, \nDuration duration: _snackBarDisplayDuration, \nAnimation<double> animation, \nVoidCallback onVisible})" }, { "code": null, "e": 27975, "s": 27444, "text": "action: Action to perform based on snackbar.animation: Entry and the exit animation of snackbar.backgroundcolor: Snackbar background color behavior: Behavior and location of snackbar.content: Content of snackbar.duration: The amount of time snackbar should be displayed.elevation: Elevates the snackbar by increasing shadow.margin: Space around snackbar.onVisible: Called the first time that the snackbar is visible within a scaffold.padding: space around content inside snackbar.shape: Shape of snackbar.width: Width of snackbar." }, { "code": null, "e": 28020, "s": 27975, "text": "action: Action to perform based on snackbar." }, { "code": null, "e": 28073, "s": 28020, "text": "animation: Entry and the exit animation of snackbar." }, { "code": null, "e": 28117, "s": 28073, "text": "backgroundcolor: Snackbar background color " }, { "code": null, "e": 28162, "s": 28117, "text": "behavior: Behavior and location of snackbar." }, { "code": null, "e": 28192, "s": 28162, "text": "content: Content of snackbar." }, { "code": null, "e": 28251, "s": 28192, "text": "duration: The amount of time snackbar should be displayed." }, { "code": null, "e": 28306, "s": 28251, "text": "elevation: Elevates the snackbar by increasing shadow." }, { "code": null, "e": 28337, "s": 28306, "text": "margin: Space around snackbar." }, { "code": null, "e": 28418, "s": 28337, "text": "onVisible: Called the first time that the snackbar is visible within a scaffold." }, { "code": null, "e": 28465, "s": 28418, "text": "padding: space around content inside snackbar." }, { "code": null, "e": 28491, "s": 28465, "text": "shape: Shape of snackbar." }, { "code": null, "e": 28517, "s": 28491, "text": "width: Width of snackbar." }, { "code": null, "e": 28780, "s": 28517, "text": "1. Create a Scaffold Widget: A Snackbar is displayed inside a scaffold widget that is used to create the entire visible screen of your mobile application. It provides the appbar, title, and other properties of the body that all together makes up the widget tree." }, { "code": null, "e": 28897, "s": 28780, "text": " Scaffold(\n appBar: AppBar(\n title: Text(title),\n backgroundColor: Colors.green,\n ),\n\n );" }, { "code": null, "e": 29308, "s": 28897, "text": "2. Create a Snackbar class: Create a stateless widget class that will represent your snackbar and the actions it is performing. Inside this class create a button it may be elevated, raised or flat, and assign a look to it, For Example: color, text, onhover effect etc. Create a final property and return Snackbar to it, that will hold all the actions that are going to be performed when the button is clicked. " }, { "code": null, "e": 29853, "s": 29308, "text": "class snackBarDemo extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return Center(\n child: RaisedButton(\n child: Text('Click Here!'),\n color: Colors.green,\n onPressed: () {\n final snackdemo = SnackBar(\n content: Text('Hii this is GFG\\'s SnackBar'),\n backgroundColor: Colors.green,\n elevation: 10,\n behavior: SnackBarBehavior.floating,\n margin: EdgeInsets.all(5),\n ),\n }),\n );\n }\n}" }, { "code": null, "e": 30085, "s": 29853, "text": "3. Display the Snackbar: Use the Scaffold Messenger class to display the information contained by your snackbar. It uses a context provided by the BuilContext argument. Here, snackdemo is the final property that holds the snackbar." }, { "code": null, "e": 30133, "s": 30085, "text": " Scaffold.of(context).showSnackBar(snackdemo);" }, { "code": null, "e": 30250, "s": 30133, "text": "4. Call your Class: Finally, Inside the body of the scaffold call the stateless class you created for your snackbar." }, { "code": null, "e": 30399, "s": 30250, "text": "Scaffold(\n appBar: AppBar(\n title: Text(title),\n backgroundColor: Colors.green,\n ),\n body: snackBarDemo(),\n );\n }\n}" }, { "code": null, "e": 30415, "s": 30399, "text": "File: main.dart" }, { "code": null, "e": 30420, "s": 30415, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { static const header = 'GeeksforGeeks'; @override Widget build(BuildContext context) { return const MaterialApp( title: header, home: MyHomePage(title: header), ); }} class MyHomePage extends StatelessWidget { const MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(title), backgroundColor: Colors.green, ), body: snackBarDemo(), ); }} class snackBarDemo extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: RaisedButton( child: Text('Click Here!'), color: Colors.green, onPressed: () { final snackdemo = SnackBar( content: Text('Hii this is GFG\\'s SnackBar'), backgroundColor: Colors.green, elevation: 10, behavior: SnackBarBehavior.floating, margin: EdgeInsets.all(5), ); Scaffold.of(context).showSnackBar(snackdemo); }), ); }}", "e": 31637, "s": 30420, "text": null }, { "code": null, "e": 31645, "s": 31637, "text": "Output:" }, { "code": null, "e": 31659, "s": 31645, "text": "rharshitaaa21" }, { "code": null, "e": 31681, "s": 31659, "text": "Flutter UI-components" }, { "code": null, "e": 31697, "s": 31681, "text": "Flutter-widgets" }, { "code": null, "e": 31705, "s": 31697, "text": "Android" }, { "code": null, "e": 31710, "s": 31705, "text": "Dart" }, { "code": null, "e": 31718, "s": 31710, "text": "Flutter" }, { "code": null, "e": 31726, "s": 31718, "text": "Android" }, { "code": null, "e": 31824, "s": 31726, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31862, "s": 31824, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 31901, "s": 31862, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 31951, "s": 31901, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 31993, "s": 31951, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 32044, "s": 31993, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 32076, "s": 32044, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 32104, "s": 32076, "text": "Listview.builder in Flutter" }, { "code": null, "e": 32126, "s": 32104, "text": "Flutter - Asset Image" }, { "code": null, "e": 32151, "s": 32126, "text": "Splash Screen in Flutter" } ]
How to Iterate over Dataframe Groups in Python-Pandas? - GeeksforGeeks
18 Aug, 2020 In this article, we’ll see how we can iterate over the groups in which a dataframe is divided. So, let’s see different ways to do this task. First, Let’s create a dataframe: Code: Python3 # import pandas libraryimport pandas as pd # dictionarydict = {'X': ['A', 'B', 'A', 'B'], 'Y': [1, 4, 3, 2]} # create a dataframedf = pd.DataFrame(dict) # show the dataframedf Output: Method 1: Using Dataframe.groupby(). This function is used to split the data into groups based on some criteria. Example: we’ll simply iterate over all the groups created. Python3 # import pandas libraryimport pandas as pd # dictionarydict = {'X': ['A', 'B', 'A', 'B'], 'Y': [1, 4, 3, 2]} # create a dataframedf = pd.DataFrame(dict) # group by 'X' columngroups = df.groupby("X") for name, group in groups: print(name) print(group) print("\n") Output: In above example, we have grouped on the basis of column “X”. As there are two different values under column “X”, so our dataframe will be divided into 2 groups. Then our for loop will run 2 times as the number groups are 2. “name” represents the group name and “group” represents the actual grouped dataframe. Method 2: Using Dataframe.groupby() and Groupby_object.groups.keys() together. Groupby_object.groups.keys() method will return the keys of the groups. Example: we’ll iterate over the keys. Python3 # import pandas libraryimport pandas as pd # dictionarydict = {'X': ['A', 'B', 'A', 'B'], 'Y': [1, 4, 3, 2]} # create a dataframedf = pd.DataFrame(dict) # group by "X" columngroups = df.groupby('X') # extract keys from groupskeys = groups.groups.keys() for i in keys: print(groups.get_group(i)) print('\n') Output: In above example, we’ll use the function groups.get_group() to get all the groups. First we’ll get all the keys of the group and then iterate through that and then calling get_group() method for each key. get_group() method will return group corresponding to the key. Python pandas-dataFrame Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python
[ { "code": null, "e": 26317, "s": 26289, "text": "\n18 Aug, 2020" }, { "code": null, "e": 26458, "s": 26317, "text": "In this article, we’ll see how we can iterate over the groups in which a dataframe is divided. So, let’s see different ways to do this task." }, { "code": null, "e": 26491, "s": 26458, "text": "First, Let’s create a dataframe:" }, { "code": null, "e": 26497, "s": 26491, "text": "Code:" }, { "code": null, "e": 26505, "s": 26497, "text": "Python3" }, { "code": "# import pandas libraryimport pandas as pd # dictionarydict = {'X': ['A', 'B', 'A', 'B'], 'Y': [1, 4, 3, 2]} # create a dataframedf = pd.DataFrame(dict) # show the dataframedf", "e": 26691, "s": 26505, "text": null }, { "code": null, "e": 26699, "s": 26691, "text": "Output:" }, { "code": null, "e": 26736, "s": 26699, "text": "Method 1: Using Dataframe.groupby()." }, { "code": null, "e": 26813, "s": 26736, "text": "This function is used to split the data into groups based on some criteria. " }, { "code": null, "e": 26872, "s": 26813, "text": "Example: we’ll simply iterate over all the groups created." }, { "code": null, "e": 26880, "s": 26872, "text": "Python3" }, { "code": "# import pandas libraryimport pandas as pd # dictionarydict = {'X': ['A', 'B', 'A', 'B'], 'Y': [1, 4, 3, 2]} # create a dataframedf = pd.DataFrame(dict) # group by 'X' columngroups = df.groupby(\"X\") for name, group in groups: print(name) print(group) print(\"\\n\")", "e": 27163, "s": 26880, "text": null }, { "code": null, "e": 27171, "s": 27163, "text": "Output:" }, { "code": null, "e": 27483, "s": 27171, "text": "In above example, we have grouped on the basis of column “X”. As there are two different values under column “X”, so our dataframe will be divided into 2 groups. Then our for loop will run 2 times as the number groups are 2. “name” represents the group name and “group” represents the actual grouped dataframe. " }, { "code": null, "e": 27562, "s": 27483, "text": "Method 2: Using Dataframe.groupby() and Groupby_object.groups.keys() together." }, { "code": null, "e": 27634, "s": 27562, "text": "Groupby_object.groups.keys() method will return the keys of the groups." }, { "code": null, "e": 27672, "s": 27634, "text": "Example: we’ll iterate over the keys." }, { "code": null, "e": 27680, "s": 27672, "text": "Python3" }, { "code": "# import pandas libraryimport pandas as pd # dictionarydict = {'X': ['A', 'B', 'A', 'B'], 'Y': [1, 4, 3, 2]} # create a dataframedf = pd.DataFrame(dict) # group by \"X\" columngroups = df.groupby('X') # extract keys from groupskeys = groups.groups.keys() for i in keys: print(groups.get_group(i)) print('\\n')", "e": 28005, "s": 27680, "text": null }, { "code": null, "e": 28013, "s": 28005, "text": "Output:" }, { "code": null, "e": 28282, "s": 28013, "text": "In above example, we’ll use the function groups.get_group() to get all the groups. First we’ll get all the keys of the group and then iterate through that and then calling get_group() method for each key. get_group() method will return group corresponding to the key." }, { "code": null, "e": 28306, "s": 28282, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28329, "s": 28306, "text": "Python Pandas-exercise" }, { "code": null, "e": 28343, "s": 28329, "text": "Python-pandas" }, { "code": null, "e": 28350, "s": 28343, "text": "Python" }, { "code": null, "e": 28448, "s": 28350, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28466, "s": 28448, "text": "Python Dictionary" }, { "code": null, "e": 28501, "s": 28466, "text": "Read a file line by line in Python" }, { "code": null, "e": 28533, "s": 28501, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28555, "s": 28533, "text": "Enumerate() in Python" }, { "code": null, "e": 28597, "s": 28555, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28627, "s": 28597, "text": "Iterate over a list in Python" }, { "code": null, "e": 28656, "s": 28627, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28700, "s": 28656, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28737, "s": 28700, "text": "Create a Pandas DataFrame from Lists" } ]
How to convert XML file into array in PHP? - GeeksforGeeks
02 Jul, 2019 Given an XML document and the task is to convert an XML file into PHP array. To convert the XML document into PHP array, some PHP functions are used which are listed below: file_get_contents() function: The file_get_contents() function is used to read a file as string. This function uses memory mapping techniques which are supported by the server and thus enhances the performance by making it a preferred way of reading contents of a file. simplexml_load_string() function: Sometimes there is a need of parsing XML data in PHP. There are a handful of methods available to parse XML data. SimpleXML is one of them. Parsing an XML document means that navigating through the XML document and return the relevant pieces of information. Nowadays, a few APIs return data in JSON format but there are still a large number of websites which returns data in XML format. So we have to master in parsing an XML document if we want to feast on APIs available. json_encode() function: The json_encode() function is used to encode a JSON string and return the JSON representation of value. json_decode() function: The json_decode() function is used to decode a JSON string. It converts a JSON encoded string into a PHP variable. Step 1: Creating an XML file (Optional): Create an XML file which need to convert into the array.GFG.xml <?xml version='1.0'?> <firstnamedb> <firstname name='Akshat'> <symbol>AK</symbol> <code>A</code> </firstname> <firstname name='Sanjay'> <symbol>SA</symbol> <code>B</code> </firstname> <firstname name='Parvez'> <symbol>PA</symbol> <code>C</code> </firstname></firstnamedb> Step 2: Convert the file into string: XML file will import into PHP using file_get_contents() function which read the entire file as a string and store into a variable. Step 3: Convert the string into an Object: Convert the string into an object which can be easily done through some inbuilt functions simplexml_load_string() of PHP. Step 4: Convert the object into JSON: The json_encode() function is used to encode a JSON string and return the JSON representation of value. Step 5: Decoding the JSON Object: The json_decode() function decode a JSON string. It converts a JSON encoded string into a PHP variable. Example: <?php // xml file path$path = "GFG.xml"; // Read entire file into string$xmlfile = file_get_contents($path); // Convert xml string into an object$new = simplexml_load_string($xmlfile); // Convert into json$con = json_encode($new); // Convert into associative array$newArr = json_decode($con, true); print_r($newArr); ?> Output: SohomPramanick Picked PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to call PHP function on the click of a Button ? How to check whether an array is empty using PHP?
[ { "code": null, "e": 26181, "s": 26153, "text": "\n02 Jul, 2019" }, { "code": null, "e": 26354, "s": 26181, "text": "Given an XML document and the task is to convert an XML file into PHP array. To convert the XML document into PHP array, some PHP functions are used which are listed below:" }, { "code": null, "e": 26624, "s": 26354, "text": "file_get_contents() function: The file_get_contents() function is used to read a file as string. This function uses memory mapping techniques which are supported by the server and thus enhances the performance by making it a preferred way of reading contents of a file." }, { "code": null, "e": 27132, "s": 26624, "text": "simplexml_load_string() function: Sometimes there is a need of parsing XML data in PHP. There are a handful of methods available to parse XML data. SimpleXML is one of them. Parsing an XML document means that navigating through the XML document and return the relevant pieces of information. Nowadays, a few APIs return data in JSON format but there are still a large number of websites which returns data in XML format. So we have to master in parsing an XML document if we want to feast on APIs available." }, { "code": null, "e": 27260, "s": 27132, "text": "json_encode() function: The json_encode() function is used to encode a JSON string and return the JSON representation of value." }, { "code": null, "e": 27399, "s": 27260, "text": "json_decode() function: The json_decode() function is used to decode a JSON string. It converts a JSON encoded string into a PHP variable." }, { "code": null, "e": 27504, "s": 27399, "text": "Step 1: Creating an XML file (Optional): Create an XML file which need to convert into the array.GFG.xml" }, { "code": "<?xml version='1.0'?> <firstnamedb> <firstname name='Akshat'> <symbol>AK</symbol> <code>A</code> </firstname> <firstname name='Sanjay'> <symbol>SA</symbol> <code>B</code> </firstname> <firstname name='Parvez'> <symbol>PA</symbol> <code>C</code> </firstname></firstnamedb>", "e": 27859, "s": 27504, "text": null }, { "code": null, "e": 28028, "s": 27859, "text": "Step 2: Convert the file into string: XML file will import into PHP using file_get_contents() function which read the entire file as a string and store into a variable." }, { "code": null, "e": 28193, "s": 28028, "text": "Step 3: Convert the string into an Object: Convert the string into an object which can be easily done through some inbuilt functions simplexml_load_string() of PHP." }, { "code": null, "e": 28335, "s": 28193, "text": "Step 4: Convert the object into JSON: The json_encode() function is used to encode a JSON string and return the JSON representation of value." }, { "code": null, "e": 28473, "s": 28335, "text": "Step 5: Decoding the JSON Object: The json_decode() function decode a JSON string. It converts a JSON encoded string into a PHP variable." }, { "code": null, "e": 28482, "s": 28473, "text": "Example:" }, { "code": "<?php // xml file path$path = \"GFG.xml\"; // Read entire file into string$xmlfile = file_get_contents($path); // Convert xml string into an object$new = simplexml_load_string($xmlfile); // Convert into json$con = json_encode($new); // Convert into associative array$newArr = json_decode($con, true); print_r($newArr); ?>", "e": 28809, "s": 28482, "text": null }, { "code": null, "e": 28817, "s": 28809, "text": "Output:" }, { "code": null, "e": 28832, "s": 28817, "text": "SohomPramanick" }, { "code": null, "e": 28839, "s": 28832, "text": "Picked" }, { "code": null, "e": 28843, "s": 28839, "text": "PHP" }, { "code": null, "e": 28856, "s": 28843, "text": "PHP Programs" }, { "code": null, "e": 28873, "s": 28856, "text": "Web Technologies" }, { "code": null, "e": 28900, "s": 28873, "text": "Web technologies Questions" }, { "code": null, "e": 28904, "s": 28900, "text": "PHP" }, { "code": null, "e": 29002, "s": 28904, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29052, "s": 29002, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 29092, "s": 29052, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 29153, "s": 29092, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 29203, "s": 29153, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 29248, "s": 29203, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 29298, "s": 29248, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 29338, "s": 29298, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 29399, "s": 29338, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 29451, "s": 29399, "text": "How to call PHP function on the click of a Button ?" } ]
Maximum jumps to reach end of Array with condition that index i can make arr[i] jumps - GeeksforGeeks
22 Jul, 2021 Given an integer N and an array arr[ ] of size N, the task is to find the maximum jumps to reach the end of the array given the constraint that from index i can make arr[i] jumps and reach the position i+arr[i]. Examples: Input: N = 5, arr[] = {2, 3, 5, 7, 9}Output: 12 Explanation:At index 0 make 2 jumps and move to index 2 and make 5 jumps after that to reach index 7 which is out of the array so total number of jumps is (2+5)=7. At index 1 make 3+9= 12 jumps At index 2 make 5 jumpsAt index 3 make 7 jumpsAt index 4 make 9 jumps Input: arr[]={2, 2, 1, 2, 3, 3}Output: 8 Approach: The idea is to use Dynamic programming to solve this problem. Follow the steps below to solve the problem. Initialize an array dp of size N with 0. dp[i] stores the number of jumps needed to reach the end of the array from index i. Also, initialize an integer ans to 0. Traverse through the array from the end of the array using for loopAssign arr[i] to dp[i] since arr[i] is the smallest number of jumps from this index.Now initialize a variable say j and assign j = i+arr[i].If the value of j is less than N, then add dp[j] to dp[i].Update the value of ans as max(ans, dp[i]) Assign arr[i] to dp[i] since arr[i] is the smallest number of jumps from this index. Now initialize a variable say j and assign j = i+arr[i]. If the value of j is less than N, then add dp[j] to dp[i]. Update the value of ans as max(ans, dp[i]) After completing the above steps print the value of ans. C++ Java Python3 C# Javascript // C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the maximum// jumps to reach end of arrayvoid findMaxJumps(int arr[], int N){ // Stores the jumps needed // to reach end from each index int dp[N] = { 0 }; int ans = 0; // Traverse the array for (int i = N - 1; i >= 0; i--) { dp[i] = arr[i]; int j = i + arr[i]; // Check if j is less // than N if (j < N) { // Add dp[j] to the // value of dp[i] dp[i] = dp[i] + dp[j]; } // Update the value // of ans ans = max(ans, dp[i]); } // Print the value of ans cout << ans;} // Driver Codeint main(){ int arr[] = { 2, 3, 5, 7, 9 }; int N = sizeof(arr) / sizeof(arr[0]); findMaxJumps(arr, N); return 0;} // Java code for the above approach import java.io.*; class GFG { // Function to find the maximum// jumps to reach end of arraystatic void findMaxJumps(int arr[], int N){ // Stores the jumps needed // to reach end from each index int dp[] = new int [N]; int ans = 0; // Traverse the array for (int i = N - 1; i >= 0; i--) { dp[i] = arr[i]; int j = i + arr[i]; // Check if j is less // than N if (j < N) { // Add dp[j] to the // value of dp[i] dp[i] = dp[i] + dp[j]; } // Update the value // of ans ans = Math.max(ans, dp[i]); } // Print the value of ans System.out.println(ans);} // Driver Codepublic static void main (String[] args) { int arr[] = { 2, 3, 5, 7, 9 }; int N = arr.length; findMaxJumps(arr, N);}} // This code is contributed by Dharanendra L V. # python 3 code for the above approach # Function to find the maximum# jumps to reach end of arraydef findMaxJumps(arr, N): # Stores the jumps needed # to reach end from each index dp = [0 for i in range(N)] ans = 0 # Traverse the array i = N - 1 while(i >= 0): dp[i] = arr[i] j = i + arr[i] # Check if j is less # than N if (j < N): # Add dp[j] to the # value of dp[i] dp[i] = dp[i] + dp[j] # Update the value # of ans ans = max(ans, dp[i]) i -= 1 # Print the value of ans print(ans) # Driver Codeif __name__ == '__main__': arr = [2, 3, 5, 7, 9] N = len(arr) findMaxJumps(arr, N) # This code is contributed by ipg2016107. // C# code for the above approach using System; class GFG { // Function to find the maximum // jumps to reach end of array static void findMaxJumps(int[] arr, int N) { // Stores the jumps needed // to reach end from each index int[] dp = new int[N]; int ans = 0; // Traverse the array for (int i = N - 1; i >= 0; i--) { dp[i] = arr[i]; int j = i + arr[i]; // Check if j is less // than N if (j < N) { // Add dp[j] to the // value of dp[i] dp[i] = dp[i] + dp[j]; } // Update the value // of ans ans = Math.Max(ans, dp[i]); } // Print the value of ans Console.Write(ans); } // Driver Code public static void Main(string[] args) { int[] arr = { 2, 3, 5, 7, 9 }; int N = arr.Length; findMaxJumps(arr, N); }} // This code is contributed by ukasp. <script>// Javascript code for the above approach // Function to find the maximum// jumps to reach end of arrayfunction findMaxJumps(arr, N){ // Stores the jumps needed // to reach end from each index let dp = new Array(N).fill(0); let ans = 0; // Traverse the array for (let i = N - 1; i >= 0; i--) { dp[i] = arr[i]; let j = i + arr[i]; // Check if j is less // than N if (j < N) { // Add dp[j] to the // value of dp[i] dp[i] = dp[i] + dp[j]; } // Update the value // of ans ans = Math.max(ans, dp[i]); } // Print the value of ans document.write(ans);} // Driver Codelet arr = [2, 3, 5, 7, 9];let N = arr.length; findMaxJumps(arr, N); // This code is contributed by _saurabh_jaiswal.</script> 12 Time Complexity: O(N)Auxiliary Space: O(N) dharanendralv23 ukasp _saurabh_jaiswal ipg2016107 Arrays Dynamic Programming Arrays Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Count pairs with given sum Window Sliding Technique Reversal algorithm for array rotation Next Greater Element 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 26067, "s": 26039, "text": "\n22 Jul, 2021" }, { "code": null, "e": 26279, "s": 26067, "text": "Given an integer N and an array arr[ ] of size N, the task is to find the maximum jumps to reach the end of the array given the constraint that from index i can make arr[i] jumps and reach the position i+arr[i]." }, { "code": null, "e": 26289, "s": 26279, "text": "Examples:" }, { "code": null, "e": 26602, "s": 26289, "text": "Input: N = 5, arr[] = {2, 3, 5, 7, 9}Output: 12 Explanation:At index 0 make 2 jumps and move to index 2 and make 5 jumps after that to reach index 7 which is out of the array so total number of jumps is (2+5)=7. At index 1 make 3+9= 12 jumps At index 2 make 5 jumpsAt index 3 make 7 jumpsAt index 4 make 9 jumps " }, { "code": null, "e": 26643, "s": 26602, "text": "Input: arr[]={2, 2, 1, 2, 3, 3}Output: 8" }, { "code": null, "e": 26760, "s": 26643, "text": "Approach: The idea is to use Dynamic programming to solve this problem. Follow the steps below to solve the problem." }, { "code": null, "e": 26923, "s": 26760, "text": "Initialize an array dp of size N with 0. dp[i] stores the number of jumps needed to reach the end of the array from index i. Also, initialize an integer ans to 0." }, { "code": null, "e": 27231, "s": 26923, "text": "Traverse through the array from the end of the array using for loopAssign arr[i] to dp[i] since arr[i] is the smallest number of jumps from this index.Now initialize a variable say j and assign j = i+arr[i].If the value of j is less than N, then add dp[j] to dp[i].Update the value of ans as max(ans, dp[i])" }, { "code": null, "e": 27316, "s": 27231, "text": "Assign arr[i] to dp[i] since arr[i] is the smallest number of jumps from this index." }, { "code": null, "e": 27373, "s": 27316, "text": "Now initialize a variable say j and assign j = i+arr[i]." }, { "code": null, "e": 27432, "s": 27373, "text": "If the value of j is less than N, then add dp[j] to dp[i]." }, { "code": null, "e": 27475, "s": 27432, "text": "Update the value of ans as max(ans, dp[i])" }, { "code": null, "e": 27532, "s": 27475, "text": "After completing the above steps print the value of ans." }, { "code": null, "e": 27536, "s": 27532, "text": "C++" }, { "code": null, "e": 27541, "s": 27536, "text": "Java" }, { "code": null, "e": 27549, "s": 27541, "text": "Python3" }, { "code": null, "e": 27552, "s": 27549, "text": "C#" }, { "code": null, "e": 27563, "s": 27552, "text": "Javascript" }, { "code": "// C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the maximum// jumps to reach end of arrayvoid findMaxJumps(int arr[], int N){ // Stores the jumps needed // to reach end from each index int dp[N] = { 0 }; int ans = 0; // Traverse the array for (int i = N - 1; i >= 0; i--) { dp[i] = arr[i]; int j = i + arr[i]; // Check if j is less // than N if (j < N) { // Add dp[j] to the // value of dp[i] dp[i] = dp[i] + dp[j]; } // Update the value // of ans ans = max(ans, dp[i]); } // Print the value of ans cout << ans;} // Driver Codeint main(){ int arr[] = { 2, 3, 5, 7, 9 }; int N = sizeof(arr) / sizeof(arr[0]); findMaxJumps(arr, N); return 0;}", "e": 28398, "s": 27563, "text": null }, { "code": "// Java code for the above approach import java.io.*; class GFG { // Function to find the maximum// jumps to reach end of arraystatic void findMaxJumps(int arr[], int N){ // Stores the jumps needed // to reach end from each index int dp[] = new int [N]; int ans = 0; // Traverse the array for (int i = N - 1; i >= 0; i--) { dp[i] = arr[i]; int j = i + arr[i]; // Check if j is less // than N if (j < N) { // Add dp[j] to the // value of dp[i] dp[i] = dp[i] + dp[j]; } // Update the value // of ans ans = Math.max(ans, dp[i]); } // Print the value of ans System.out.println(ans);} // Driver Codepublic static void main (String[] args) { int arr[] = { 2, 3, 5, 7, 9 }; int N = arr.length; findMaxJumps(arr, N);}} // This code is contributed by Dharanendra L V.", "e": 29297, "s": 28398, "text": null }, { "code": "# python 3 code for the above approach # Function to find the maximum# jumps to reach end of arraydef findMaxJumps(arr, N): # Stores the jumps needed # to reach end from each index dp = [0 for i in range(N)] ans = 0 # Traverse the array i = N - 1 while(i >= 0): dp[i] = arr[i] j = i + arr[i] # Check if j is less # than N if (j < N): # Add dp[j] to the # value of dp[i] dp[i] = dp[i] + dp[j] # Update the value # of ans ans = max(ans, dp[i]) i -= 1 # Print the value of ans print(ans) # Driver Codeif __name__ == '__main__': arr = [2, 3, 5, 7, 9] N = len(arr) findMaxJumps(arr, N) # This code is contributed by ipg2016107.", "e": 30070, "s": 29297, "text": null }, { "code": "// C# code for the above approach using System; class GFG { // Function to find the maximum // jumps to reach end of array static void findMaxJumps(int[] arr, int N) { // Stores the jumps needed // to reach end from each index int[] dp = new int[N]; int ans = 0; // Traverse the array for (int i = N - 1; i >= 0; i--) { dp[i] = arr[i]; int j = i + arr[i]; // Check if j is less // than N if (j < N) { // Add dp[j] to the // value of dp[i] dp[i] = dp[i] + dp[j]; } // Update the value // of ans ans = Math.Max(ans, dp[i]); } // Print the value of ans Console.Write(ans); } // Driver Code public static void Main(string[] args) { int[] arr = { 2, 3, 5, 7, 9 }; int N = arr.Length; findMaxJumps(arr, N); }} // This code is contributed by ukasp.", "e": 31075, "s": 30070, "text": null }, { "code": "<script>// Javascript code for the above approach // Function to find the maximum// jumps to reach end of arrayfunction findMaxJumps(arr, N){ // Stores the jumps needed // to reach end from each index let dp = new Array(N).fill(0); let ans = 0; // Traverse the array for (let i = N - 1; i >= 0; i--) { dp[i] = arr[i]; let j = i + arr[i]; // Check if j is less // than N if (j < N) { // Add dp[j] to the // value of dp[i] dp[i] = dp[i] + dp[j]; } // Update the value // of ans ans = Math.max(ans, dp[i]); } // Print the value of ans document.write(ans);} // Driver Codelet arr = [2, 3, 5, 7, 9];let N = arr.length; findMaxJumps(arr, N); // This code is contributed by _saurabh_jaiswal.</script>", "e": 31898, "s": 31075, "text": null }, { "code": null, "e": 31904, "s": 31901, "text": "12" }, { "code": null, "e": 31949, "s": 31906, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 31967, "s": 31951, "text": "dharanendralv23" }, { "code": null, "e": 31973, "s": 31967, "text": "ukasp" }, { "code": null, "e": 31990, "s": 31973, "text": "_saurabh_jaiswal" }, { "code": null, "e": 32001, "s": 31990, "text": "ipg2016107" }, { "code": null, "e": 32008, "s": 32001, "text": "Arrays" }, { "code": null, "e": 32028, "s": 32008, "text": "Dynamic Programming" }, { "code": null, "e": 32035, "s": 32028, "text": "Arrays" }, { "code": null, "e": 32055, "s": 32035, "text": "Dynamic Programming" }, { "code": null, "e": 32153, "s": 32055, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32184, "s": 32153, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 32211, "s": 32184, "text": "Count pairs with given sum" }, { "code": null, "e": 32236, "s": 32211, "text": "Window Sliding Technique" }, { "code": null, "e": 32274, "s": 32236, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 32295, "s": 32274, "text": "Next Greater Element" }, { "code": null, "e": 32324, "s": 32295, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 32354, "s": 32324, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 32388, "s": 32354, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 32419, "s": 32388, "text": "Bellman–Ford Algorithm | DP-23" } ]
Python SQLite - Insert Data - GeeksforGeeks
30 Apr, 2021 In this article, we will discuss how can we insert data in a table in the SQLite database from Python using the sqlite3 module. The SQL INSERT INTO statement of SQL is used to insert a new row in a table. There are two ways of using the INSERT INTO statement for inserting rows: Only values: The first method is to specify only the value of data to be inserted without the column names. INSERT INTO table_name VALUES (value1, value2, value3,...); table_name: name of the table. value1, value2,.. : value of first column, second column,... for the new record Column names and values both: In the second method we will specify both the columns which we want to fill and their corresponding values as shown below: INSERT INTO table_name (column1, column2, column3,..) VALUES ( value1, value2, value3,..); table_name: name of the table. column1: name of first column, second column ... value1, value2, value3 : value of first column, second column,... for the new record Example 1: Below is a program that depicts how to insert data in an SQLite table using only values. In the program, we first create a table named STUDENT and then insert values into it using the 1st syntax of the INSERT query. Finally, we display the content of the table and commit it to the database. Python3 # Import moduleimport sqlite3 # Connecting to sqliteconn = sqlite3.connect('geeks2.db') # Creating a cursor object using the # cursor() methodcursor = conn.cursor() # Creating tabletable ="""CREATE TABLE STUDENT(NAME VARCHAR(255), CLASS VARCHAR(255),SECTION VARCHAR(255));"""cursor.execute(table) # Queries to INSERT records.cursor.execute('''INSERT INTO STUDENT VALUES ('Raju', '7th', 'A')''')cursor.execute('''INSERT INTO STUDENT VALUES ('Shyam', '8th', 'B')''')cursor.execute('''INSERT INTO STUDENT VALUES ('Baburao', '9th', 'C')''') # Display data insertedprint("Data Inserted in the table: ")data=cursor.execute('''SELECT * FROM STUDENT''')for row in data: print(row) # Commit your changes in the database conn.commit() # Closing the connectionconn.close() Output: SQLite3: Example 2: The below program is similar to that of the 1st program, but we insert values into the table by reordering the names of the columns with values as in the 2nd syntax. Python3 # Import moduleimport sqlite3 # Connecting to sqliteconn = sqlite3.connect('geek.db') # Creating a cursor object using the # cursor() methodcursor = conn.cursor() # Creating tabletable ="""CREATE TABLE STUDENT(NAME VARCHAR(255), CLASS VARCHAR(255),SECTION VARCHAR(255));"""cursor.execute(table) # Queries to INSERT records.cursor.execute( '''INSERT INTO STUDENT (CLASS, SECTION, NAME) VALUES ('7th', 'A', 'Raju')''') cursor.execute( '''INSERT INTO STUDENT (SECTION, NAME, CLASS) VALUES ('B', 'Shyam', '8th')''') cursor.execute( '''INSERT INTO STUDENT (NAME, CLASS, SECTION ) VALUES ('Baburao', '9th', 'C')''') # Display data insertedprint("Data Inserted in the table: ")data=cursor.execute('''SELECT * FROM STUDENT''')for row in data: print(row) # Commit your changes in # the database conn.commit() # Closing the connectionconn.close() Output: SQLite3: Picked Python-SQLite Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python
[ { "code": null, "e": 25799, "s": 25771, "text": "\n30 Apr, 2021" }, { "code": null, "e": 26078, "s": 25799, "text": "In this article, we will discuss how can we insert data in a table in the SQLite database from Python using the sqlite3 module. The SQL INSERT INTO statement of SQL is used to insert a new row in a table. There are two ways of using the INSERT INTO statement for inserting rows:" }, { "code": null, "e": 26186, "s": 26078, "text": "Only values: The first method is to specify only the value of data to be inserted without the column names." }, { "code": null, "e": 26246, "s": 26186, "text": "INSERT INTO table_name VALUES (value1, value2, value3,...);" }, { "code": null, "e": 26277, "s": 26246, "text": "table_name: name of the table." }, { "code": null, "e": 26357, "s": 26277, "text": "value1, value2,.. : value of first column, second column,... for the new record" }, { "code": null, "e": 26510, "s": 26357, "text": "Column names and values both: In the second method we will specify both the columns which we want to fill and their corresponding values as shown below:" }, { "code": null, "e": 26601, "s": 26510, "text": "INSERT INTO table_name (column1, column2, column3,..) VALUES ( value1, value2, value3,..);" }, { "code": null, "e": 26632, "s": 26601, "text": "table_name: name of the table." }, { "code": null, "e": 26681, "s": 26632, "text": "column1: name of first column, second column ..." }, { "code": null, "e": 26766, "s": 26681, "text": "value1, value2, value3 : value of first column, second column,... for the new record" }, { "code": null, "e": 27069, "s": 26766, "text": "Example 1: Below is a program that depicts how to insert data in an SQLite table using only values. In the program, we first create a table named STUDENT and then insert values into it using the 1st syntax of the INSERT query. Finally, we display the content of the table and commit it to the database." }, { "code": null, "e": 27077, "s": 27069, "text": "Python3" }, { "code": "# Import moduleimport sqlite3 # Connecting to sqliteconn = sqlite3.connect('geeks2.db') # Creating a cursor object using the # cursor() methodcursor = conn.cursor() # Creating tabletable =\"\"\"CREATE TABLE STUDENT(NAME VARCHAR(255), CLASS VARCHAR(255),SECTION VARCHAR(255));\"\"\"cursor.execute(table) # Queries to INSERT records.cursor.execute('''INSERT INTO STUDENT VALUES ('Raju', '7th', 'A')''')cursor.execute('''INSERT INTO STUDENT VALUES ('Shyam', '8th', 'B')''')cursor.execute('''INSERT INTO STUDENT VALUES ('Baburao', '9th', 'C')''') # Display data insertedprint(\"Data Inserted in the table: \")data=cursor.execute('''SELECT * FROM STUDENT''')for row in data: print(row) # Commit your changes in the database conn.commit() # Closing the connectionconn.close()", "e": 27852, "s": 27077, "text": null }, { "code": null, "e": 27860, "s": 27852, "text": "Output:" }, { "code": null, "e": 27869, "s": 27860, "text": "SQLite3:" }, { "code": null, "e": 28046, "s": 27869, "text": "Example 2: The below program is similar to that of the 1st program, but we insert values into the table by reordering the names of the columns with values as in the 2nd syntax." }, { "code": null, "e": 28054, "s": 28046, "text": "Python3" }, { "code": "# Import moduleimport sqlite3 # Connecting to sqliteconn = sqlite3.connect('geek.db') # Creating a cursor object using the # cursor() methodcursor = conn.cursor() # Creating tabletable =\"\"\"CREATE TABLE STUDENT(NAME VARCHAR(255), CLASS VARCHAR(255),SECTION VARCHAR(255));\"\"\"cursor.execute(table) # Queries to INSERT records.cursor.execute( '''INSERT INTO STUDENT (CLASS, SECTION, NAME) VALUES ('7th', 'A', 'Raju')''') cursor.execute( '''INSERT INTO STUDENT (SECTION, NAME, CLASS) VALUES ('B', 'Shyam', '8th')''') cursor.execute( '''INSERT INTO STUDENT (NAME, CLASS, SECTION ) VALUES ('Baburao', '9th', 'C')''') # Display data insertedprint(\"Data Inserted in the table: \")data=cursor.execute('''SELECT * FROM STUDENT''')for row in data: print(row) # Commit your changes in # the database conn.commit() # Closing the connectionconn.close()", "e": 28909, "s": 28054, "text": null }, { "code": null, "e": 28917, "s": 28909, "text": "Output:" }, { "code": null, "e": 28926, "s": 28917, "text": "SQLite3:" }, { "code": null, "e": 28933, "s": 28926, "text": "Picked" }, { "code": null, "e": 28947, "s": 28933, "text": "Python-SQLite" }, { "code": null, "e": 28954, "s": 28947, "text": "Python" }, { "code": null, "e": 29052, "s": 28954, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29070, "s": 29052, "text": "Python Dictionary" }, { "code": null, "e": 29102, "s": 29070, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29124, "s": 29102, "text": "Enumerate() in Python" }, { "code": null, "e": 29166, "s": 29124, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29192, "s": 29166, "text": "Python String | replace()" }, { "code": null, "e": 29221, "s": 29192, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29265, "s": 29221, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29302, "s": 29265, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29338, "s": 29302, "text": "Convert integer to string in Python" } ]
Taking password as input in C++ - GeeksforGeeks
21 Aug, 2021 There are two methods in which input can be taken in a more secure way: Do not display any content. Display a special character such as an asterisk instead of actual content. In this method, input content will be invisible. This can be implemented in two ways: Program 1: Below is the program where console mode is set to enable, echo input, and reset the console mode: C++ // C++ program to take the input// invisibly#include <iostream>#include <windows.h>using namespace std; // Function take password and// reset to console modestd::string takePasswdFromUser(){ HANDLE hStdInput = GetStdHandle(STD_INPUT_HANDLE); DWORD mode = 0; // Create a restore point Mode // is know 503 GetConsoleMode(hStdInput, &mode); // Enable echo input // set to 499 SetConsoleMode( hStdInput, mode & (~ENABLE_ECHO_INPUT)); // Take input string ipt; getline(cin, ipt); // Otherwise next cout will print // into the same line cout << endl; // Restore the mode SetConsoleMode(hStdInput, mode); return ipt;} // Driver Codeint main(){ string input; cout << "@root>>> "; // Function Call input = takePasswdFromUser(); // Print the input cout << input << endl;} Output: For this getch() is used. This function takes a character input from user without buffer and doesn’t wait for the user to press “return” key. Program 2: Below is the C++ program to demonstrate the use of getch() in conio.h: C++ // C++ program to demonstrate the// use of getch()#include <conio.h>#include <iostream>using namespace std; // Function using getch()std::string takePasswdFromUser(){ string ipt = ""; char ipt_ch; while (true) { ipt_ch = getch(); // Check whether user enters // a special non-printable // character if (ipt_ch < 32) { cout << endl; return ipt; } ipt.push_back(ipt_ch); }} // Driver Codeint main(){ string input; cout << "@root>>> "; // Function call input = takePasswdFromUser(); cout << input << endl;} Output: Drawback: The user can’t clear the response made earlier. When backspace is pressed, the input is returned. Program 3: Below is the C++ program to demonstrate the solution to the above drawback: C++ // C++ program to demonstrate the// solution of above drawback#include <conio.h>#include <iostream>using namespace std; // Enumeratorenum TT_Input { // ASCII code of backspace is 8 BACKSPACE = 8, RETURN = 32}; // Function accepting passwordstd::string takePasswdFromUser(){ string ipt = ""; char ipt_ch; while (true) { ipt_ch = getch(); if (ipt_ch < TT_Input::RETURN && ipt_ch != TT_Input::BACKSPACE) { cout << endl; return ipt; } // Check whether the user // pressed backspace if (ipt_ch == TT_Input::BACKSPACE) { // Check if ipt is empty or not if (ipt.length() == 0) continue; else { // Removes last character ipt.pop_back(); continue; } } ipt.push_back(ipt_ch); }} // Driver Codeint main(){ string input; cout << "@root>>> "; // Function call input = takePasswdFromUser(); cout << input << endl;} The idea is to use the library <conio.h> here to hide password with asterisk(*). Below is the C++ program using conio.h to hide the password using *: Program 4: C++ // C++ program to hide the password// using *(asterik)#include <conio.h>#include <iostream>using namespace std; // Enumeratorenum IN { // 13 is ASCII for carriage // return IN_BACK = 8, IN_RET = 13 }; // Function that accepts the passwordstd::string takePasswdFromUser( char sp = '*'){ // Stores the password string passwd = ""; char ch_ipt; // Until condition is true while (true) { ch_ipt = getch(); // if the ch_ipt if (ch_ipt == IN::IN_RET) { cout << endl; return passwd; } else if (ch_ipt == IN::IN_BACK && passwd.length() != 0) { passwd.pop_back(); // Cout statement is very // important as it will erase // previously printed character cout << "\b \b"; continue; } // Without using this, program // will crash as \b can't be // print in beginning of line else if (ch_ipt == IN::IN_BACK && passwd.length() == 0) { continue; } passwd.push_back(ch_ipt); cout << sp; }} // Driver Codeint main(){ string input; cout << "@root>>> "; // Function call input = takePasswdFromUser(); cout << input << endl;} adnanirshad158 cpp-input-output Input and Output C++ C++ Programs Programming Language CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Header files in C/C++ and its uses Program to print ASCII Value of a character How to return multiple values from a function in C or C++? C++ Program for QuickSort Sorting a Map by value in C++ STL
[ { "code": null, "e": 25367, "s": 25339, "text": "\n21 Aug, 2021" }, { "code": null, "e": 25439, "s": 25367, "text": "There are two methods in which input can be taken in a more secure way:" }, { "code": null, "e": 25467, "s": 25439, "text": "Do not display any content." }, { "code": null, "e": 25542, "s": 25467, "text": "Display a special character such as an asterisk instead of actual content." }, { "code": null, "e": 25628, "s": 25542, "text": "In this method, input content will be invisible. This can be implemented in two ways:" }, { "code": null, "e": 25639, "s": 25628, "text": "Program 1:" }, { "code": null, "e": 25737, "s": 25639, "text": "Below is the program where console mode is set to enable, echo input, and reset the console mode:" }, { "code": null, "e": 25741, "s": 25737, "text": "C++" }, { "code": "// C++ program to take the input// invisibly#include <iostream>#include <windows.h>using namespace std; // Function take password and// reset to console modestd::string takePasswdFromUser(){ HANDLE hStdInput = GetStdHandle(STD_INPUT_HANDLE); DWORD mode = 0; // Create a restore point Mode // is know 503 GetConsoleMode(hStdInput, &mode); // Enable echo input // set to 499 SetConsoleMode( hStdInput, mode & (~ENABLE_ECHO_INPUT)); // Take input string ipt; getline(cin, ipt); // Otherwise next cout will print // into the same line cout << endl; // Restore the mode SetConsoleMode(hStdInput, mode); return ipt;} // Driver Codeint main(){ string input; cout << \"@root>>> \"; // Function Call input = takePasswdFromUser(); // Print the input cout << input << endl;}", "e": 26601, "s": 25741, "text": null }, { "code": null, "e": 26610, "s": 26601, "text": "Output: " }, { "code": null, "e": 26752, "s": 26610, "text": "For this getch() is used. This function takes a character input from user without buffer and doesn’t wait for the user to press “return” key." }, { "code": null, "e": 26763, "s": 26752, "text": "Program 2:" }, { "code": null, "e": 26834, "s": 26763, "text": "Below is the C++ program to demonstrate the use of getch() in conio.h:" }, { "code": null, "e": 26838, "s": 26834, "text": "C++" }, { "code": "// C++ program to demonstrate the// use of getch()#include <conio.h>#include <iostream>using namespace std; // Function using getch()std::string takePasswdFromUser(){ string ipt = \"\"; char ipt_ch; while (true) { ipt_ch = getch(); // Check whether user enters // a special non-printable // character if (ipt_ch < 32) { cout << endl; return ipt; } ipt.push_back(ipt_ch); }} // Driver Codeint main(){ string input; cout << \"@root>>> \"; // Function call input = takePasswdFromUser(); cout << input << endl;}", "e": 27442, "s": 26838, "text": null }, { "code": null, "e": 27451, "s": 27442, "text": "Output: " }, { "code": null, "e": 27559, "s": 27451, "text": "Drawback: The user can’t clear the response made earlier. When backspace is pressed, the input is returned." }, { "code": null, "e": 27570, "s": 27559, "text": "Program 3:" }, { "code": null, "e": 27647, "s": 27570, "text": "Below is the C++ program to demonstrate the solution to the above drawback: " }, { "code": null, "e": 27651, "s": 27647, "text": "C++" }, { "code": "// C++ program to demonstrate the// solution of above drawback#include <conio.h>#include <iostream>using namespace std; // Enumeratorenum TT_Input { // ASCII code of backspace is 8 BACKSPACE = 8, RETURN = 32}; // Function accepting passwordstd::string takePasswdFromUser(){ string ipt = \"\"; char ipt_ch; while (true) { ipt_ch = getch(); if (ipt_ch < TT_Input::RETURN && ipt_ch != TT_Input::BACKSPACE) { cout << endl; return ipt; } // Check whether the user // pressed backspace if (ipt_ch == TT_Input::BACKSPACE) { // Check if ipt is empty or not if (ipt.length() == 0) continue; else { // Removes last character ipt.pop_back(); continue; } } ipt.push_back(ipt_ch); }} // Driver Codeint main(){ string input; cout << \"@root>>> \"; // Function call input = takePasswdFromUser(); cout << input << endl;}", "e": 28688, "s": 27651, "text": null }, { "code": null, "e": 28838, "s": 28688, "text": "The idea is to use the library <conio.h> here to hide password with asterisk(*). Below is the C++ program using conio.h to hide the password using *:" }, { "code": null, "e": 28850, "s": 28838, "text": "Program 4: " }, { "code": null, "e": 28854, "s": 28850, "text": "C++" }, { "code": "// C++ program to hide the password// using *(asterik)#include <conio.h>#include <iostream>using namespace std; // Enumeratorenum IN { // 13 is ASCII for carriage // return IN_BACK = 8, IN_RET = 13 }; // Function that accepts the passwordstd::string takePasswdFromUser( char sp = '*'){ // Stores the password string passwd = \"\"; char ch_ipt; // Until condition is true while (true) { ch_ipt = getch(); // if the ch_ipt if (ch_ipt == IN::IN_RET) { cout << endl; return passwd; } else if (ch_ipt == IN::IN_BACK && passwd.length() != 0) { passwd.pop_back(); // Cout statement is very // important as it will erase // previously printed character cout << \"\\b \\b\"; continue; } // Without using this, program // will crash as \\b can't be // print in beginning of line else if (ch_ipt == IN::IN_BACK && passwd.length() == 0) { continue; } passwd.push_back(ch_ipt); cout << sp; }} // Driver Codeint main(){ string input; cout << \"@root>>> \"; // Function call input = takePasswdFromUser(); cout << input << endl;}", "e": 30138, "s": 28854, "text": null }, { "code": null, "e": 30155, "s": 30140, "text": "adnanirshad158" }, { "code": null, "e": 30172, "s": 30155, "text": "cpp-input-output" }, { "code": null, "e": 30189, "s": 30172, "text": "Input and Output" }, { "code": null, "e": 30193, "s": 30189, "text": "C++" }, { "code": null, "e": 30206, "s": 30193, "text": "C++ Programs" }, { "code": null, "e": 30227, "s": 30206, "text": "Programming Language" }, { "code": null, "e": 30231, "s": 30227, "text": "CPP" }, { "code": null, "e": 30329, "s": 30231, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30357, "s": 30329, "text": "Operator Overloading in C++" }, { "code": null, "e": 30377, "s": 30357, "text": "Polymorphism in C++" }, { "code": null, "e": 30410, "s": 30377, "text": "Friend class and function in C++" }, { "code": null, "e": 30434, "s": 30410, "text": "Sorting a vector in C++" }, { "code": null, "e": 30459, "s": 30434, "text": "std::string class in C++" }, { "code": null, "e": 30494, "s": 30459, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 30538, "s": 30494, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 30597, "s": 30538, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 30623, "s": 30597, "text": "C++ Program for QuickSort" } ]
Custom Hooks in ReactJS
In this article, we are going to learn how to define custom hooks in ReactJS. All the rules and usage guidelines are the same as that of the predefined ReactJS hooks like − Call Hooks at the Top Level Call Hooks at the Top Level Call Hooks from React Functions only Call Hooks from React Functions only In this example, we will build an input validator application that will display some text based on the user-defined conditions in the custom hook. App.jsx import React from 'react'; import useForm from './CustomHook'; const App = () => { const input = useForm(); return ( <div> <input onChange={input.onChange} value={input.value} /> {input.valid ? 'Welcome to TutorialsPoint' : 'Try again'} </div> ); }; export default App; CustomHook.jsx import React, { useState } from 'react'; const useForm = () => { const [val, setVal] = useState(''); const [valid, setValid] = useState(false); const inputHandler = (e) => { setVal(e.target.value); e.target.value === 'TutorialsPoint' ? setValid(true) : setValid(false); }; return { value: val, onChange: inputHandler, valid }; }; export default useForm; In the above example, when the user types in the input field, then the custom hook is called which decides whether the text is valid or not based on certain conditions. This will produce the following result.
[ { "code": null, "e": 1140, "s": 1062, "text": "In this article, we are going to learn how to define custom hooks in ReactJS." }, { "code": null, "e": 1235, "s": 1140, "text": "All the rules and usage guidelines are the same as that of the predefined ReactJS hooks like −" }, { "code": null, "e": 1263, "s": 1235, "text": "Call Hooks at the Top Level" }, { "code": null, "e": 1291, "s": 1263, "text": "Call Hooks at the Top Level" }, { "code": null, "e": 1328, "s": 1291, "text": "Call Hooks from React Functions only" }, { "code": null, "e": 1365, "s": 1328, "text": "Call Hooks from React Functions only" }, { "code": null, "e": 1512, "s": 1365, "text": "In this example, we will build an input validator application that will display some text based on the user-defined conditions in the custom hook." }, { "code": null, "e": 1520, "s": 1512, "text": "App.jsx" }, { "code": null, "e": 1824, "s": 1520, "text": "import React from 'react';\nimport useForm from './CustomHook';\n\nconst App = () => {\n const input = useForm();\n return (\n <div>\n <input onChange={input.onChange} value={input.value} />\n {input.valid ? 'Welcome to TutorialsPoint' : 'Try again'}\n </div>\n );\n};\nexport default App;" }, { "code": null, "e": 1839, "s": 1824, "text": "CustomHook.jsx" }, { "code": null, "e": 2223, "s": 1839, "text": "import React, { useState } from 'react';\n\nconst useForm = () => {\n const [val, setVal] = useState('');\n const [valid, setValid] = useState(false);\n\n const inputHandler = (e) => {\n setVal(e.target.value);\n e.target.value === 'TutorialsPoint' ? setValid(true) : setValid(false);\n };\n return { value: val, onChange: inputHandler, valid };\n};\n\nexport default useForm;" }, { "code": null, "e": 2392, "s": 2223, "text": "In the above example, when the user types in the input field, then the custom hook is called which decides whether the text is valid or not based on certain conditions." }, { "code": null, "e": 2432, "s": 2392, "text": "This will produce the following result." } ]
Find initial integral solution of Linear Diophantine equation if finite solution exists - GeeksforGeeks
22 Dec, 2021 Given three integers a, b, and c representing a linear equation of the form: ax + by = c. The task is to find the initial integral solution of the given equation if a finite solution exists. A Linear Diophantine equation (LDE) is an equation with 2 or more integer unknowns and the integer unknowns are each to at most degree of 1. Linear Diophantine equation in two variables takes the form of ax+by=c, where x,y are integer variables and a, b, c are integer constants. x and y are unknown variables. Examples: Input: a = 4, b = 18, c = 10 Output: x = -20, y = 5 Explanation: (-20)*4 + (5)*18 = 10 Input: a = 9, b = 12, c = 5 Output: No Solutions exists Approach: First, check if a and are non-zero.If both of them are zero and c is non-zero then, no solution exists. If c is also zero then infinite solution exits.For given a and b, calculate the value of x1, y1, and gcd using Extended Euclidean Algorithm.Now, for a solution to existing gcd(a, b) should be multiple of c.Calculate the solution of the equation as follows: First, check if a and are non-zero. If both of them are zero and c is non-zero then, no solution exists. If c is also zero then infinite solution exits. For given a and b, calculate the value of x1, y1, and gcd using Extended Euclidean Algorithm. Now, for a solution to existing gcd(a, b) should be multiple of c. Calculate the solution of the equation as follows: x = x1 * ( c / gcd ) y = y1 * ( c / gcd ) Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to implement the extended// euclid algorithmint gcd_extend(int a, int b, int& x, int& y){ // Base Case if (b == 0) { x = 1; y = 0; return a; } // Recursively find the gcd else { int g = gcd_extend(b, a % b, x, y); int x1 = x, y1 = y; x = y1; y = x1 - (a / b) * y1; return g; }} // Function to print the solutions of// the given equations ax + by = cvoid print_solution(int a, int b, int c){ int x, y; if (a == 0 && b == 0) { // Condition for infinite solutions if (c == 0) { cout << "Infinite Solutions Exist" << endl; } // Condition for no solutions exist else { cout << "No Solution exists" << endl; } } int gcd = gcd_extend(a, b, x, y); // Condition for no solutions exist if (c % gcd != 0) { cout << "No Solution exists" << endl; } else { // Print the solution cout << "x = " << x * (c / gcd) << ", y = " << y * (c / gcd) << endl; }} // Driver Codeint main(void){ int a, b, c; // Given coefficients a = 4; b = 18; c = 10; // Function Call print_solution(a, b, c); return 0;} // Java program for the above approachclass GFG{ static int x, y; // Function to implement the extended// euclid algorithmstatic int gcd_extend(int a, int b){ // Base Case if (b == 0) { x = 1; y = 0; return a; } // Recursively find the gcd else { int g = gcd_extend(b, a % b); int x1 = x, y1 = y; x = y1; y = x1 - (a / b) * y1; return g; }} // Function to print the solutions of// the given equations ax + by = cstatic void print_solution(int a, int b, int c){ if (a == 0 && b == 0) { // Condition for infinite solutions if (c == 0) { System.out.print("Infinite Solutions " + "Exist" + "\n"); } // Condition for no solutions exist else { System.out.print("No Solution exists" + "\n"); } } int gcd = gcd_extend(a, b); // Condition for no solutions exist if (c % gcd != 0) { System.out.print("No Solution exists" + "\n"); } else { // Print the solution System.out.print("x = " + x * (c / gcd) + ", y = " + y * (c / gcd) + "\n"); }} // Driver Codepublic static void main(String[] args){ int a, b, c; // Given coefficients a = 4; b = 18; c = 10; // Function Call print_solution(a, b, c);}} // This code is contributed by Rajput-Ji # Python3 program for the above approachimport math x, y = 0, 0 # Function to implement the extended# euclid algorithmdef gcd_extend(a, b): global x, y # Base Case if (b == 0): x = 1 y = 0 return a # Recursively find the gcd else: g = gcd_extend(b, a % b) x1, y1 = x, y x = y1 y = x1 - math.floor(a / b) * y1 return g # Function to print the solutions of# the given equations ax + by = cdef print_solution(a, b, c): if (a == 0 and b == 0): # Condition for infinite solutions if (c == 0): print("Infinite Solutions Exist") # Condition for no solutions exist else : print("No Solution exists") gcd = gcd_extend(a, b) # Condition for no solutions exist if (c % gcd != 0): print("No Solution exists") else: # Print the solution print("x = ", int(x * (c / gcd)), ", y = ", int(y * (c / gcd)), sep = "") # Given coefficientsa = 4b = 18c = 10 # Function Callprint_solution(a, b, c) # This code is contributed by decode2207. // C# program for the above approachusing System; class GFG{ static int x, y; // Function to implement the extended// euclid algorithmstatic int gcd_extend(int a, int b){ // Base Case if (b == 0) { x = 1; y = 0; return a; } // Recursively find the gcd else { int g = gcd_extend(b, a % b); int x1 = x, y1 = y; x = y1; y = x1 - (a / b) * y1; return g; }} // Function to print the solutions of// the given equations ax + by = cstatic void print_solution(int a, int b, int c){ if (a == 0 && b == 0) { // Condition for infinite solutions if (c == 0) { Console.Write("Infinite Solutions " + "Exist" + "\n"); } // Condition for no solutions exist else { Console.Write("No Solution exists" + "\n"); } } int gcd = gcd_extend(a, b); // Condition for no solutions exist if (c % gcd != 0) { Console.Write("No Solution exists" + "\n"); } else { // Print the solution Console.Write("x = " + x * (c / gcd) + ", y = " + y * (c / gcd) + "\n"); }} // Driver Codepublic static void Main(String[] args){ int a, b, c; // Given coefficients a = 4; b = 18; c = 10; // Function call print_solution(a, b, c);}} // This code contributed by amal kumar choubey <script> // Javascript program for the above approach let x, y; // Function to implement the extended// euclid algorithmfunction gcd_extend(a, b){ // Base Case if (b == 0) { x = 1; y = 0; return a; } // Recursively find the gcd else { let g = gcd_extend(b, a % b); let x1 = x, y1 = y; x = y1; y = x1 - Math.floor(a / b) * y1; return g; }} // Function to print the solutions of// the given equations ax + by = cfunction print_solution(a, b, c){ if (a == 0 && b == 0) { // Condition for infinite solutions if (c == 0) { document.write("Infinite Solutions " + "Exist" + "\n"); } // Condition for no solutions exist else { document.write("No Solution exists" + "\n"); } } let gcd = gcd_extend(a, b); // Condition for no solutions exist if (c % gcd != 0) { document.write("No Solution exists" + "\n"); } else { // Print the solution document.write("x = " + x * (c / gcd) + ", y = " + y * (c / gcd) + "<br/>"); }} // Driver Code let a, b, c; // Given coefficients a = 4; b = 18; c = 10; // Function Call print_solution(a, b, c); </script> x = -20, y = 5 Time Complexity: O(log(max(A, B))), where A and B are the coefficient of x and y in the given linear equation. Auxiliary Space: O(1) Rajput-Ji Amal Kumar Choubey target_2 decode2207 khushboogoyal499 GCD-LCM Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find sum of elements in a given array Operators in C / C++ Program for factorial of a number Program for Decimal to Binary Conversion Algorithm to solve Rubik's Cube Print all possible combinations of r elements in a given array of size n The Knight's tour problem | Backtracking-1
[ { "code": null, "e": 24620, "s": 24592, "text": "\n22 Dec, 2021" }, { "code": null, "e": 24811, "s": 24620, "text": "Given three integers a, b, and c representing a linear equation of the form: ax + by = c. The task is to find the initial integral solution of the given equation if a finite solution exists." }, { "code": null, "e": 25122, "s": 24811, "text": "A Linear Diophantine equation (LDE) is an equation with 2 or more integer unknowns and the integer unknowns are each to at most degree of 1. Linear Diophantine equation in two variables takes the form of ax+by=c, where x,y are integer variables and a, b, c are integer constants. x and y are unknown variables." }, { "code": null, "e": 25134, "s": 25122, "text": "Examples: " }, { "code": null, "e": 25188, "s": 25134, "text": "Input: a = 4, b = 18, c = 10 Output: x = -20, y = 5 " }, { "code": null, "e": 25223, "s": 25188, "text": "Explanation: (-20)*4 + (5)*18 = 10" }, { "code": null, "e": 25281, "s": 25223, "text": "Input: a = 9, b = 12, c = 5 Output: No Solutions exists " }, { "code": null, "e": 25292, "s": 25281, "text": "Approach: " }, { "code": null, "e": 25653, "s": 25292, "text": "First, check if a and are non-zero.If both of them are zero and c is non-zero then, no solution exists. If c is also zero then infinite solution exits.For given a and b, calculate the value of x1, y1, and gcd using Extended Euclidean Algorithm.Now, for a solution to existing gcd(a, b) should be multiple of c.Calculate the solution of the equation as follows:" }, { "code": null, "e": 25689, "s": 25653, "text": "First, check if a and are non-zero." }, { "code": null, "e": 25806, "s": 25689, "text": "If both of them are zero and c is non-zero then, no solution exists. If c is also zero then infinite solution exits." }, { "code": null, "e": 25900, "s": 25806, "text": "For given a and b, calculate the value of x1, y1, and gcd using Extended Euclidean Algorithm." }, { "code": null, "e": 25967, "s": 25900, "text": "Now, for a solution to existing gcd(a, b) should be multiple of c." }, { "code": null, "e": 26018, "s": 25967, "text": "Calculate the solution of the equation as follows:" }, { "code": null, "e": 26060, "s": 26018, "text": "x = x1 * ( c / gcd )\ny = y1 * ( c / gcd )" }, { "code": null, "e": 26111, "s": 26060, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26115, "s": 26111, "text": "C++" }, { "code": null, "e": 26120, "s": 26115, "text": "Java" }, { "code": null, "e": 26128, "s": 26120, "text": "Python3" }, { "code": null, "e": 26131, "s": 26128, "text": "C#" }, { "code": null, "e": 26142, "s": 26131, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to implement the extended// euclid algorithmint gcd_extend(int a, int b, int& x, int& y){ // Base Case if (b == 0) { x = 1; y = 0; return a; } // Recursively find the gcd else { int g = gcd_extend(b, a % b, x, y); int x1 = x, y1 = y; x = y1; y = x1 - (a / b) * y1; return g; }} // Function to print the solutions of// the given equations ax + by = cvoid print_solution(int a, int b, int c){ int x, y; if (a == 0 && b == 0) { // Condition for infinite solutions if (c == 0) { cout << \"Infinite Solutions Exist\" << endl; } // Condition for no solutions exist else { cout << \"No Solution exists\" << endl; } } int gcd = gcd_extend(a, b, x, y); // Condition for no solutions exist if (c % gcd != 0) { cout << \"No Solution exists\" << endl; } else { // Print the solution cout << \"x = \" << x * (c / gcd) << \", y = \" << y * (c / gcd) << endl; }} // Driver Codeint main(void){ int a, b, c; // Given coefficients a = 4; b = 18; c = 10; // Function Call print_solution(a, b, c); return 0;}", "e": 27579, "s": 26142, "text": null }, { "code": "// Java program for the above approachclass GFG{ static int x, y; // Function to implement the extended// euclid algorithmstatic int gcd_extend(int a, int b){ // Base Case if (b == 0) { x = 1; y = 0; return a; } // Recursively find the gcd else { int g = gcd_extend(b, a % b); int x1 = x, y1 = y; x = y1; y = x1 - (a / b) * y1; return g; }} // Function to print the solutions of// the given equations ax + by = cstatic void print_solution(int a, int b, int c){ if (a == 0 && b == 0) { // Condition for infinite solutions if (c == 0) { System.out.print(\"Infinite Solutions \" + \"Exist\" + \"\\n\"); } // Condition for no solutions exist else { System.out.print(\"No Solution exists\" + \"\\n\"); } } int gcd = gcd_extend(a, b); // Condition for no solutions exist if (c % gcd != 0) { System.out.print(\"No Solution exists\" + \"\\n\"); } else { // Print the solution System.out.print(\"x = \" + x * (c / gcd) + \", y = \" + y * (c / gcd) + \"\\n\"); }} // Driver Codepublic static void main(String[] args){ int a, b, c; // Given coefficients a = 4; b = 18; c = 10; // Function Call print_solution(a, b, c);}} // This code is contributed by Rajput-Ji", "e": 29045, "s": 27579, "text": null }, { "code": "# Python3 program for the above approachimport math x, y = 0, 0 # Function to implement the extended# euclid algorithmdef gcd_extend(a, b): global x, y # Base Case if (b == 0): x = 1 y = 0 return a # Recursively find the gcd else: g = gcd_extend(b, a % b) x1, y1 = x, y x = y1 y = x1 - math.floor(a / b) * y1 return g # Function to print the solutions of# the given equations ax + by = cdef print_solution(a, b, c): if (a == 0 and b == 0): # Condition for infinite solutions if (c == 0): print(\"Infinite Solutions Exist\") # Condition for no solutions exist else : print(\"No Solution exists\") gcd = gcd_extend(a, b) # Condition for no solutions exist if (c % gcd != 0): print(\"No Solution exists\") else: # Print the solution print(\"x = \", int(x * (c / gcd)), \", y = \", int(y * (c / gcd)), sep = \"\") # Given coefficientsa = 4b = 18c = 10 # Function Callprint_solution(a, b, c) # This code is contributed by decode2207.", "e": 30152, "s": 29045, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ static int x, y; // Function to implement the extended// euclid algorithmstatic int gcd_extend(int a, int b){ // Base Case if (b == 0) { x = 1; y = 0; return a; } // Recursively find the gcd else { int g = gcd_extend(b, a % b); int x1 = x, y1 = y; x = y1; y = x1 - (a / b) * y1; return g; }} // Function to print the solutions of// the given equations ax + by = cstatic void print_solution(int a, int b, int c){ if (a == 0 && b == 0) { // Condition for infinite solutions if (c == 0) { Console.Write(\"Infinite Solutions \" + \"Exist\" + \"\\n\"); } // Condition for no solutions exist else { Console.Write(\"No Solution exists\" + \"\\n\"); } } int gcd = gcd_extend(a, b); // Condition for no solutions exist if (c % gcd != 0) { Console.Write(\"No Solution exists\" + \"\\n\"); } else { // Print the solution Console.Write(\"x = \" + x * (c / gcd) + \", y = \" + y * (c / gcd) + \"\\n\"); }} // Driver Codepublic static void Main(String[] args){ int a, b, c; // Given coefficients a = 4; b = 18; c = 10; // Function call print_solution(a, b, c);}} // This code contributed by amal kumar choubey", "e": 31615, "s": 30152, "text": null }, { "code": "<script> // Javascript program for the above approach let x, y; // Function to implement the extended// euclid algorithmfunction gcd_extend(a, b){ // Base Case if (b == 0) { x = 1; y = 0; return a; } // Recursively find the gcd else { let g = gcd_extend(b, a % b); let x1 = x, y1 = y; x = y1; y = x1 - Math.floor(a / b) * y1; return g; }} // Function to print the solutions of// the given equations ax + by = cfunction print_solution(a, b, c){ if (a == 0 && b == 0) { // Condition for infinite solutions if (c == 0) { document.write(\"Infinite Solutions \" + \"Exist\" + \"\\n\"); } // Condition for no solutions exist else { document.write(\"No Solution exists\" + \"\\n\"); } } let gcd = gcd_extend(a, b); // Condition for no solutions exist if (c % gcd != 0) { document.write(\"No Solution exists\" + \"\\n\"); } else { // Print the solution document.write(\"x = \" + x * (c / gcd) + \", y = \" + y * (c / gcd) + \"<br/>\"); }} // Driver Code let a, b, c; // Given coefficients a = 4; b = 18; c = 10; // Function Call print_solution(a, b, c); </script>", "e": 33000, "s": 31615, "text": null }, { "code": null, "e": 33015, "s": 33000, "text": "x = -20, y = 5" }, { "code": null, "e": 33150, "s": 33017, "text": "Time Complexity: O(log(max(A, B))), where A and B are the coefficient of x and y in the given linear equation. Auxiliary Space: O(1)" }, { "code": null, "e": 33160, "s": 33150, "text": "Rajput-Ji" }, { "code": null, "e": 33179, "s": 33160, "text": "Amal Kumar Choubey" }, { "code": null, "e": 33188, "s": 33179, "text": "target_2" }, { "code": null, "e": 33199, "s": 33188, "text": "decode2207" }, { "code": null, "e": 33216, "s": 33199, "text": "khushboogoyal499" }, { "code": null, "e": 33224, "s": 33216, "text": "GCD-LCM" }, { "code": null, "e": 33237, "s": 33224, "text": "Mathematical" }, { "code": null, "e": 33250, "s": 33237, "text": "Mathematical" }, { "code": null, "e": 33348, "s": 33250, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33357, "s": 33348, "text": "Comments" }, { "code": null, "e": 33370, "s": 33357, "text": "Old Comments" }, { "code": null, "e": 33394, "s": 33370, "text": "Merge two sorted arrays" }, { "code": null, "e": 33437, "s": 33394, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 33451, "s": 33437, "text": "Prime Numbers" }, { "code": null, "e": 33500, "s": 33451, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 33521, "s": 33500, "text": "Operators in C / C++" }, { "code": null, "e": 33555, "s": 33521, "text": "Program for factorial of a number" }, { "code": null, "e": 33596, "s": 33555, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 33628, "s": 33596, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 33701, "s": 33628, "text": "Print all possible combinations of r elements in a given array of size n" } ]
Find the safe position | Practice | GeeksforGeeks
There was a group of Jewish soldiers who were surrounded by Roman Army in a circular fence. They decided not to get captured by the brutal Roman Army. So, they made a plan. They planned to kill each other. The soldier would kill the fellow soldier next to him on left. They would do so till only one soldier is left and in the last the remained soldier would kill themselves. But there was a problem, soldier A didn’t want to die he want to stay alive so he wanted to stand a position where he could stand till last. After all his fellow soldiers died he would simple surrender himself rather then killing himself. So, given N i,e number of Jewish soldiers, find the safe_position of soldier A. Example 1: Input: N = 10 Output: 5 Explanation: 1 kills 2 : 3 kills 4 : 5 kills 6 : 7 kills 8 : 9 kills 10 Now 1 kills 3 : 5 kills 7 : 9 kills 1 Now 5 kills 9 Example 2: Input: N = 3 Output: 3 Explanation: 1 kills 2 : 3 kills 1 Safe_Position : 3 Your Task: You don't need to read or print anything. Your task is to complete the function find_pos() which takes N as input parameter and returns the safe position for soldier A. Expected Time Complexity: O(log(N)) Expected Space Complexity: O(1) Constraints: 1 <= N <= 100000 0 vikramadityakumar1 month ago def find_pos(self, N): p = 1 while p <= N: p *= 2 return (2 * N) - p + 1 0 Kingshuk Basak5 years ago Kingshuk Basak Program Stopped!! Your program is taking more than 5 sec.Hint : There might be an infinite loop or non-terminating recursion in your code. Need Help Code: #codet=int(input())while(t>0): n=int(input()) d=[] for i in range(1,n+1): d.append(i) j=len(d) while(j>1): if(j%2==0): for i in range(j-1,0,-2): del d[-i] else: for i in range(j-2,0,-2): del d[-i+1] del d[0] j=len(d) print(d[0]) t=t-1 0 sunil maurya5 years ago sunil maurya focus on power of 2 its simple. 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": 923, "s": 226, "text": "There was a group of Jewish soldiers who were surrounded by Roman Army in a circular fence. They decided not to get captured by the brutal Roman Army. So, they made a plan.\nThey planned to kill each other. The soldier would kill the fellow soldier next to him on left. They would do so till only one soldier is left and in the last the remained soldier would kill themselves. But there was a problem, soldier A didn’t want to die he want to stay alive so he wanted to stand a position where he could stand till last. After all his fellow soldiers died he would simple surrender himself rather then killing himself. So, given N i,e number of Jewish soldiers, find the safe_position of soldier A.\n " }, { "code": null, "e": 934, "s": 923, "text": "Example 1:" }, { "code": null, "e": 1086, "s": 934, "text": "Input: N = 10\nOutput: 5\nExplanation: 1 kills 2 : 3 kills 4 : \n5 kills 6 : 7 kills 8 : 9 kills 10\nNow 1 kills 3 : 5 kills 7 : 9 kills 1 \nNow 5 kills 9 \n" }, { "code": null, "e": 1097, "s": 1086, "text": "Example 2:" }, { "code": null, "e": 1175, "s": 1097, "text": "Input: N = 3\nOutput: 3\nExplanation: 1 kills 2 : 3 kills 1\nSafe_Position : 3\n" }, { "code": null, "e": 1359, "s": 1177, "text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function find_pos() which takes N as input parameter and returns the safe position for soldier A.\n " }, { "code": null, "e": 1429, "s": 1359, "text": "Expected Time Complexity: O(log(N))\nExpected Space Complexity: O(1)\n " }, { "code": null, "e": 1461, "s": 1429, "text": "Constraints:\n1 <= N <= 100000\n " }, { "code": null, "e": 1463, "s": 1461, "text": "0" }, { "code": null, "e": 1492, "s": 1463, "text": "vikramadityakumar1 month ago" }, { "code": null, "e": 1598, "s": 1492, "text": "def find_pos(self, N):\n\t p = 1\n while p <= N:\n p *= 2\n return (2 * N) - p + 1" }, { "code": null, "e": 1600, "s": 1598, "text": "0" }, { "code": null, "e": 1626, "s": 1600, "text": "Kingshuk Basak5 years ago" }, { "code": null, "e": 1641, "s": 1626, "text": "Kingshuk Basak" }, { "code": null, "e": 1780, "s": 1641, "text": "Program Stopped!! Your program is taking more than 5 sec.Hint : There might be an infinite loop or non-terminating recursion in your code." }, { "code": null, "e": 1790, "s": 1780, "text": "Need Help" }, { "code": null, "e": 1796, "s": 1790, "text": "Code:" }, { "code": null, "e": 2143, "s": 1796, "text": "#codet=int(input())while(t>0): n=int(input()) d=[] for i in range(1,n+1): d.append(i) j=len(d) while(j>1): if(j%2==0): for i in range(j-1,0,-2): del d[-i] else: for i in range(j-2,0,-2): del d[-i+1] del d[0] j=len(d) print(d[0]) t=t-1" }, { "code": null, "e": 2145, "s": 2143, "text": "0" }, { "code": null, "e": 2169, "s": 2145, "text": "sunil maurya5 years ago" }, { "code": null, "e": 2182, "s": 2169, "text": "sunil maurya" }, { "code": null, "e": 2215, "s": 2182, "text": "focus on power of 2 its simple." }, { "code": null, "e": 2361, "s": 2215, "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": 2397, "s": 2361, "text": " Login to access your submissions. " }, { "code": null, "e": 2407, "s": 2397, "text": "\nProblem\n" }, { "code": null, "e": 2417, "s": 2407, "text": "\nContest\n" }, { "code": null, "e": 2480, "s": 2417, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 2628, "s": 2480, "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": 2836, "s": 2628, "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": 2942, "s": 2836, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Python - Compare Dictionaries on certain Keys - GeeksforGeeks
04 May, 2020 Sometimes, while working with Python dictionaries, we can have a problem in which we need to compare dictionaries for equality on bases in selected keys. This kind of problem is common and has application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using loopThis is brute force way in which this task can be performed. In this, we iterate for both the dictionary and manually test for keys equality using equality operator from selected keys. # Python3 code to demonstrate working of # Compare Dictionaries on certain Keys# Using loop # initializing dictionariestest_dict1 = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'geeks' : 5}test_dict2 = {'gfg' : 2, 'is' : 3, 'best' : 3, 'for' : 7, 'geeks' : 5} # printing original dictionariesprint("The original dictionary 1 : " + str(test_dict1))print("The original dictionary 2 : " + str(test_dict2)) # initializing compare keys comp_keys = ['best', 'geeks'] # Compare Dictionaries on certain Keys# Using loopres = Truefor key in comp_keys: if test_dict1.get(key) != test_dict2.get(key): res = False break # printing result print("Are dictionary equal : " + str(res)) The original dictionary 1 : {‘geeks’: 5, ‘gfg’: 1, ‘is’: 2, ‘for’: 4, ‘best’: 3}The original dictionary 2 : {‘geeks’: 5, ‘gfg’: 2, ‘is’: 3, ‘for’: 7, ‘best’: 3}Are dictionary equal : True Method #2 : Using all()This is one liner alternative to perform this task. In this the functionality of comparison is done using all(), comparing all required keys. # Python3 code to demonstrate working of # Compare Dictionaries on certain Keys# Using all() # initializing dictionariestest_dict1 = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'geeks' : 5}test_dict2 = {'gfg' : 2, 'is' : 3, 'best' : 3, 'for' : 7, 'geeks' : 5} # printing original dictionariesprint("The original dictionary 1 : " + str(test_dict1))print("The original dictionary 2 : " + str(test_dict2)) # initializing compare keys comp_keys = ['best', 'geeks'] # Compare Dictionaries on certain Keys# Using all()res = all(test_dict1.get(key) == test_dict2.get(key) for key in comp_keys) # printing result print("Are dictionary equal : " + str(res)) The original dictionary 1 : {‘geeks’: 5, ‘gfg’: 1, ‘is’: 2, ‘for’: 4, ‘best’: 3}The original dictionary 2 : {‘geeks’: 5, ‘gfg’: 2, ‘is’: 3, ‘for’: 7, ‘best’: 3}Are dictionary equal : True Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26341, "s": 26313, "text": "\n04 May, 2020" }, { "code": null, "e": 26626, "s": 26341, "text": "Sometimes, while working with Python dictionaries, we can have a problem in which we need to compare dictionaries for equality on bases in selected keys. This kind of problem is common and has application in many domains. Lets discuss certain ways in which this task can be performed." }, { "code": null, "e": 26833, "s": 26626, "text": "Method #1 : Using loopThis is brute force way in which this task can be performed. In this, we iterate for both the dictionary and manually test for keys equality using equality operator from selected keys." }, { "code": "# Python3 code to demonstrate working of # Compare Dictionaries on certain Keys# Using loop # initializing dictionariestest_dict1 = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'geeks' : 5}test_dict2 = {'gfg' : 2, 'is' : 3, 'best' : 3, 'for' : 7, 'geeks' : 5} # printing original dictionariesprint(\"The original dictionary 1 : \" + str(test_dict1))print(\"The original dictionary 2 : \" + str(test_dict2)) # initializing compare keys comp_keys = ['best', 'geeks'] # Compare Dictionaries on certain Keys# Using loopres = Truefor key in comp_keys: if test_dict1.get(key) != test_dict2.get(key): res = False break # printing result print(\"Are dictionary equal : \" + str(res)) ", "e": 27531, "s": 26833, "text": null }, { "code": null, "e": 27719, "s": 27531, "text": "The original dictionary 1 : {‘geeks’: 5, ‘gfg’: 1, ‘is’: 2, ‘for’: 4, ‘best’: 3}The original dictionary 2 : {‘geeks’: 5, ‘gfg’: 2, ‘is’: 3, ‘for’: 7, ‘best’: 3}Are dictionary equal : True" }, { "code": null, "e": 27886, "s": 27721, "text": "Method #2 : Using all()This is one liner alternative to perform this task. In this the functionality of comparison is done using all(), comparing all required keys." }, { "code": "# Python3 code to demonstrate working of # Compare Dictionaries on certain Keys# Using all() # initializing dictionariestest_dict1 = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'geeks' : 5}test_dict2 = {'gfg' : 2, 'is' : 3, 'best' : 3, 'for' : 7, 'geeks' : 5} # printing original dictionariesprint(\"The original dictionary 1 : \" + str(test_dict1))print(\"The original dictionary 2 : \" + str(test_dict2)) # initializing compare keys comp_keys = ['best', 'geeks'] # Compare Dictionaries on certain Keys# Using all()res = all(test_dict1.get(key) == test_dict2.get(key) for key in comp_keys) # printing result print(\"Are dictionary equal : \" + str(res)) ", "e": 28546, "s": 27886, "text": null }, { "code": null, "e": 28734, "s": 28546, "text": "The original dictionary 1 : {‘geeks’: 5, ‘gfg’: 1, ‘is’: 2, ‘for’: 4, ‘best’: 3}The original dictionary 2 : {‘geeks’: 5, ‘gfg’: 2, ‘is’: 3, ‘for’: 7, ‘best’: 3}Are dictionary equal : True" }, { "code": null, "e": 28761, "s": 28734, "text": "Python dictionary-programs" }, { "code": null, "e": 28768, "s": 28761, "text": "Python" }, { "code": null, "e": 28784, "s": 28768, "text": "Python Programs" }, { "code": null, "e": 28882, "s": 28784, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28900, "s": 28882, "text": "Python Dictionary" }, { "code": null, "e": 28935, "s": 28900, "text": "Read a file line by line in Python" }, { "code": null, "e": 28967, "s": 28935, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28989, "s": 28967, "text": "Enumerate() in Python" }, { "code": null, "e": 29031, "s": 28989, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29074, "s": 29031, "text": "Python program to convert a list to string" }, { "code": null, "e": 29096, "s": 29074, "text": "Defaultdict in Python" }, { "code": null, "e": 29135, "s": 29096, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 29181, "s": 29135, "text": "Python | Split string into list of characters" } ]
Number System: Cyclicity of Numbers - GeeksforGeeks
21 Oct, 2021 Number System is a method of representing numbers on the number line with the help of a set of symbols and rules. These symbols range from 0-9 and are termed digits. The Number System is used to perform mathematical computations ranging from great scientific calculations to calculations like counting the number of Toys for a Kid or the number of chocolates remaining in the box. Number systems comprise multiple types based on the base value for their digits. Cyclicity Of Numbers: The cyclicity of any number is focused on its unit digit mainly. Every unit digit has its own repetitive pattern when raised to any power. This concept is of tremendous use while solving aptitude problems. The concept of cyclicity of numbers can be learned by figuring out the unit digits of all the single-digit numbers from 0 to 9 when raised to certain powers. These numbers can be broadly classified into three categories listed as follows: 1. Digits 0, 1, 5, and 6: Here, when each of these digits is raised to any power, the unit digit of the final answer is the number itself. Examples: 1. 5 ^ 2 = 25: Unit digit is 5, the number itself. 2. 1 ^ 6 = 1: Unit digit is 1, the number itself. 3. 0 ^ 4 = 0: Unit digit is 0, the number itself. 4. 6 ^ 3 = 216: Unit digit is 6, the number itself. Below are some questions based on the above concept: Question 1: Find the unit digit of 416345. Answer: Simply find 6345 which will give 6 as a unit digit, hence the unit digit of 416345 is 6. Question 2: Find the unit digit of 23534566. Answer: Find 534566 which will give 5 as a unit digit, hence the unit digit of 23534566 is 5. 2. Digits 4 and 9: Both of these two digits, 4 and 9, have a cyclicity of two different digits as their unit digit. Examples: 1. 4 ^ 2 = 16: Unit digit is 6. 2. 4 ^ 3 = 64: Unit digit is 4. 3. 4 ^ 4 = 256: Unit digit is 6. 4. 4 ^ 5 = 1024: Unit digit is 4. 5. 9 ^ 2 = 81: Unit digit is 1. 6. 9 ^ 3 = 729: Unit digit is 9. It can be observed that the unit digits 6 and4 are repeating in an odd-even order. So, 4 has a cyclicity of 2. Similar is the case with 9. It can be generalized as follows: 4odd = 4: If 4 is raised to the power of an odd number, then the unit digit will be 4. 4even = 6: If 4 is raised to the power of an even number, then the unit digit will be 6. 9odd = 9: If 9 is raised to the power of an odd number, then the unit digit will be 9. 9even = 1: If 9 is raised to the power of an even number, then the unit digit will be 1. Below are some questions based on the above concept: Question 1: Find the unit digit of 41423. Answer: 23 is an odd number, so 4odd=4, hence the unit digit is 4. Question 2: Find the unit digit of 2982. Answer: 82 is an even number, so 9even=1, hence the unit digit is 1. 3. Digits 2, 3, 7, and 8: These numbers have a cyclicity of four different numbers. Examples: 1. 2 ^ 1 = 2: Unit digit is 2. 2. 2 ^ 2 = 4: Unit digit is 4. 3. 2 ^ 3 = 8: Unit digit is 8. 4. 2 ^ 4 = 16: Unit digit is 6. 5. 2 ^ 5 = 32: Unit digit is 2. 6. 2 ^ 6 = 64: Unit digit is 4. It can be observed that the unit digits 2, 4, 8, 6 repeats themselves after a period of four numbers. Similarly, The cyclicity of 3 has 4 different numbers: 3, 9, 7, 1. The cyclicity of 7 has 4 different numbers: 7, 9, 3, 1. The cyclicity of 8 has 4 different numbers: 8, 4, 2, 4. Below are some questions based on the above concept: Question 1: Find the unit digit of 257345. Answer: 345 % 4 = 1, so 71, hence the unit digit is 7. Question 2: Find the unit digit of 42343. Answer: 43 % 4 = 3, so 33, hence 7 is the unit digit. Question 3: Find the unit digit of 28146. Answer: 146 % 4 = 2, so 82, hence the unit digit is 4. Cyclicity Table: The concepts discussed above can be summarized as: Aptitude number-theory Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Modulo Operator (%) in C/C++ with Examples Merge two sorted arrays Program to find sum of elements in a given array Operators in C / C++ Program for factorial of a number Algorithm to solve Rubik's Cube Print all possible combinations of r elements in a given array of size n The Knight's tour problem | Backtracking-1 Minimum number of jumps to reach end Find minimum number of coins that make a given value
[ { "code": null, "e": 24470, "s": 24442, "text": "\n21 Oct, 2021" }, { "code": null, "e": 24932, "s": 24470, "text": "Number System is a method of representing numbers on the number line with the help of a set of symbols and rules. These symbols range from 0-9 and are termed digits. The Number System is used to perform mathematical computations ranging from great scientific calculations to calculations like counting the number of Toys for a Kid or the number of chocolates remaining in the box. Number systems comprise multiple types based on the base value for their digits." }, { "code": null, "e": 25399, "s": 24932, "text": "Cyclicity Of Numbers: The cyclicity of any number is focused on its unit digit mainly. Every unit digit has its own repetitive pattern when raised to any power. This concept is of tremendous use while solving aptitude problems. The concept of cyclicity of numbers can be learned by figuring out the unit digits of all the single-digit numbers from 0 to 9 when raised to certain powers. These numbers can be broadly classified into three categories listed as follows:" }, { "code": null, "e": 25538, "s": 25399, "text": "1. Digits 0, 1, 5, and 6: Here, when each of these digits is raised to any power, the unit digit of the final answer is the number itself." }, { "code": null, "e": 25548, "s": 25538, "text": "Examples:" }, { "code": null, "e": 25751, "s": 25548, "text": "1. 5 ^ 2 = 25: Unit digit is 5, the number itself.\n2. 1 ^ 6 = 1: Unit digit is 1, the number itself.\n3. 0 ^ 4 = 0: Unit digit is 0, the number itself.\n4. 6 ^ 3 = 216: Unit digit is 6, the number itself." }, { "code": null, "e": 25804, "s": 25751, "text": "Below are some questions based on the above concept:" }, { "code": null, "e": 25847, "s": 25804, "text": "Question 1: Find the unit digit of 416345." }, { "code": null, "e": 25944, "s": 25847, "text": "Answer: Simply find 6345 which will give 6 as a unit digit, hence the unit digit of 416345 is 6." }, { "code": null, "e": 25989, "s": 25944, "text": "Question 2: Find the unit digit of 23534566." }, { "code": null, "e": 26083, "s": 25989, "text": "Answer: Find 534566 which will give 5 as a unit digit, hence the unit digit of 23534566 is 5." }, { "code": null, "e": 26199, "s": 26083, "text": "2. Digits 4 and 9: Both of these two digits, 4 and 9, have a cyclicity of two different digits as their unit digit." }, { "code": null, "e": 26209, "s": 26199, "text": "Examples:" }, { "code": null, "e": 26405, "s": 26209, "text": "1. 4 ^ 2 = 16: Unit digit is 6.\n2. 4 ^ 3 = 64: Unit digit is 4.\n3. 4 ^ 4 = 256: Unit digit is 6.\n4. 4 ^ 5 = 1024: Unit digit is 4.\n5. 9 ^ 2 = 81: Unit digit is 1.\n6. 9 ^ 3 = 729: Unit digit is 9." }, { "code": null, "e": 26544, "s": 26405, "text": "It can be observed that the unit digits 6 and4 are repeating in an odd-even order. So, 4 has a cyclicity of 2. Similar is the case with 9." }, { "code": null, "e": 26578, "s": 26544, "text": "It can be generalized as follows:" }, { "code": null, "e": 26665, "s": 26578, "text": "4odd = 4: If 4 is raised to the power of an odd number, then the unit digit will be 4." }, { "code": null, "e": 26754, "s": 26665, "text": "4even = 6: If 4 is raised to the power of an even number, then the unit digit will be 6." }, { "code": null, "e": 26841, "s": 26754, "text": "9odd = 9: If 9 is raised to the power of an odd number, then the unit digit will be 9." }, { "code": null, "e": 26930, "s": 26841, "text": "9even = 1: If 9 is raised to the power of an even number, then the unit digit will be 1." }, { "code": null, "e": 26983, "s": 26930, "text": "Below are some questions based on the above concept:" }, { "code": null, "e": 27025, "s": 26983, "text": "Question 1: Find the unit digit of 41423." }, { "code": null, "e": 27092, "s": 27025, "text": "Answer: 23 is an odd number, so 4odd=4, hence the unit digit is 4." }, { "code": null, "e": 27133, "s": 27092, "text": "Question 2: Find the unit digit of 2982." }, { "code": null, "e": 27202, "s": 27133, "text": "Answer: 82 is an even number, so 9even=1, hence the unit digit is 1." }, { "code": null, "e": 27286, "s": 27202, "text": "3. Digits 2, 3, 7, and 8: These numbers have a cyclicity of four different numbers." }, { "code": null, "e": 27296, "s": 27286, "text": "Examples:" }, { "code": null, "e": 27485, "s": 27296, "text": "1. 2 ^ 1 = 2: Unit digit is 2.\n2. 2 ^ 2 = 4: Unit digit is 4.\n3. 2 ^ 3 = 8: Unit digit is 8.\n4. 2 ^ 4 = 16: Unit digit is 6.\n5. 2 ^ 5 = 32: Unit digit is 2.\n6. 2 ^ 6 = 64: Unit digit is 4." }, { "code": null, "e": 27598, "s": 27485, "text": "It can be observed that the unit digits 2, 4, 8, 6 repeats themselves after a period of four numbers. Similarly," }, { "code": null, "e": 27654, "s": 27598, "text": "The cyclicity of 3 has 4 different numbers: 3, 9, 7, 1." }, { "code": null, "e": 27710, "s": 27654, "text": "The cyclicity of 7 has 4 different numbers: 7, 9, 3, 1." }, { "code": null, "e": 27766, "s": 27710, "text": "The cyclicity of 8 has 4 different numbers: 8, 4, 2, 4." }, { "code": null, "e": 27819, "s": 27766, "text": "Below are some questions based on the above concept:" }, { "code": null, "e": 27862, "s": 27819, "text": "Question 1: Find the unit digit of 257345." }, { "code": null, "e": 27917, "s": 27862, "text": "Answer: 345 % 4 = 1, so 71, hence the unit digit is 7." }, { "code": null, "e": 27959, "s": 27917, "text": "Question 2: Find the unit digit of 42343." }, { "code": null, "e": 28013, "s": 27959, "text": "Answer: 43 % 4 = 3, so 33, hence 7 is the unit digit." }, { "code": null, "e": 28055, "s": 28013, "text": "Question 3: Find the unit digit of 28146." }, { "code": null, "e": 28110, "s": 28055, "text": "Answer: 146 % 4 = 2, so 82, hence the unit digit is 4." }, { "code": null, "e": 28178, "s": 28110, "text": "Cyclicity Table: The concepts discussed above can be summarized as:" }, { "code": null, "e": 28187, "s": 28178, "text": "Aptitude" }, { "code": null, "e": 28201, "s": 28187, "text": "number-theory" }, { "code": null, "e": 28214, "s": 28201, "text": "Mathematical" }, { "code": null, "e": 28228, "s": 28214, "text": "number-theory" }, { "code": null, "e": 28241, "s": 28228, "text": "Mathematical" }, { "code": null, "e": 28339, "s": 28241, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28348, "s": 28339, "text": "Comments" }, { "code": null, "e": 28361, "s": 28348, "text": "Old Comments" }, { "code": null, "e": 28404, "s": 28361, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 28428, "s": 28404, "text": "Merge two sorted arrays" }, { "code": null, "e": 28477, "s": 28428, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 28498, "s": 28477, "text": "Operators in C / C++" }, { "code": null, "e": 28532, "s": 28498, "text": "Program for factorial of a number" }, { "code": null, "e": 28564, "s": 28532, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 28637, "s": 28564, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 28680, "s": 28637, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 28717, "s": 28680, "text": "Minimum number of jumps to reach end" } ]
Red-Black Tree | Set 3 (Delete) - GeeksforGeeks
23 Dec, 2021 We have discussed the following topics on the Red-Black tree in previous posts. We strongly recommend referring following post as a prerequisite of this post.Red-Black Tree Introduction Red Black Tree InsertInsertion Vs Deletion: Like Insertion, recoloring and rotations are used to maintain the Red-Black properties.In the insert operation, we check the color of the uncle to decide the appropriate case. In the delete operation, we check the color of the sibling to decide the appropriate case.The main property that violates after insertion is two consecutive reds. In delete, the main violated property is, change of black height in subtrees as deletion of a black node may cause reduced black height in one root to leaf path.Deletion is a fairly complex process. To understand deletion, the notion of double black is used. When a black node is deleted and replaced by a black child, the child is marked as double black. The main task now becomes to convert this double black to single black.Deletion Steps Following are detailed steps for deletion.1) Perform standard BST delete. When we perform standard delete operation in BST, we always end up deleting a node which is an either leaf or has only one child (For an internal node, we copy the successor and then recursively call delete for successor, successor is always a leaf node or a node with one child). So we only need to handle cases where a node is leaf or has one child. Let v be the node to be deleted and u be the child that replaces v (Note that u is NULL when v is a leaf and color of NULL is considered as Black).2) Simple Case: If either u or v is red, we mark the replaced child as black (No change in black height). Note that both u and v cannot be red as v is parent of u and two consecutive reds are not allowed in red-black tree. 3) If Both u and v are Black.3.1) Color u as double black. Now our task reduces to convert this double black to single black. Note that If v is leaf, then u is NULL and color of NULL is considered black. So the deletion of a black leaf also causes a double black. 3.2) Do following while the current node u is double black, and it is not the root. Let sibling of node be s. ....(a): If sibling s is black and at least one of sibling’s children is red, perform rotation(s). Let the red child of s be r. This case can be divided in four subcases depending upon positions of s and r...............(i) Left Left Case (s is left child of its parent and r is left child of s or both children of s are red). This is mirror of right right case shown in below diagram...............(ii) Left Right Case (s is left child of its parent and r is right child). This is mirror of right left case shown in below diagram...............(iii) Right Right Case (s is right child of its parent and r is right child of s or both children of s are red) ..............(iv) Right Left Case (s is right child of its parent and r is left child of s) .....(b): If sibling is black and its both children are black, perform recoloring, and recur for the parent if parent is black. In this case, if parent was red, then we didn’t need to recur for parent, we can simply make it black (red + double black = single black).....(c): If sibling is red, perform a rotation to move old sibling up, recolor the old sibling and parent. The new sibling is always black (See the below diagram). This mainly converts the tree to black sibling case (by rotation) and leads to case (a) or (b). This case can be divided in two subcases. ..............(i) Left Case (s is left child of its parent). This is mirror of right right case shown in below diagram. We right rotate the parent p. ..............(ii) Right Case (s is right child of its parent). We left rotate the parent p. 3.3) If u is root, make it single black and return (Black height of complete tree reduces by 1).below is the C++ implementation of above approach: CPP #include <iostream>#include <queue>using namespace std; enum COLOR { RED, BLACK }; class Node {public: int val; COLOR color; Node *left, *right, *parent; Node(int val) : val(val) { parent = left = right = NULL; // Node is created during insertion // Node is red at insertion color = RED; } // returns pointer to uncle Node *uncle() { // If no parent or grandparent, then no uncle if (parent == NULL or parent->parent == NULL) return NULL; if (parent->isOnLeft()) // uncle on right return parent->parent->right; else // uncle on left return parent->parent->left; } // check if node is left child of parent bool isOnLeft() { return this == parent->left; } // returns pointer to sibling Node *sibling() { // sibling null if no parent if (parent == NULL) return NULL; if (isOnLeft()) return parent->right; return parent->left; } // moves node down and moves given node in its place void moveDown(Node *nParent) { if (parent != NULL) { if (isOnLeft()) { parent->left = nParent; } else { parent->right = nParent; } } nParent->parent = parent; parent = nParent; } bool hasRedChild() { return (left != NULL and left->color == RED) or (right != NULL and right->color == RED); }}; class RBTree { Node *root; // left rotates the given node void leftRotate(Node *x) { // new parent will be node's right child Node *nParent = x->right; // update root if current node is root if (x == root) root = nParent; x->moveDown(nParent); // connect x with new parent's left element x->right = nParent->left; // connect new parent's left element with node // if it is not null if (nParent->left != NULL) nParent->left->parent = x; // connect new parent with x nParent->left = x; } void rightRotate(Node *x) { // new parent will be node's left child Node *nParent = x->left; // update root if current node is root if (x == root) root = nParent; x->moveDown(nParent); // connect x with new parent's right element x->left = nParent->right; // connect new parent's right element with node // if it is not null if (nParent->right != NULL) nParent->right->parent = x; // connect new parent with x nParent->right = x; } void swapColors(Node *x1, Node *x2) { COLOR temp; temp = x1->color; x1->color = x2->color; x2->color = temp; } void swapValues(Node *u, Node *v) { int temp; temp = u->val; u->val = v->val; v->val = temp; } // fix red red at given node void fixRedRed(Node *x) { // if x is root color it black and return if (x == root) { x->color = BLACK; return; } // initialize parent, grandparent, uncle Node *parent = x->parent, *grandparent = parent->parent, *uncle = x->uncle(); if (parent->color != BLACK) { if (uncle != NULL && uncle->color == RED) { // uncle red, perform recoloring and recurse parent->color = BLACK; uncle->color = BLACK; grandparent->color = RED; fixRedRed(grandparent); } else { // Else perform LR, LL, RL, RR if (parent->isOnLeft()) { if (x->isOnLeft()) { // for left right swapColors(parent, grandparent); } else { leftRotate(parent); swapColors(x, grandparent); } // for left left and left right rightRotate(grandparent); } else { if (x->isOnLeft()) { // for right left rightRotate(parent); swapColors(x, grandparent); } else { swapColors(parent, grandparent); } // for right right and right left leftRotate(grandparent); } } } } // find node that do not have a left child // in the subtree of the given node Node *successor(Node *x) { Node *temp = x; while (temp->left != NULL) temp = temp->left; return temp; } // find node that replaces a deleted node in BST Node *BSTreplace(Node *x) { // when node have 2 children if (x->left != NULL and x->right != NULL) return successor(x->right); // when leaf if (x->left == NULL and x->right == NULL) return NULL; // when single child if (x->left != NULL) return x->left; else return x->right; } // deletes the given node void deleteNode(Node *v) { Node *u = BSTreplace(v); // True when u and v are both black bool uvBlack = ((u == NULL or u->color == BLACK) and (v->color == BLACK)); Node *parent = v->parent; if (u == NULL) { // u is NULL therefore v is leaf if (v == root) { // v is root, making root null root = NULL; } else { if (uvBlack) { // u and v both black // v is leaf, fix double black at v fixDoubleBlack(v); } else { // u or v is red if (v->sibling() != NULL) // sibling is not null, make it red" v->sibling()->color = RED; } // delete v from the tree if (v->isOnLeft()) { parent->left = NULL; } else { parent->right = NULL; } } delete v; return; } if (v->left == NULL or v->right == NULL) { // v has 1 child if (v == root) { // v is root, assign the value of u to v, and delete u v->val = u->val; v->left = v->right = NULL; delete u; } else { // Detach v from tree and move u up if (v->isOnLeft()) { parent->left = u; } else { parent->right = u; } delete v; u->parent = parent; if (uvBlack) { // u and v both black, fix double black at u fixDoubleBlack(u); } else { // u or v red, color u black u->color = BLACK; } } return; } // v has 2 children, swap values with successor and recurse swapValues(u, v); deleteNode(u); } void fixDoubleBlack(Node *x) { if (x == root) // Reached root return; Node *sibling = x->sibling(), *parent = x->parent; if (sibling == NULL) { // No sibiling, double black pushed up fixDoubleBlack(parent); } else { if (sibling->color == RED) { // Sibling red parent->color = RED; sibling->color = BLACK; if (sibling->isOnLeft()) { // left case rightRotate(parent); } else { // right case leftRotate(parent); } fixDoubleBlack(x); } else { // Sibling black if (sibling->hasRedChild()) { // at least 1 red children if (sibling->left != NULL and sibling->left->color == RED) { if (sibling->isOnLeft()) { // left left sibling->left->color = sibling->color; sibling->color = parent->color; rightRotate(parent); } else { // right left sibling->left->color = parent->color; rightRotate(sibling); leftRotate(parent); } } else { if (sibling->isOnLeft()) { // left right sibling->right->color = parent->color; leftRotate(sibling); rightRotate(parent); } else { // right right sibling->right->color = sibling->color; sibling->color = parent->color; leftRotate(parent); } } parent->color = BLACK; } else { // 2 black children sibling->color = RED; if (parent->color == BLACK) fixDoubleBlack(parent); else parent->color = BLACK; } } } } // prints level order for given node void levelOrder(Node *x) { if (x == NULL) // return if node is null return; // queue for level order queue<Node *> q; Node *curr; // push x q.push(x); while (!q.empty()) { // while q is not empty // dequeue curr = q.front(); q.pop(); // print node value cout << curr->val << " "; // push children to queue if (curr->left != NULL) q.push(curr->left); if (curr->right != NULL) q.push(curr->right); } } // prints inorder recursively void inorder(Node *x) { if (x == NULL) return; inorder(x->left); cout << x->val << " "; inorder(x->right); } public: // constructor // initialize root RBTree() { root = NULL; } Node *getRoot() { return root; } // searches for given value // if found returns the node (used for delete) // else returns the last node while traversing (used in insert) Node *search(int n) { Node *temp = root; while (temp != NULL) { if (n < temp->val) { if (temp->left == NULL) break; else temp = temp->left; } else if (n == temp->val) { break; } else { if (temp->right == NULL) break; else temp = temp->right; } } return temp; } // inserts the given value to tree void insert(int n) { Node *newNode = new Node(n); if (root == NULL) { // when root is null // simply insert value at root newNode->color = BLACK; root = newNode; } else { Node *temp = search(n); if (temp->val == n) { // return if value already exists return; } // if value is not found, search returns the node // where the value is to be inserted // connect new node to correct node newNode->parent = temp; if (n < temp->val) temp->left = newNode; else temp->right = newNode; // fix red red voilaton if exists fixRedRed(newNode); } } // utility function that deletes the node with given value void deleteByVal(int n) { if (root == NULL) // Tree is empty return; Node *v = search(n), *u; if (v->val != n) { cout << "No node found to delete with value:" << n << endl; return; } deleteNode(v); } // prints inorder of the tree void printInOrder() { cout << "Inorder: " << endl; if (root == NULL) cout << "Tree is empty" << endl; else inorder(root); cout << endl; } // prints level order of the tree void printLevelOrder() { cout << "Level order: " << endl; if (root == NULL) cout << "Tree is empty" << endl; else levelOrder(root); cout << endl; }}; int main() { RBTree tree; tree.insert(7); tree.insert(3); tree.insert(18); tree.insert(10); tree.insert(22); tree.insert(8); tree.insert(11); tree.insert(26); tree.insert(2); tree.insert(6); tree.insert(13); tree.printInOrder(); tree.printLevelOrder(); cout<<endl<<"Deleting 18, 11, 3, 10, 22"<<endl; tree.deleteByVal(18); tree.deleteByVal(11); tree.deleteByVal(3); tree.deleteByVal(10); tree.deleteByVal(22); tree.printInOrder(); tree.printLevelOrder(); return 0;} Output: Inorder: 2 3 6 7 8 10 11 13 18 22 26 Level order: 10 7 18 3 8 11 22 2 6 13 26 Deleting 18, 11, 3, 10, 22 Inorder: 2 6 7 8 13 26 Level order: 13 7 26 6 8 2 References: https://www.cs.purdue.edu/homes/ayg/CS251/slides/chap13c.pdf Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. RivestPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above shwetanknaveen BhanuPratapSinghRathore govindtomar94 kuldeepy10459 Red Black Tree Self-Balancing-BST Advanced Data Structure Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Agents in Artificial Intelligence Decision Tree Introduction with example Segment Tree | Set 1 (Sum of given range) Disjoint Set Data Structures Ordered Set and GNU C++ PBDS Insert Operation in B-Tree Binary Indexed Tree or Fenwick Tree Binomial Heap Design a Chess Game Difference between B tree and B+ tree
[ { "code": null, "e": 26143, "s": 26115, "text": "\n23 Dec, 2021" }, { "code": null, "e": 27954, "s": 26143, "text": "We have discussed the following topics on the Red-Black tree in previous posts. We strongly recommend referring following post as a prerequisite of this post.Red-Black Tree Introduction Red Black Tree InsertInsertion Vs Deletion: Like Insertion, recoloring and rotations are used to maintain the Red-Black properties.In the insert operation, we check the color of the uncle to decide the appropriate case. In the delete operation, we check the color of the sibling to decide the appropriate case.The main property that violates after insertion is two consecutive reds. In delete, the main violated property is, change of black height in subtrees as deletion of a black node may cause reduced black height in one root to leaf path.Deletion is a fairly complex process. To understand deletion, the notion of double black is used. When a black node is deleted and replaced by a black child, the child is marked as double black. The main task now becomes to convert this double black to single black.Deletion Steps Following are detailed steps for deletion.1) Perform standard BST delete. When we perform standard delete operation in BST, we always end up deleting a node which is an either leaf or has only one child (For an internal node, we copy the successor and then recursively call delete for successor, successor is always a leaf node or a node with one child). So we only need to handle cases where a node is leaf or has one child. Let v be the node to be deleted and u be the child that replaces v (Note that u is NULL when v is a leaf and color of NULL is considered as Black).2) Simple Case: If either u or v is red, we mark the replaced child as black (No change in black height). Note that both u and v cannot be red as v is parent of u and two consecutive reds are not allowed in red-black tree. " }, { "code": null, "e": 28220, "s": 27954, "text": "3) If Both u and v are Black.3.1) Color u as double black. Now our task reduces to convert this double black to single black. Note that If v is leaf, then u is NULL and color of NULL is considered black. So the deletion of a black leaf also causes a double black. " }, { "code": null, "e": 28989, "s": 28220, "text": "3.2) Do following while the current node u is double black, and it is not the root. Let sibling of node be s. ....(a): If sibling s is black and at least one of sibling’s children is red, perform rotation(s). Let the red child of s be r. This case can be divided in four subcases depending upon positions of s and r...............(i) Left Left Case (s is left child of its parent and r is left child of s or both children of s are red). This is mirror of right right case shown in below diagram...............(ii) Left Right Case (s is left child of its parent and r is right child). This is mirror of right left case shown in below diagram...............(iii) Right Right Case (s is right child of its parent and r is right child of s or both children of s are red) " }, { "code": null, "e": 29084, "s": 28989, "text": "..............(iv) Right Left Case (s is right child of its parent and r is left child of s) " }, { "code": null, "e": 29214, "s": 29084, "text": ".....(b): If sibling is black and its both children are black, perform recoloring, and recur for the parent if parent is black. " }, { "code": null, "e": 29899, "s": 29214, "text": "In this case, if parent was red, then we didn’t need to recur for parent, we can simply make it black (red + double black = single black).....(c): If sibling is red, perform a rotation to move old sibling up, recolor the old sibling and parent. The new sibling is always black (See the below diagram). This mainly converts the tree to black sibling case (by rotation) and leads to case (a) or (b). This case can be divided in two subcases. ..............(i) Left Case (s is left child of its parent). This is mirror of right right case shown in below diagram. We right rotate the parent p. ..............(ii) Right Case (s is right child of its parent). We left rotate the parent p. " }, { "code": null, "e": 30048, "s": 29899, "text": "3.3) If u is root, make it single black and return (Black height of complete tree reduces by 1).below is the C++ implementation of above approach: " }, { "code": null, "e": 30052, "s": 30048, "text": "CPP" }, { "code": "#include <iostream>#include <queue>using namespace std; enum COLOR { RED, BLACK }; class Node {public: int val; COLOR color; Node *left, *right, *parent; Node(int val) : val(val) { parent = left = right = NULL; // Node is created during insertion // Node is red at insertion color = RED; } // returns pointer to uncle Node *uncle() { // If no parent or grandparent, then no uncle if (parent == NULL or parent->parent == NULL) return NULL; if (parent->isOnLeft()) // uncle on right return parent->parent->right; else // uncle on left return parent->parent->left; } // check if node is left child of parent bool isOnLeft() { return this == parent->left; } // returns pointer to sibling Node *sibling() { // sibling null if no parent if (parent == NULL) return NULL; if (isOnLeft()) return parent->right; return parent->left; } // moves node down and moves given node in its place void moveDown(Node *nParent) { if (parent != NULL) { if (isOnLeft()) { parent->left = nParent; } else { parent->right = nParent; } } nParent->parent = parent; parent = nParent; } bool hasRedChild() { return (left != NULL and left->color == RED) or (right != NULL and right->color == RED); }}; class RBTree { Node *root; // left rotates the given node void leftRotate(Node *x) { // new parent will be node's right child Node *nParent = x->right; // update root if current node is root if (x == root) root = nParent; x->moveDown(nParent); // connect x with new parent's left element x->right = nParent->left; // connect new parent's left element with node // if it is not null if (nParent->left != NULL) nParent->left->parent = x; // connect new parent with x nParent->left = x; } void rightRotate(Node *x) { // new parent will be node's left child Node *nParent = x->left; // update root if current node is root if (x == root) root = nParent; x->moveDown(nParent); // connect x with new parent's right element x->left = nParent->right; // connect new parent's right element with node // if it is not null if (nParent->right != NULL) nParent->right->parent = x; // connect new parent with x nParent->right = x; } void swapColors(Node *x1, Node *x2) { COLOR temp; temp = x1->color; x1->color = x2->color; x2->color = temp; } void swapValues(Node *u, Node *v) { int temp; temp = u->val; u->val = v->val; v->val = temp; } // fix red red at given node void fixRedRed(Node *x) { // if x is root color it black and return if (x == root) { x->color = BLACK; return; } // initialize parent, grandparent, uncle Node *parent = x->parent, *grandparent = parent->parent, *uncle = x->uncle(); if (parent->color != BLACK) { if (uncle != NULL && uncle->color == RED) { // uncle red, perform recoloring and recurse parent->color = BLACK; uncle->color = BLACK; grandparent->color = RED; fixRedRed(grandparent); } else { // Else perform LR, LL, RL, RR if (parent->isOnLeft()) { if (x->isOnLeft()) { // for left right swapColors(parent, grandparent); } else { leftRotate(parent); swapColors(x, grandparent); } // for left left and left right rightRotate(grandparent); } else { if (x->isOnLeft()) { // for right left rightRotate(parent); swapColors(x, grandparent); } else { swapColors(parent, grandparent); } // for right right and right left leftRotate(grandparent); } } } } // find node that do not have a left child // in the subtree of the given node Node *successor(Node *x) { Node *temp = x; while (temp->left != NULL) temp = temp->left; return temp; } // find node that replaces a deleted node in BST Node *BSTreplace(Node *x) { // when node have 2 children if (x->left != NULL and x->right != NULL) return successor(x->right); // when leaf if (x->left == NULL and x->right == NULL) return NULL; // when single child if (x->left != NULL) return x->left; else return x->right; } // deletes the given node void deleteNode(Node *v) { Node *u = BSTreplace(v); // True when u and v are both black bool uvBlack = ((u == NULL or u->color == BLACK) and (v->color == BLACK)); Node *parent = v->parent; if (u == NULL) { // u is NULL therefore v is leaf if (v == root) { // v is root, making root null root = NULL; } else { if (uvBlack) { // u and v both black // v is leaf, fix double black at v fixDoubleBlack(v); } else { // u or v is red if (v->sibling() != NULL) // sibling is not null, make it red\" v->sibling()->color = RED; } // delete v from the tree if (v->isOnLeft()) { parent->left = NULL; } else { parent->right = NULL; } } delete v; return; } if (v->left == NULL or v->right == NULL) { // v has 1 child if (v == root) { // v is root, assign the value of u to v, and delete u v->val = u->val; v->left = v->right = NULL; delete u; } else { // Detach v from tree and move u up if (v->isOnLeft()) { parent->left = u; } else { parent->right = u; } delete v; u->parent = parent; if (uvBlack) { // u and v both black, fix double black at u fixDoubleBlack(u); } else { // u or v red, color u black u->color = BLACK; } } return; } // v has 2 children, swap values with successor and recurse swapValues(u, v); deleteNode(u); } void fixDoubleBlack(Node *x) { if (x == root) // Reached root return; Node *sibling = x->sibling(), *parent = x->parent; if (sibling == NULL) { // No sibiling, double black pushed up fixDoubleBlack(parent); } else { if (sibling->color == RED) { // Sibling red parent->color = RED; sibling->color = BLACK; if (sibling->isOnLeft()) { // left case rightRotate(parent); } else { // right case leftRotate(parent); } fixDoubleBlack(x); } else { // Sibling black if (sibling->hasRedChild()) { // at least 1 red children if (sibling->left != NULL and sibling->left->color == RED) { if (sibling->isOnLeft()) { // left left sibling->left->color = sibling->color; sibling->color = parent->color; rightRotate(parent); } else { // right left sibling->left->color = parent->color; rightRotate(sibling); leftRotate(parent); } } else { if (sibling->isOnLeft()) { // left right sibling->right->color = parent->color; leftRotate(sibling); rightRotate(parent); } else { // right right sibling->right->color = sibling->color; sibling->color = parent->color; leftRotate(parent); } } parent->color = BLACK; } else { // 2 black children sibling->color = RED; if (parent->color == BLACK) fixDoubleBlack(parent); else parent->color = BLACK; } } } } // prints level order for given node void levelOrder(Node *x) { if (x == NULL) // return if node is null return; // queue for level order queue<Node *> q; Node *curr; // push x q.push(x); while (!q.empty()) { // while q is not empty // dequeue curr = q.front(); q.pop(); // print node value cout << curr->val << \" \"; // push children to queue if (curr->left != NULL) q.push(curr->left); if (curr->right != NULL) q.push(curr->right); } } // prints inorder recursively void inorder(Node *x) { if (x == NULL) return; inorder(x->left); cout << x->val << \" \"; inorder(x->right); } public: // constructor // initialize root RBTree() { root = NULL; } Node *getRoot() { return root; } // searches for given value // if found returns the node (used for delete) // else returns the last node while traversing (used in insert) Node *search(int n) { Node *temp = root; while (temp != NULL) { if (n < temp->val) { if (temp->left == NULL) break; else temp = temp->left; } else if (n == temp->val) { break; } else { if (temp->right == NULL) break; else temp = temp->right; } } return temp; } // inserts the given value to tree void insert(int n) { Node *newNode = new Node(n); if (root == NULL) { // when root is null // simply insert value at root newNode->color = BLACK; root = newNode; } else { Node *temp = search(n); if (temp->val == n) { // return if value already exists return; } // if value is not found, search returns the node // where the value is to be inserted // connect new node to correct node newNode->parent = temp; if (n < temp->val) temp->left = newNode; else temp->right = newNode; // fix red red voilaton if exists fixRedRed(newNode); } } // utility function that deletes the node with given value void deleteByVal(int n) { if (root == NULL) // Tree is empty return; Node *v = search(n), *u; if (v->val != n) { cout << \"No node found to delete with value:\" << n << endl; return; } deleteNode(v); } // prints inorder of the tree void printInOrder() { cout << \"Inorder: \" << endl; if (root == NULL) cout << \"Tree is empty\" << endl; else inorder(root); cout << endl; } // prints level order of the tree void printLevelOrder() { cout << \"Level order: \" << endl; if (root == NULL) cout << \"Tree is empty\" << endl; else levelOrder(root); cout << endl; }}; int main() { RBTree tree; tree.insert(7); tree.insert(3); tree.insert(18); tree.insert(10); tree.insert(22); tree.insert(8); tree.insert(11); tree.insert(26); tree.insert(2); tree.insert(6); tree.insert(13); tree.printInOrder(); tree.printLevelOrder(); cout<<endl<<\"Deleting 18, 11, 3, 10, 22\"<<endl; tree.deleteByVal(18); tree.deleteByVal(11); tree.deleteByVal(3); tree.deleteByVal(10); tree.deleteByVal(22); tree.printInOrder(); tree.printLevelOrder(); return 0;}", "e": 41063, "s": 30052, "text": null }, { "code": null, "e": 41072, "s": 41063, "text": "Output: " }, { "code": null, "e": 41236, "s": 41072, "text": "Inorder: \n2 3 6 7 8 10 11 13 18 22 26 \nLevel order: \n10 7 18 3 8 11 22 2 6 13 26 \n\nDeleting 18, 11, 3, 10, 22\nInorder: \n2 6 7 8 13 26 \nLevel order: \n13 7 26 6 8 2 " }, { "code": null, "e": 41548, "s": 41236, "text": "References: https://www.cs.purdue.edu/homes/ayg/CS251/slides/chap13c.pdf Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. RivestPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 41563, "s": 41548, "text": "shwetanknaveen" }, { "code": null, "e": 41587, "s": 41563, "text": "BhanuPratapSinghRathore" }, { "code": null, "e": 41601, "s": 41587, "text": "govindtomar94" }, { "code": null, "e": 41615, "s": 41601, "text": "kuldeepy10459" }, { "code": null, "e": 41630, "s": 41615, "text": "Red Black Tree" }, { "code": null, "e": 41649, "s": 41630, "text": "Self-Balancing-BST" }, { "code": null, "e": 41673, "s": 41649, "text": "Advanced Data Structure" }, { "code": null, "e": 41771, "s": 41673, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41805, "s": 41771, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 41845, "s": 41805, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 41887, "s": 41845, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 41916, "s": 41887, "text": "Disjoint Set Data Structures" }, { "code": null, "e": 41945, "s": 41916, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 41972, "s": 41945, "text": "Insert Operation in B-Tree" }, { "code": null, "e": 42008, "s": 41972, "text": "Binary Indexed Tree or Fenwick Tree" }, { "code": null, "e": 42022, "s": 42008, "text": "Binomial Heap" }, { "code": null, "e": 42042, "s": 42022, "text": "Design a Chess Game" } ]
Bitwise AND of all unordered pairs from a given array - GeeksforGeeks
26 Jul, 2021 Given an array arr[] of size N, the task is to find the bitwise AND of all possible unordered pairs present in the given array. Examples: Input: arr[] = {1, 5, 3, 7}Output: 1 Explanation: All possible unordered pairs are (1, 5), (1, 3), (1, 7), (5, 3), (5, 7), (3, 7). Bitwise AND of all possible pairs = ( 1 & 5 ) & ( 1 & 3 ) & ( 1 & 7 ) & ( 5 & 3 ) & ( 5 & 7 ) & ( 3 & 7 ) = 1 & 1 & 1 & 1 & 5 & 3 = 1 Therefore, the required output is 1. Input: arr[] = {4, 5, 12, 15}Output: 4 Naive approach: The idea is to traverse the array and generate all possible pairs of the given array. Finally, print Bitwise AND of each element present in these pairs of the given array. Follow the steps below to solve the problem: Initialize a variable, say totalAND, to store Bitwise AND of each element from these pairs. Iterate over the array and generate all possible pairs (arr[i], arr[j]) from the given array. For each pair (arr[i], arr[j]), update the value of totalAND = (totalAND & arr[i] & arr[j]). Finally, print the value of totalAND. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement // the above approach #include <bits/stdc++.h> using namespace std; // Function to calculate bitwise AND // of all pairs from the given array int TotalAndPair(int arr[], int N) { // Stores bitwise AND // of all possible pairs int totalAND = (1 << 30) - 1; // Generate all possible pairs for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { // Calculate bitwise AND // of each pair totalAND &= arr[i] & arr[j]; } } return totalAND; } // Driver Code int main() { int arr[] = { 4, 5, 12, 15 }; int N = sizeof(arr) / sizeof(arr[0]); cout << TotalAndPair(arr, N); } // Java program to implement // the above approach import java.util.*; class GFG{ // Function to calculate bitwise AND // of all pairs from the given array static int TotalAndPair(int arr[], int N) { // Stores bitwise AND // of all possible pairs int totalAND = (1 << 30) - 1; // Generate all possible pairs for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { // Calculate bitwise AND // of each pair totalAND &= arr[i] & arr[j]; } } return totalAND; } // Driver Code public static void main(String[] args) { int arr[] = { 4, 5, 12, 15 }; int N = arr.length; System.out.print(TotalAndPair(arr, N)); } } // This code is contributed by shikhasingrajput # Python3 program to implement # the above approach # Function to calculate bitwise AND # of all pairs from the given array def TotalAndPair(arr, N): # Stores bitwise AND # of all possible pairs totalAND = (1 << 30) - 1 # Generate all possible pairs for i in range(N): for j in range(i + 1, N): # Calculate bitwise AND # of each pair totalAND &= (arr[i] & arr[j]) return totalAND # Driver Code if __name__ == '__main__': arr=[4, 5, 12, 15] N = len(arr) print(TotalAndPair(arr, N)) # This code is contributed by mohit kumar 29 // C# program to implement // the above approach using System; class GFG{ // Function to calculate bitwise AND // of all pairs from the given array static int TotalAndPair(int[] arr, int N) { // Stores bitwise AND // of all possible pairs int totalAND = (1 << 30) - 1; // Generate all possible pairs for(int i = 0; i < N; i++) { for(int j = i + 1; j < N; j++) { // Calculate bitwise AND // of each pair totalAND &= arr[i] & arr[j]; } } return totalAND; } // Driver Code public static void Main() { int[] arr = { 4, 5, 12, 15 }; int N = arr.Length; Console.Write(TotalAndPair(arr, N)); } } // This code is contributed by sanjoy_62 <script> // JavaScript program to implement // the above approach // Function to calculate bitwise AND // of all pairs from the given array function TotalAndPair(arr, N) { // Stores bitwise AND // of all possible pairs let totalAND = (1 << 30) - 1; // Generate all possible pairs for (let i = 0; i < N; i++) { for (let j = i + 1; j < N; j++) { // Calculate bitwise AND // of each pair totalAND &= arr[i] & arr[j]; } } return totalAND; } // Driver Code let arr = [ 4, 5, 12, 15 ]; let N = arr.length; document.write(TotalAndPair(arr, N)); // This code is contributed by Surbhi Tyagi </script> 4 Time Complexity: O(N2)Auxiliary Space: O(1) Efficient Approach: The above approach can be optimized based on the following observations: Considering an array of 4 elements, required Bitwise AND is as follows: (arr[0] & arr[1]) & (arr[0] & arr[2]) & (arr[0] & arr[3]) & (arr[1] & arr[2]) & (arr[1] & arr[3]) & (arr[2] & arr[3]) Since Bitwise AND follows Associative property, the above expression can be rearranged as: (arr[0] & arr[0] & arr[0]) & (arr[1] & arr[1] & arr[1]) & (arr[2] & arr[2] & arr[2]) & (arr[3] & arr[3] & arr[3]) It can be observed that each array element occurs exactly (N – 1) times in all possible pairs. Based on the X & X = X property of Bitwise AND operators, the above expression can be rearranged to arr[0] & arr[1] & arr[2] & arr[3], which is equal to the Bitwise AND of all elements of original array. Follow the steps below to solve the problem: Initialize a variable totalAND to store the result. Traverse the given array. Calculate Bitwise AND of all unordered pairs by updating totalAND = totalAND & arr[i]. Below is the implementation of the above approach C++ Java Python3 C# Javascript // C++ program to implement // the above approach #include <bits/stdc++.h> using namespace std; // Function to calculate bitwise AND // of all pairs from the given array int TotalAndPair(int arr[], int N) { // Stores bitwise AND // of all possible pairs int totalAND = (1 << 30) - 1; // Iterate over the array arr[] for (int i = 0; i < N; i++) { // Calculate bitwise AND // of each array element totalAND &= arr[i]; } return totalAND; } // Driver Code int main() { int arr[] = { 4, 5, 12, 15 }; int N = sizeof(arr) / sizeof(arr[0]); cout << TotalAndPair(arr, N); } // Java program to implement // the above approach import java.util.*; class GFG{ // Function to calculate bitwise AND // of all pairs from the given array static int TotalAndPair(int arr[], int N) { // Stores bitwise AND // of all possible pairs int totalAND = (1 << 30) - 1; // Iterate over the array arr[] for (int i = 0; i < N; i++) { // Calculate bitwise AND // of each array element totalAND &= arr[i]; } return totalAND; } // Driver Code public static void main(String[] args) { int arr[] = { 4, 5, 12, 15 }; int N = arr.length; System.out.print(TotalAndPair(arr, N)); } } // This code is contributed by 29AjayKumar # Python program to implement # the above approach # Function to calculate bitwise AND # of all pairs from the given array def TotalAndPair(arr, N): # Stores bitwise AND # of all possible pairs totalAND = (1 << 30) - 1; # Iterate over the array arr for i in range(N): # Calculate bitwise AND # of each array element totalAND &= arr[i]; return totalAND; # Driver Code if __name__ == '__main__': arr = [4, 5, 12, 15]; N = len(arr); print(TotalAndPair(arr, N)); # This code is contributed by 29AjayKumar // C# program to implement // the above approach using System; class GFG{ // Function to calculate bitwise AND // of all pairs from the given array static int TotalAndPair(int []arr, int N) { // Stores bitwise AND // of all possible pairs int totalAND = (1 << 30) - 1; // Iterate over the array arr[] for(int i = 0; i < N; i++) { // Calculate bitwise AND // of each array element totalAND &= arr[i]; } return totalAND; } // Driver Code public static void Main(String[] args) { int []arr = { 4, 5, 12, 15 }; int N = arr.Length; Console.Write(TotalAndPair(arr, N)); } } // This code is contributed by AnkThon <script> // JavaScript program to implement // the above approach // Function to calculate bitwise AND // of all pairs from the given array function TotalAndPair(arr, N) { // Stores bitwise AND // of all possible pairs let totalAND = (1 << 30) - 1; // Iterate over the array arr[] for (let i = 0; i < N; i++) { // Calculate bitwise AND // of each array element totalAND &= arr[i]; } return totalAND; } // Driver Code let arr = [ 4, 5, 12, 15 ]; let N = arr.length; document.write(TotalAndPair(arr, N)); // This code is contributed by Surbhi Tyagi. </script> 4 Time Complexity: O(N)Auxiliary Space: O(1) mohit kumar 29 shikhasingrajput sanjoy_62 29AjayKumar ankthon surbhityagi15 adnanirshad158 Bitwise-AND Arrays Bit Magic C++ Programs Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer How to swap two numbers without using a temporary variable?
[ { "code": null, "e": 26993, "s": 26962, "text": " \n26 Jul, 2021\n" }, { "code": null, "e": 27121, "s": 26993, "text": "Given an array arr[] of size N, the task is to find the bitwise AND of all possible unordered pairs present in the given array." }, { "code": null, "e": 27131, "s": 27121, "text": "Examples:" }, { "code": null, "e": 27548, "s": 27131, "text": "Input: arr[] = {1, 5, 3, 7}Output: 1 Explanation: All possible unordered pairs are (1, 5), (1, 3), (1, 7), (5, 3), (5, 7), (3, 7). Bitwise AND of all possible pairs = ( 1 & 5 ) & ( 1 & 3 ) & ( 1 & 7 ) & ( 5 & 3 ) & ( 5 & 7 ) & ( 3 & 7 ) = 1 & 1 & 1 & 1 & 5 & 3 = 1 Therefore, the required output is 1." }, { "code": null, "e": 27587, "s": 27548, "text": "Input: arr[] = {4, 5, 12, 15}Output: 4" }, { "code": null, "e": 27820, "s": 27587, "text": "Naive approach: The idea is to traverse the array and generate all possible pairs of the given array. Finally, print Bitwise AND of each element present in these pairs of the given array. Follow the steps below to solve the problem:" }, { "code": null, "e": 27912, "s": 27820, "text": "Initialize a variable, say totalAND, to store Bitwise AND of each element from these pairs." }, { "code": null, "e": 28006, "s": 27912, "text": "Iterate over the array and generate all possible pairs (arr[i], arr[j]) from the given array." }, { "code": null, "e": 28099, "s": 28006, "text": "For each pair (arr[i], arr[j]), update the value of totalAND = (totalAND & arr[i] & arr[j])." }, { "code": null, "e": 28137, "s": 28099, "text": "Finally, print the value of totalAND." }, { "code": null, "e": 28188, "s": 28137, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28192, "s": 28188, "text": "C++" }, { "code": null, "e": 28197, "s": 28192, "text": "Java" }, { "code": null, "e": 28205, "s": 28197, "text": "Python3" }, { "code": null, "e": 28208, "s": 28205, "text": "C#" }, { "code": null, "e": 28219, "s": 28208, "text": "Javascript" }, { "code": "\n\n\n\n\n\n\n// C++ program to implement\n// the above approach\n \n#include <bits/stdc++.h>\nusing namespace std;\n \n// Function to calculate bitwise AND\n// of all pairs from the given array\nint TotalAndPair(int arr[], int N)\n{\n // Stores bitwise AND\n // of all possible pairs\n int totalAND = (1 << 30) - 1;\n \n // Generate all possible pairs\n for (int i = 0; i < N; i++) {\n for (int j = i + 1; j < N;\n j++) {\n \n // Calculate bitwise AND\n // of each pair\n totalAND &= arr[i]\n & arr[j];\n }\n }\n return totalAND;\n}\n \n// Driver Code\nint main()\n{\n int arr[] = { 4, 5, 12, 15 };\n int N = sizeof(arr) / sizeof(arr[0]);\n cout << TotalAndPair(arr, N);\n}\n\n\n\n\n\n", "e": 28981, "s": 28229, "text": null }, { "code": "\n\n\n\n\n\n\n// Java program to implement\n// the above approach\nimport java.util.*;\n \nclass GFG{\n \n// Function to calculate bitwise AND\n// of all pairs from the given array\nstatic int TotalAndPair(int arr[], int N)\n{\n // Stores bitwise AND\n // of all possible pairs\n int totalAND = (1 << 30) - 1;\n \n // Generate all possible pairs\n for (int i = 0; i < N; i++) \n {\n for (int j = i + 1; j < N;\n j++)\n {\n \n // Calculate bitwise AND\n // of each pair\n totalAND &= arr[i]\n & arr[j];\n }\n }\n return totalAND;\n}\n \n// Driver Code\npublic static void main(String[] args)\n{\n int arr[] = { 4, 5, 12, 15 };\n int N = arr.length;\n System.out.print(TotalAndPair(arr, N));\n}\n}\n \n// This code is contributed by shikhasingrajput\n\n\n\n\n\n", "e": 29821, "s": 28991, "text": null }, { "code": "\n\n\n\n\n\n\n# Python3 program to implement\n# the above approach\n \n# Function to calculate bitwise AND\n# of all pairs from the given array\ndef TotalAndPair(arr, N):\n \n # Stores bitwise AND\n # of all possible pairs\n totalAND = (1 << 30) - 1\n \n # Generate all possible pairs\n for i in range(N):\n for j in range(i + 1, N):\n \n # Calculate bitwise AND\n # of each pair\n totalAND &= (arr[i] & arr[j])\n return totalAND\n \n# Driver Code\nif __name__ == '__main__':\n arr=[4, 5, 12, 15]\n N = len(arr)\n print(TotalAndPair(arr, N)) \n \n# This code is contributed by mohit kumar 29\n\n\n\n\n\n", "e": 30459, "s": 29831, "text": null }, { "code": "\n\n\n\n\n\n\n// C# program to implement\n// the above approach \nusing System;\n \nclass GFG{\n \n// Function to calculate bitwise AND\n// of all pairs from the given array\nstatic int TotalAndPair(int[] arr, int N)\n{\n \n // Stores bitwise AND\n // of all possible pairs\n int totalAND = (1 << 30) - 1;\n \n // Generate all possible pairs\n for(int i = 0; i < N; i++) \n {\n for(int j = i + 1; j < N; j++)\n {\n \n // Calculate bitwise AND\n // of each pair\n totalAND &= arr[i] & arr[j];\n }\n }\n return totalAND;\n}\n \n// Driver Code\npublic static void Main()\n{\n int[] arr = { 4, 5, 12, 15 };\n int N = arr.Length;\n \n Console.Write(TotalAndPair(arr, N));\n}\n}\n \n// This code is contributed by sanjoy_62\n\n\n\n\n\n", "e": 31259, "s": 30469, "text": null }, { "code": "\n\n\n\n\n\n\n<script>\n \n// JavaScript program to implement\n// the above approach\n \n// Function to calculate bitwise AND\n// of all pairs from the given array\nfunction TotalAndPair(arr, N)\n{\n // Stores bitwise AND\n // of all possible pairs\n let totalAND = (1 << 30) - 1;\n \n // Generate all possible pairs\n for (let i = 0; i < N; i++) {\n for (let j = i + 1; j < N;\n j++) {\n \n // Calculate bitwise AND\n // of each pair\n totalAND &= arr[i]\n & arr[j];\n }\n }\n return totalAND;\n}\n \n// Driver Code\n let arr = [ 4, 5, 12, 15 ];\n let N = arr.length;\n document.write(TotalAndPair(arr, N));\n \n \n// This code is contributed by Surbhi Tyagi\n \n</script>\n\n\n\n\n\n", "e": 32018, "s": 31269, "text": null }, { "code": null, "e": 32020, "s": 32018, "text": "4" }, { "code": null, "e": 32066, "s": 32022, "text": "Time Complexity: O(N2)Auxiliary Space: O(1)" }, { "code": null, "e": 32159, "s": 32066, "text": "Efficient Approach: The above approach can be optimized based on the following observations:" }, { "code": null, "e": 32231, "s": 32159, "text": "Considering an array of 4 elements, required Bitwise AND is as follows:" }, { "code": null, "e": 32351, "s": 32231, "text": "(arr[0] & arr[1]) & (arr[0] & arr[2]) & (arr[0] & arr[3]) & (arr[1] & arr[2]) & (arr[1] & arr[3]) & (arr[2] & arr[3]) " }, { "code": null, "e": 32442, "s": 32351, "text": "Since Bitwise AND follows Associative property, the above expression can be rearranged as:" }, { "code": null, "e": 32558, "s": 32442, "text": "(arr[0] & arr[0] & arr[0]) & (arr[1] & arr[1] & arr[1]) & (arr[2] & arr[2] & arr[2]) & (arr[3] & arr[3] & arr[3]) " }, { "code": null, "e": 32653, "s": 32558, "text": "It can be observed that each array element occurs exactly (N – 1) times in all possible pairs." }, { "code": null, "e": 32857, "s": 32653, "text": "Based on the X & X = X property of Bitwise AND operators, the above expression can be rearranged to arr[0] & arr[1] & arr[2] & arr[3], which is equal to the Bitwise AND of all elements of original array." }, { "code": null, "e": 32903, "s": 32857, "text": "Follow the steps below to solve the problem: " }, { "code": null, "e": 32955, "s": 32903, "text": "Initialize a variable totalAND to store the result." }, { "code": null, "e": 32981, "s": 32955, "text": "Traverse the given array." }, { "code": null, "e": 33068, "s": 32981, "text": "Calculate Bitwise AND of all unordered pairs by updating totalAND = totalAND & arr[i]." }, { "code": null, "e": 33118, "s": 33068, "text": "Below is the implementation of the above approach" }, { "code": null, "e": 33122, "s": 33118, "text": "C++" }, { "code": null, "e": 33127, "s": 33122, "text": "Java" }, { "code": null, "e": 33135, "s": 33127, "text": "Python3" }, { "code": null, "e": 33138, "s": 33135, "text": "C#" }, { "code": null, "e": 33149, "s": 33138, "text": "Javascript" }, { "code": "\n\n\n\n\n\n\n// C++ program to implement\n// the above approach\n \n#include <bits/stdc++.h>\nusing namespace std;\n \n// Function to calculate bitwise AND\n// of all pairs from the given array\nint TotalAndPair(int arr[], int N)\n{\n // Stores bitwise AND\n // of all possible pairs\n int totalAND = (1 << 30) - 1;\n \n // Iterate over the array arr[]\n for (int i = 0; i < N; i++) {\n \n // Calculate bitwise AND\n // of each array element\n totalAND &= arr[i];\n }\n return totalAND;\n}\n \n// Driver Code\nint main()\n{\n int arr[] = { 4, 5, 12, 15 };\n int N = sizeof(arr) / sizeof(arr[0]);\n cout << TotalAndPair(arr, N);\n}\n\n\n\n\n\n", "e": 33811, "s": 33159, "text": null }, { "code": "\n\n\n\n\n\n\n// Java program to implement\n// the above approach\n \nimport java.util.*;\n \nclass GFG{\n \n// Function to calculate bitwise AND\n// of all pairs from the given array\nstatic int TotalAndPair(int arr[], int N)\n{\n // Stores bitwise AND\n // of all possible pairs\n int totalAND = (1 << 30) - 1;\n \n // Iterate over the array arr[]\n for (int i = 0; i < N; i++) {\n \n // Calculate bitwise AND\n // of each array element\n totalAND &= arr[i];\n }\n return totalAND;\n}\n \n// Driver Code\npublic static void main(String[] args)\n{\n int arr[] = { 4, 5, 12, 15 };\n int N = arr.length;\n System.out.print(TotalAndPair(arr, N));\n}\n}\n \n// This code is contributed by 29AjayKumar \n\n\n\n\n\n", "e": 34536, "s": 33821, "text": null }, { "code": "\n\n\n\n\n\n\n# Python program to implement\n# the above approach\n \n# Function to calculate bitwise AND\n# of all pairs from the given array\ndef TotalAndPair(arr, N):\n \n # Stores bitwise AND\n # of all possible pairs\n totalAND = (1 << 30) - 1;\n \n # Iterate over the array arr\n for i in range(N):\n \n # Calculate bitwise AND\n # of each array element\n totalAND &= arr[i];\n \n return totalAND;\n \n# Driver Code\nif __name__ == '__main__':\n arr = [4, 5, 12, 15];\n N = len(arr);\n print(TotalAndPair(arr, N));\n \n # This code is contributed by 29AjayKumar \n\n\n\n\n\n", "e": 35151, "s": 34546, "text": null }, { "code": "\n\n\n\n\n\n\n// C# program to implement\n// the above approach\nusing System;\n \nclass GFG{\n \n// Function to calculate bitwise AND\n// of all pairs from the given array\nstatic int TotalAndPair(int []arr, int N)\n{\n \n // Stores bitwise AND\n // of all possible pairs\n int totalAND = (1 << 30) - 1;\n \n // Iterate over the array arr[]\n for(int i = 0; i < N; i++) \n {\n \n // Calculate bitwise AND\n // of each array element\n totalAND &= arr[i];\n }\n return totalAND;\n}\n \n// Driver Code\npublic static void Main(String[] args)\n{\n int []arr = { 4, 5, 12, 15 };\n int N = arr.Length;\n \n Console.Write(TotalAndPair(arr, N));\n}\n}\n \n// This code is contributed by AnkThon\n\n\n\n\n\n", "e": 35886, "s": 35161, "text": null }, { "code": "\n\n\n\n\n\n\n<script>\n// JavaScript program to implement\n// the above approach\n \n// Function to calculate bitwise AND\n// of all pairs from the given array\nfunction TotalAndPair(arr, N)\n{\n // Stores bitwise AND\n // of all possible pairs\n let totalAND = (1 << 30) - 1;\n \n // Iterate over the array arr[]\n for (let i = 0; i < N; i++) {\n \n // Calculate bitwise AND\n // of each array element\n totalAND &= arr[i];\n }\n return totalAND;\n}\n \n// Driver Code\n \n let arr = [ 4, 5, 12, 15 ];\n let N = arr.length;\n document.write(TotalAndPair(arr, N));\n \n \n// This code is contributed by Surbhi Tyagi.\n</script>\n\n\n\n\n\n", "e": 36545, "s": 35896, "text": null }, { "code": null, "e": 36547, "s": 36545, "text": "4" }, { "code": null, "e": 36592, "s": 36549, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 36609, "s": 36594, "text": "mohit kumar 29" }, { "code": null, "e": 36626, "s": 36609, "text": "shikhasingrajput" }, { "code": null, "e": 36636, "s": 36626, "text": "sanjoy_62" }, { "code": null, "e": 36648, "s": 36636, "text": "29AjayKumar" }, { "code": null, "e": 36656, "s": 36648, "text": "ankthon" }, { "code": null, "e": 36670, "s": 36656, "text": "surbhityagi15" }, { "code": null, "e": 36685, "s": 36670, "text": "adnanirshad158" }, { "code": null, "e": 36699, "s": 36685, "text": "\nBitwise-AND\n" }, { "code": null, "e": 36708, "s": 36699, "text": "\nArrays\n" }, { "code": null, "e": 36720, "s": 36708, "text": "\nBit Magic\n" }, { "code": null, "e": 36735, "s": 36720, "text": "\nC++ Programs\n" }, { "code": null, "e": 36750, "s": 36735, "text": "\nMathematical\n" }, { "code": null, "e": 36955, "s": 36750, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 37023, "s": 36955, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 37067, "s": 37023, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 37090, "s": 37067, "text": "Introduction to Arrays" }, { "code": null, "e": 37122, "s": 37090, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 37136, "s": 37122, "text": "Linear Search" }, { "code": null, "e": 37163, "s": 37136, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 37209, "s": 37163, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 37277, "s": 37209, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 37306, "s": 37277, "text": "Count set bits in an integer" } ]
How to Calculate the Code Execution Time in C#? - GeeksforGeeks
23 Nov, 2021 The execution time of a task is defined as the time taken by the system to execute that task. The execution time of a program is equal to the sum of the execution time of its statements. There are numerous ways to calculate the execution time of a program in C#. In this article, we will see three ways to measure execution time in C#. We can calculate the execution time of the code using StartNew() and Stop() methods. StartNew() method comes under the Stopwatch class and it basically used to initialize a new Stopwatch instance. Internally it marks the elapsed time property equal to zero and then it starts measuring the elapsed time. This method is almost the same as calling the Stopwatch constructor first and then calling class on the new instance. Syntax: public static StartNew (); Stop() method also comes under the Stopwatch class and it is used to stop the current measuring time for an interval. Firstly we can call StartNew() method in Stopwatch to start the elapsed time and at the end, we can call this method to end the current measuring time interval. Eventually, the total execution time is calculated with the help of elapsed property. Whenever a Stopwatch instance measures more than one interval, this method is similar to pausing the elapsed time measurement. Like StartNew() method, this method is also defined under System.Diagnostics namespace. Syntax: public void Stop (); Example: C# // C# program to find the execution time of the codeusing System;using System.Diagnostics; class GFG{ static public void Main(){ // Starting the Stopwatch var watch = Stopwatch.StartNew(); // Iterating using for loop for(int i = 0; i < 5; i++) { // Print on console Console.WriteLine("GeeksforGeeks"); } // Stop the Stopwatch watch.Stop(); // Print the execution time in milliseconds // by using the property elapsed milliseconds Console.WriteLine( $"The Execution time of the program is {watch.ElapsedMilliseconds}ms");}} GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks The Execution time of the program is 37ms We can also find the execution time of the code using the GetTimestamp() method. This method is quite helpful for finding the number of ticks for a duration in the timer mechanism. We can use the high-resolution performance counter of the Stopwatch class to get the current value of that counter. We can use the system timer also to get the current DateTime.Ticks property of the DateTime.UtcNow instance. Its return type is a long integer that represents the tick counter value of the timer mechanism. Syntax: public static long GetTimestamp (); Example: C# // C# program to find the execution time of the codeusing System;using System.Diagnostics; class GFG{ static public void Main(){ // Mark the start before the loop var start = Stopwatch.GetTimestamp(); // Iterating using for loop for(int i = 0; i < 5; i++) { // Print on console Console.WriteLine("GeeksforGeeks"); } // Mark the end after the loop var end = Stopwatch.GetTimestamp(); // Print the difference Console.WriteLine("Elapsed Time is {0} ticks", (end - start));}} GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks Elapsed Time is 343095 ticks We can calculate the execution time of the code using the DateTime.Now property. This property is quite helpful to get a DateTime object that is initially marked with the current date and time on the device (as the local time). The property value of this method is DateTime which is an object whose value is current local data and time. The Now property returns a DateTime value which depicts the current date and time on the device or computer. This is defined under the System namespace. Syntax: public static DateTime Now { get; } Example: C# // C# program to find the execution time of the codeusing System; class GFG{ static public void Main(){ // Marking the start time DateTime start = DateTime.Now; // Iterating using for loop for(int i = 0 ; i < 5 ; i++) { Console.WriteLine("GeeksforGeeks"); } // Marking the end time DateTime end = DateTime.Now; // Total Duration TimeSpan ts = (end - start); // Print the execution time in milliseconds Console.WriteLine("The execution time of the program is {0} ms", ts.TotalMilliseconds);}} Output: GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks The execution time of the program is 176.095 ms Picked C# C# Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Convert String to Character Array in C# Getting a Month Name Using Month Number in C# Program to Print a New Line in C# Socket Programming in C# Program to find absolute value of a given number
[ { "code": null, "e": 25657, "s": 25629, "text": "\n23 Nov, 2021" }, { "code": null, "e": 25993, "s": 25657, "text": "The execution time of a task is defined as the time taken by the system to execute that task. The execution time of a program is equal to the sum of the execution time of its statements. There are numerous ways to calculate the execution time of a program in C#. In this article, we will see three ways to measure execution time in C#." }, { "code": null, "e": 26416, "s": 25993, "text": "We can calculate the execution time of the code using StartNew() and Stop() methods. StartNew() method comes under the Stopwatch class and it basically used to initialize a new Stopwatch instance. Internally it marks the elapsed time property equal to zero and then it starts measuring the elapsed time. This method is almost the same as calling the Stopwatch constructor first and then calling class on the new instance. " }, { "code": null, "e": 26424, "s": 26416, "text": "Syntax:" }, { "code": null, "e": 26451, "s": 26424, "text": "public static StartNew ();" }, { "code": null, "e": 27032, "s": 26451, "text": "Stop() method also comes under the Stopwatch class and it is used to stop the current measuring time for an interval. Firstly we can call StartNew() method in Stopwatch to start the elapsed time and at the end, we can call this method to end the current measuring time interval. Eventually, the total execution time is calculated with the help of elapsed property. Whenever a Stopwatch instance measures more than one interval, this method is similar to pausing the elapsed time measurement. Like StartNew() method, this method is also defined under System.Diagnostics namespace. " }, { "code": null, "e": 27040, "s": 27032, "text": "Syntax:" }, { "code": null, "e": 27061, "s": 27040, "text": "public void Stop ();" }, { "code": null, "e": 27070, "s": 27061, "text": "Example:" }, { "code": null, "e": 27073, "s": 27070, "text": "C#" }, { "code": "// C# program to find the execution time of the codeusing System;using System.Diagnostics; class GFG{ static public void Main(){ // Starting the Stopwatch var watch = Stopwatch.StartNew(); // Iterating using for loop for(int i = 0; i < 5; i++) { // Print on console Console.WriteLine(\"GeeksforGeeks\"); } // Stop the Stopwatch watch.Stop(); // Print the execution time in milliseconds // by using the property elapsed milliseconds Console.WriteLine( $\"The Execution time of the program is {watch.ElapsedMilliseconds}ms\");}}", "e": 27705, "s": 27073, "text": null }, { "code": null, "e": 27817, "s": 27705, "text": "GeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nThe Execution time of the program is 37ms" }, { "code": null, "e": 28320, "s": 27817, "text": "We can also find the execution time of the code using the GetTimestamp() method. This method is quite helpful for finding the number of ticks for a duration in the timer mechanism. We can use the high-resolution performance counter of the Stopwatch class to get the current value of that counter. We can use the system timer also to get the current DateTime.Ticks property of the DateTime.UtcNow instance. Its return type is a long integer that represents the tick counter value of the timer mechanism." }, { "code": null, "e": 28328, "s": 28320, "text": "Syntax:" }, { "code": null, "e": 28364, "s": 28328, "text": "public static long GetTimestamp ();" }, { "code": null, "e": 28373, "s": 28364, "text": "Example:" }, { "code": null, "e": 28376, "s": 28373, "text": "C#" }, { "code": "// C# program to find the execution time of the codeusing System;using System.Diagnostics; class GFG{ static public void Main(){ // Mark the start before the loop var start = Stopwatch.GetTimestamp(); // Iterating using for loop for(int i = 0; i < 5; i++) { // Print on console Console.WriteLine(\"GeeksforGeeks\"); } // Mark the end after the loop var end = Stopwatch.GetTimestamp(); // Print the difference Console.WriteLine(\"Elapsed Time is {0} ticks\", (end - start));}}", "e": 28939, "s": 28376, "text": null }, { "code": null, "e": 29038, "s": 28939, "text": "GeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nElapsed Time is 343095 ticks" }, { "code": null, "e": 29528, "s": 29038, "text": "We can calculate the execution time of the code using the DateTime.Now property. This property is quite helpful to get a DateTime object that is initially marked with the current date and time on the device (as the local time). The property value of this method is DateTime which is an object whose value is current local data and time. The Now property returns a DateTime value which depicts the current date and time on the device or computer. This is defined under the System namespace." }, { "code": null, "e": 29536, "s": 29528, "text": "Syntax:" }, { "code": null, "e": 29572, "s": 29536, "text": "public static DateTime Now { get; }" }, { "code": null, "e": 29581, "s": 29572, "text": "Example:" }, { "code": null, "e": 29584, "s": 29581, "text": "C#" }, { "code": "// C# program to find the execution time of the codeusing System; class GFG{ static public void Main(){ // Marking the start time DateTime start = DateTime.Now; // Iterating using for loop for(int i = 0 ; i < 5 ; i++) { Console.WriteLine(\"GeeksforGeeks\"); } // Marking the end time DateTime end = DateTime.Now; // Total Duration TimeSpan ts = (end - start); // Print the execution time in milliseconds Console.WriteLine(\"The execution time of the program is {0} ms\", ts.TotalMilliseconds);}}", "e": 30194, "s": 29584, "text": null }, { "code": null, "e": 30202, "s": 30194, "text": "Output:" }, { "code": null, "e": 30320, "s": 30202, "text": "GeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nThe execution time of the program is 176.095 ms" }, { "code": null, "e": 30327, "s": 30320, "text": "Picked" }, { "code": null, "e": 30330, "s": 30327, "text": "C#" }, { "code": null, "e": 30342, "s": 30330, "text": "C# Programs" }, { "code": null, "e": 30440, "s": 30342, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30463, "s": 30440, "text": "Extension Method in C#" }, { "code": null, "e": 30491, "s": 30463, "text": "HashSet in C# with Examples" }, { "code": null, "e": 30508, "s": 30491, "text": "C# | Inheritance" }, { "code": null, "e": 30530, "s": 30508, "text": "Partial Classes in C#" }, { "code": null, "e": 30559, "s": 30530, "text": "C# | Generics - Introduction" }, { "code": null, "e": 30599, "s": 30559, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 30645, "s": 30599, "text": "Getting a Month Name Using Month Number in C#" }, { "code": null, "e": 30679, "s": 30645, "text": "Program to Print a New Line in C#" }, { "code": null, "e": 30704, "s": 30679, "text": "Socket Programming in C#" } ]
How to Exclude Columns in Pandas? - GeeksforGeeks
19 Dec, 2021 In this article, we will discuss how to exclude columns in pandas dataframe. Let’s create a dataframe with four columns in python. Python3 # import pandas moduleimport pandas as pd # create food dataframedata = pd.DataFrame({'food_id': [1, 2, 3, 4], 'name': ['idly', 'dosa', 'poori', 'chapathi'], 'city': ['delhi', 'goa', 'hyd', 'chennai'], 'cost': [12, 34, 21, 23]}) # displaydata Output: We can exclude one column from the pandas dataframe by using the loc function. This function removes the column based on the location. Syntax: dataframe.loc[:, ddataframe.columns!='column_name'] Parameters: dataframe: is the input dataframe columns: is the method used to get the columns column_name: is the column to be excluded Example: In this example, we will be using the loc() function with the given data frame to exclude columns with name,city, and cost in python. Python3 # import pandas moduleimport pandas as pd # create food dataframedata = pd.DataFrame({'food_id': [1, 2, 3, 4], 'name': ['idly', 'dosa', 'poori', 'chapathi'], 'city': ['delhi', 'goa', 'hyd', 'chennai'], 'cost': [12, 34, 21, 23]}) # exclude name columnprint(data.loc[:, data.columns != 'name']) # exclude city columnprint(data.loc[:, data.columns != 'city']) # exclude cost columnprint(data.loc[:, data.columns != 'cost']) Output: Here we are using loc function with isin operator to exclude the multiple columns Syntax: dataframe.loc[:, ~dataframe.columns.isin([‘column1’,.................., ‘column n’])] Example: In this example, we will be using the isin operator to exclude the name and food_id column from the given data frame. Python3 # import pandas moduleimport pandas as pd # create food dataframedata = pd.DataFrame({'food_id': [1, 2, 3, 4], 'name': ['idly', 'dosa', 'poori', 'chapathi'], 'city': ['delhi', 'goa', 'hyd', 'chennai'], 'cost': [12, 34, 21, 23]}) # exclude name and food_id columnprint(data.loc[:, ~data.columns.isin(['name', 'food_id'])]) Output: pandas-dataframe-program Picked Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Create a directory in Python Python | os.path.join() method Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 26088, "s": 26060, "text": "\n19 Dec, 2021" }, { "code": null, "e": 26165, "s": 26088, "text": "In this article, we will discuss how to exclude columns in pandas dataframe." }, { "code": null, "e": 26219, "s": 26165, "text": "Let’s create a dataframe with four columns in python." }, { "code": null, "e": 26227, "s": 26219, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # create food dataframedata = pd.DataFrame({'food_id': [1, 2, 3, 4], 'name': ['idly', 'dosa', 'poori', 'chapathi'], 'city': ['delhi', 'goa', 'hyd', 'chennai'], 'cost': [12, 34, 21, 23]}) # displaydata", "e": 26532, "s": 26227, "text": null }, { "code": null, "e": 26540, "s": 26532, "text": "Output:" }, { "code": null, "e": 26675, "s": 26540, "text": "We can exclude one column from the pandas dataframe by using the loc function. This function removes the column based on the location." }, { "code": null, "e": 26683, "s": 26675, "text": "Syntax:" }, { "code": null, "e": 26735, "s": 26683, "text": "dataframe.loc[:, ddataframe.columns!='column_name']" }, { "code": null, "e": 26747, "s": 26735, "text": "Parameters:" }, { "code": null, "e": 26781, "s": 26747, "text": "dataframe: is the input dataframe" }, { "code": null, "e": 26828, "s": 26781, "text": "columns: is the method used to get the columns" }, { "code": null, "e": 26870, "s": 26828, "text": "column_name: is the column to be excluded" }, { "code": null, "e": 26879, "s": 26870, "text": "Example:" }, { "code": null, "e": 27013, "s": 26879, "text": "In this example, we will be using the loc() function with the given data frame to exclude columns with name,city, and cost in python." }, { "code": null, "e": 27021, "s": 27013, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # create food dataframedata = pd.DataFrame({'food_id': [1, 2, 3, 4], 'name': ['idly', 'dosa', 'poori', 'chapathi'], 'city': ['delhi', 'goa', 'hyd', 'chennai'], 'cost': [12, 34, 21, 23]}) # exclude name columnprint(data.loc[:, data.columns != 'name']) # exclude city columnprint(data.loc[:, data.columns != 'city']) # exclude cost columnprint(data.loc[:, data.columns != 'cost'])", "e": 27506, "s": 27021, "text": null }, { "code": null, "e": 27514, "s": 27506, "text": "Output:" }, { "code": null, "e": 27596, "s": 27514, "text": "Here we are using loc function with isin operator to exclude the multiple columns" }, { "code": null, "e": 27604, "s": 27596, "text": "Syntax:" }, { "code": null, "e": 27690, "s": 27604, "text": "dataframe.loc[:, ~dataframe.columns.isin([‘column1’,.................., ‘column n’])]" }, { "code": null, "e": 27699, "s": 27690, "text": "Example:" }, { "code": null, "e": 27817, "s": 27699, "text": "In this example, we will be using the isin operator to exclude the name and food_id column from the given data frame." }, { "code": null, "e": 27825, "s": 27817, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # create food dataframedata = pd.DataFrame({'food_id': [1, 2, 3, 4], 'name': ['idly', 'dosa', 'poori', 'chapathi'], 'city': ['delhi', 'goa', 'hyd', 'chennai'], 'cost': [12, 34, 21, 23]}) # exclude name and food_id columnprint(data.loc[:, ~data.columns.isin(['name', 'food_id'])])", "e": 28209, "s": 27825, "text": null }, { "code": null, "e": 28217, "s": 28209, "text": "Output:" }, { "code": null, "e": 28242, "s": 28217, "text": "pandas-dataframe-program" }, { "code": null, "e": 28249, "s": 28242, "text": "Picked" }, { "code": null, "e": 28273, "s": 28249, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28287, "s": 28273, "text": "Python-pandas" }, { "code": null, "e": 28294, "s": 28287, "text": "Python" }, { "code": null, "e": 28392, "s": 28294, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28424, "s": 28392, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28466, "s": 28424, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28508, "s": 28466, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28564, "s": 28508, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28591, "s": 28564, "text": "Python Classes and Objects" }, { "code": null, "e": 28613, "s": 28591, "text": "Defaultdict in Python" }, { "code": null, "e": 28642, "s": 28613, "text": "Create a directory in Python" }, { "code": null, "e": 28673, "s": 28642, "text": "Python | os.path.join() method" }, { "code": null, "e": 28709, "s": 28673, "text": "Python | Pandas dataframe.groupby()" } ]
C program to find Highest Common Factor (HCF) and Least Common Multiple (LCM)
First, let us learn how to find Highest Common Factor (HCF). The greatest number divides each of the two or more numbers is called HCF or Highest Common Factor. It is also called as Greatest Common Measure(GCM) and Greatest Common Divisor(GCD). For example, What is the HCF of 12 and 16? Factors of 12 = 1, 2, 3, 4, 6,12. Factors of 16=1,2,4,8,16 Highest common factor (H.C.F) of 12 and 16 = 4. For two integers x and y, denoted LCM(x,y), it is the smallest positive integer that is divisible by both x and y. For example, LCM(2,3) = 6 and LCM(6,10) = 30. Live Demo #include <stdio.h> int main() { int num1, num2, x, y, temp, gcd, lcm; printf("Enter two integers\n"); scanf("%d%d", &x, &y); num1 = x; num2 = y; while (num2 != 0) { temp = num2; num2 = num1 % num2; num1 = temp; } gcd = num1; lcm = (x*y)/gcd; printf("GCD of %d and %d = %d\n", x, y, gcd); printf("LCM of %d and %d = %d\n", x, y, lcm); return 0; } Upon execution, you will receive the following output − Run 1: Enter two integers 6 12 GCD of 6 and 12 = 6 LCM of 6 and 12 = 12 Run 2: Enter two integers 24 36 GCD of 24 and 36 = 12 LCM of 24 and 36 = 72
[ { "code": null, "e": 1123, "s": 1062, "text": "First, let us learn how to find Highest Common Factor (HCF)." }, { "code": null, "e": 1307, "s": 1123, "text": "The greatest number divides each of the two or more numbers is called HCF or Highest Common Factor. It is also called as Greatest Common Measure(GCM) and Greatest Common Divisor(GCD)." }, { "code": null, "e": 1320, "s": 1307, "text": "For example," }, { "code": null, "e": 1350, "s": 1320, "text": "What is the HCF of 12 and 16?" }, { "code": null, "e": 1409, "s": 1350, "text": "Factors of 12 = 1, 2, 3, 4, 6,12.\nFactors of 16=1,2,4,8,16" }, { "code": null, "e": 1457, "s": 1409, "text": "Highest common factor (H.C.F) of 12 and 16 = 4." }, { "code": null, "e": 1572, "s": 1457, "text": "For two integers x and y, denoted LCM(x,y), it is the smallest positive integer that is divisible by both x and y." }, { "code": null, "e": 1585, "s": 1572, "text": "For example," }, { "code": null, "e": 1618, "s": 1585, "text": "LCM(2,3) = 6 and LCM(6,10) = 30." }, { "code": null, "e": 1629, "s": 1618, "text": " Live Demo" }, { "code": null, "e": 2029, "s": 1629, "text": "#include <stdio.h>\nint main() {\n int num1, num2, x, y, temp, gcd, lcm;\n printf(\"Enter two integers\\n\");\n scanf(\"%d%d\", &x, &y);\n num1 = x;\n num2 = y;\n while (num2 != 0) {\n temp = num2;\n num2 = num1 % num2;\n num1 = temp;\n }\n gcd = num1;\n lcm = (x*y)/gcd;\n printf(\"GCD of %d and %d = %d\\n\", x, y, gcd);\n printf(\"LCM of %d and %d = %d\\n\", x, y, lcm);\n return 0;\n}" }, { "code": null, "e": 2085, "s": 2029, "text": "Upon execution, you will receive the following output −" }, { "code": null, "e": 2233, "s": 2085, "text": "Run 1:\nEnter two integers\n6 12\nGCD of 6 and 12 = 6\nLCM of 6 and 12 = 12\nRun 2:\nEnter two integers\n24 36\nGCD of 24 and 36 = 12\nLCM of 24 and 36 = 72" } ]
GATE | GATE-CS-2014-(Set-3) | Question 65 - GeeksforGeeks
20 Sep, 2021 Let X denote the Exclusive OR (XOR) operation. Let ‘1’ and ‘0’ denote the binary constants. Consider the following Boolean expression for F over two variables P and Q: F(P, Q) = ( ( 1 X P) X (P X Q) ) X ( (P X Q) X (Q X 0) ) The equivalent expression for F is(A) P + Q(B) (P + Q)’(C) P X Q(D) (P X Q)’Answer: (D)Explanation: We need to simplify the above expression. As the given operation is XOR, we shall see property of XOR. Let A and B be boolean variable. In A XOR B, the result is 1 if both the bits/inputs are different, else 0. Now, ( ( 1 X P) X (P X Q) ) X ( (P X Q) X (Q X 0) ) ( P' X P X Q ) X ( P X Q X Q ) ( as 1 X P = P' and Q X 0 = Q ) (1 X Q) X ( P X 0) ( as P' X P = 1 , and Q X Q = 0 ) Q' X P ( as 1 X Q = Q' and P X 0 = P ) PQ + P'Q' ( XOR Expansion, A X B = AB' + A'B ) This is the final simplified expression. Now we need to check for the options. If we simplify option D expression. ( P X Q )' = ( PQ' + P'Q )' ( XOR Expansion, A X B = AB' + A'B ) ((PQ')'.(P'Q)') ( De Morgan's law ) ( P'+ Q).(P + Q') ( De Morgan's law ) P'P + PQ + P'Q' + QQ' PQ + P'Q' ( as PP' = 0 and QQ' = 0 ) Hence both the equations are same. Therefore Option D. YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersBoolean Algebra and Identities | GATE PYQs with Rishabh Setiya | GeeksforGeeks GATEWatch 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:001:00 / 22:24•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=mDkgr_tIfYc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Quiz of this Question GATE-CS-2014-(Set-3) GATE-GATE-CS-2014-(Set-3) 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": 25649, "s": 25621, "text": "\n20 Sep, 2021" }, { "code": null, "e": 25817, "s": 25649, "text": "Let X denote the Exclusive OR (XOR) operation. Let ‘1’ and ‘0’ denote the binary constants. Consider the following Boolean expression for F over two variables P and Q:" }, { "code": null, "e": 25875, "s": 25817, "text": "F(P, Q) = ( ( 1 X P) X (P X Q) ) X ( (P X Q) X (Q X 0) ) " }, { "code": null, "e": 26078, "s": 25875, "text": "The equivalent expression for F is(A) P + Q(B) (P + Q)’(C) P X Q(D) (P X Q)’Answer: (D)Explanation: We need to simplify the above expression. As the given operation is XOR, we shall see property of XOR." }, { "code": null, "e": 26111, "s": 26078, "text": "Let A and B be boolean variable." }, { "code": null, "e": 26186, "s": 26111, "text": "In A XOR B, the result is 1 if both the bits/inputs are different, else 0." }, { "code": null, "e": 26191, "s": 26186, "text": "Now," }, { "code": null, "e": 26824, "s": 26191, "text": "\n( ( 1 X P) X (P X Q) ) X ( (P X Q) X (Q X 0) )\n\n( P' X P X Q ) X ( P X Q X Q ) ( as 1 X P = P' and Q X 0 = Q )\n\n(1 X Q) X ( P X 0) ( as P' X P = 1 , and Q X Q = 0 )\n\nQ' X P ( as 1 X Q = Q' and P X 0 = P )\n\nPQ + P'Q' ( XOR Expansion, A X B = AB' + A'B )\n\nThis is the final simplified expression.\n\nNow we need to check for the options.\n\nIf we simplify option D expression.\n\n( P X Q )' = ( PQ' + P'Q )' ( XOR Expansion, A X B = AB' + A'B )\n\n((PQ')'.(P'Q)') ( De Morgan's law )\n\n( P'+ Q).(P + Q') ( De Morgan's law )\n\nP'P + PQ + P'Q' + QQ'\n\nPQ + P'Q' ( as PP' = 0 and QQ' = 0 ) \n\nHence both the equations are same. Therefore Option D. " }, { "code": null, "e": 27715, "s": 26824, "text": "YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersBoolean Algebra and Identities | GATE PYQs with Rishabh Setiya | GeeksforGeeks GATEWatch 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:001:00 / 22:24•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=mDkgr_tIfYc\" 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": 27737, "s": 27715, "text": "Quiz of this Question" }, { "code": null, "e": 27758, "s": 27737, "text": "GATE-CS-2014-(Set-3)" }, { "code": null, "e": 27784, "s": 27758, "text": "GATE-GATE-CS-2014-(Set-3)" }, { "code": null, "e": 27789, "s": 27784, "text": "GATE" }, { "code": null, "e": 27887, "s": 27789, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27921, "s": 27887, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 27955, "s": 27921, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 27989, "s": 27955, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 28022, "s": 27989, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 28058, "s": 28022, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 28092, "s": 28058, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 28128, "s": 28092, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 28162, "s": 28128, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 28196, "s": 28162, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Statistical - NORM.S.INV Function
The NORMS.S.INV function returns the inverse of the standard normal cumulative distribution. The distribution has a mean of zero and a standard deviation of one. NORM.S.INV (probability) If probability is nonnumeric, NORMS.INV returns the #VALUE! error value. If probability is nonnumeric, NORMS.INV returns the #VALUE! error value. If probability <= 0 or if probability >= 1, NORMS.INV returns the #NUM! error value. If probability <= 0 or if probability >= 1, NORMS.INV returns the #NUM! error value. Given a value for probability, NORM.S.INV seeks that value z such that NORM.S.DIST (z,TRUE) = probability Given a value for probability, NORM.S.INV seeks that value z such that NORM.S.DIST (z,TRUE) = probability Thus, precision of NORM.S.INV depends on precision of NORM.S.DIST. NORM.S.INV uses an iterative search technique. Excel 2010, Excel 2013, Excel 2016 296 Lectures 146 hours Arun Motoori 56 Lectures 5.5 hours Pavan Lalwani 120 Lectures 6.5 hours Inf Sid 134 Lectures 8.5 hours Yoda Learning 46 Lectures 7.5 hours William Fiset 25 Lectures 1.5 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2016, "s": 1854, "text": "The NORMS.S.INV function returns the inverse of the standard normal cumulative distribution. The distribution has a mean of zero and a standard deviation of one." }, { "code": null, "e": 2042, "s": 2016, "text": "NORM.S.INV (probability)\n" }, { "code": null, "e": 2115, "s": 2042, "text": "If probability is nonnumeric, NORMS.INV returns the #VALUE! error value." }, { "code": null, "e": 2188, "s": 2115, "text": "If probability is nonnumeric, NORMS.INV returns the #VALUE! error value." }, { "code": null, "e": 2273, "s": 2188, "text": "If probability <= 0 or if probability >= 1, NORMS.INV returns the #NUM! error value." }, { "code": null, "e": 2358, "s": 2273, "text": "If probability <= 0 or if probability >= 1, NORMS.INV returns the #NUM! error value." }, { "code": null, "e": 2465, "s": 2358, "text": "Given a value for probability, NORM.S.INV seeks that value z such that\nNORM.S.DIST (z,TRUE) = probability\n" }, { "code": null, "e": 2536, "s": 2465, "text": "Given a value for probability, NORM.S.INV seeks that value z such that" }, { "code": null, "e": 2571, "s": 2536, "text": "NORM.S.DIST (z,TRUE) = probability" }, { "code": null, "e": 2685, "s": 2571, "text": "Thus, precision of NORM.S.INV depends on precision of NORM.S.DIST. NORM.S.INV uses an iterative search technique." }, { "code": null, "e": 2720, "s": 2685, "text": "Excel 2010, Excel 2013, Excel 2016" }, { "code": null, "e": 2756, "s": 2720, "text": "\n 296 Lectures \n 146 hours \n" }, { "code": null, "e": 2770, "s": 2756, "text": " Arun Motoori" }, { "code": null, "e": 2805, "s": 2770, "text": "\n 56 Lectures \n 5.5 hours \n" }, { "code": null, "e": 2820, "s": 2805, "text": " Pavan Lalwani" }, { "code": null, "e": 2856, "s": 2820, "text": "\n 120 Lectures \n 6.5 hours \n" }, { "code": null, "e": 2865, "s": 2856, "text": " Inf Sid" }, { "code": null, "e": 2901, "s": 2865, "text": "\n 134 Lectures \n 8.5 hours \n" }, { "code": null, "e": 2916, "s": 2901, "text": " Yoda Learning" }, { "code": null, "e": 2951, "s": 2916, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 2966, "s": 2951, "text": " William Fiset" }, { "code": null, "e": 3001, "s": 2966, "text": "\n 25 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3015, "s": 3001, "text": " Sasha Miller" }, { "code": null, "e": 3022, "s": 3015, "text": " Print" }, { "code": null, "e": 3033, "s": 3022, "text": " Add Notes" } ]
Swing Examples - Show Confirm Dialog with custom buttons
Following example showcase how to show confirm dialog with customized button texts in swing based application. We are using the following APIs. JOptionPane − To create a standard dialog box. JOptionPane − To create a standard dialog box. JOptionPane.showOptionDialog() − To show the message alert with multiple options. JOptionPane.showOptionDialog() − To show the message alert with multiple options. JOptionPane.YES_NO_OPTION − To get Yes and No buttons. JOptionPane.YES_NO_OPTION − To get Yes and No buttons. import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.LayoutManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; public class SwingTester { public static void main(String[] args) { createWindow(); } private static void createWindow() { JFrame frame = new JFrame("Swing Tester"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); createUI(frame); frame.setSize(560, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void createUI(final JFrame frame){ JPanel panel = new JPanel(); LayoutManager layout = new FlowLayout(); panel.setLayout(layout); JButton button = new JButton("Click Me!"); final JLabel label = new JLabel(); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String[] options = {"Yes! Please.", "No! Not now."}; int result = JOptionPane.showOptionDialog( frame, "Sure? You want to exit?", "Swing Tester", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, //no custom icon options, //button titles options[0] //default button ); if(result == JOptionPane.YES_OPTION){ label.setText("You selected: Yes! Please"); }else if (result == JOptionPane.NO_OPTION){ label.setText("You selected: No! Not now."); }else { label.setText("None selected"); } } }); panel.add(button); panel.add(label); frame.getContentPane().add(panel, BorderLayout.CENTER); } } Print Add Notes Bookmark this page
[ { "code": null, "e": 2150, "s": 2039, "text": "Following example showcase how to show confirm dialog with customized button texts in swing based application." }, { "code": null, "e": 2183, "s": 2150, "text": "We are using the following APIs." }, { "code": null, "e": 2230, "s": 2183, "text": "JOptionPane − To create a standard dialog box." }, { "code": null, "e": 2277, "s": 2230, "text": "JOptionPane − To create a standard dialog box." }, { "code": null, "e": 2359, "s": 2277, "text": "JOptionPane.showOptionDialog() − To show the message alert with multiple options." }, { "code": null, "e": 2441, "s": 2359, "text": "JOptionPane.showOptionDialog() − To show the message alert with multiple options." }, { "code": null, "e": 2496, "s": 2441, "text": "JOptionPane.YES_NO_OPTION − To get Yes and No buttons." }, { "code": null, "e": 2551, "s": 2496, "text": "JOptionPane.YES_NO_OPTION − To get Yes and No buttons." }, { "code": null, "e": 4552, "s": 2551, "text": "import java.awt.BorderLayout;\nimport java.awt.FlowLayout;\nimport java.awt.LayoutManager;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\n\npublic class SwingTester {\n public static void main(String[] args) {\n createWindow();\n }\n\n private static void createWindow() { \n JFrame frame = new JFrame(\"Swing Tester\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n createUI(frame);\n frame.setSize(560, 200); \n frame.setLocationRelativeTo(null); \n frame.setVisible(true);\n }\n\n private static void createUI(final JFrame frame){ \n JPanel panel = new JPanel();\n LayoutManager layout = new FlowLayout(); \n panel.setLayout(layout); \n\n JButton button = new JButton(\"Click Me!\");\n final JLabel label = new JLabel();\n button.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n String[] options = {\"Yes! Please.\", \"No! Not now.\"}; \n int result = JOptionPane.showOptionDialog(\n frame,\n \"Sure? You want to exit?\", \n \"Swing Tester\", \n JOptionPane.YES_NO_OPTION,\n JOptionPane.QUESTION_MESSAGE,\n null, //no custom icon\n options, //button titles\n options[0] //default button\n );\n if(result == JOptionPane.YES_OPTION){\n label.setText(\"You selected: Yes! Please\");\n }else if (result == JOptionPane.NO_OPTION){\n label.setText(\"You selected: No! Not now.\");\n }else {\n label.setText(\"None selected\");\n }\n }\n });\n\n panel.add(button);\n panel.add(label);\n frame.getContentPane().add(panel, BorderLayout.CENTER); \n } \n} " }, { "code": null, "e": 4559, "s": 4552, "text": " Print" }, { "code": null, "e": 4570, "s": 4559, "text": " Add Notes" } ]
Five Advanced Plots in Python — Matplotlib | by Rashida Nasrin Sucky | Towards Data Science
Data visualization is probably the most widely used feature in data science for obvious reasons. Visualization is the best way to present and understand data. So, it is a good idea to have a lot of visualization tools in hand. Because different kind of visualization is appropriate in a different situation. In this article, I will share some code for five 3d visualizations in Matplotlib. I am assuming, you know 2d plots in Matplotlib. So, I won’t go for too much discussion. This article will simply demonstrate how to make these five plots. The five 3d plots I will demonstrate in this article: Scatter PlotContour PlotTri-Surf PlotSurface PlotBar Plot Scatter Plot Contour Plot Tri-Surf Plot Surface Plot Bar Plot I am using a dataset from Kaggle for this article. Please feel free to download the dataset from this link if you want to run this code yourself. This is an open dataset that is mentioned here. First import the necessary packages and the dataset: import pandas as pdimport numpy as npfrom mpl_toolkits import mplot3dimport matplotlib.pyplot as pltdf = pd.read_csv("auto_clean.csv") The dataset is pretty big. So I am not showing any screenshots here. These are the columns of this dataset: df.columns Output: Index(['symboling', 'normalized-losses', 'make', 'aspiration', 'num-of-doors','body-style', 'drive-wheels', 'engine-location', 'wheel-base', 'length', 'width', 'height', 'curb-weight', 'engine-type', 'num-of-cylinders', 'engine-size', 'fuel-system', 'bore', 'stroke', 'compression-ratio', 'horsepower', 'peak-rpm', 'city-mpg', 'highway-mpg', 'price', 'city-L/100km', 'horsepower-binned', 'diesel', 'gas'] ,dtype='object') Let’s move to the plotting part. The scatter plot is pretty self-explanatory. I am assuming that you know the 2d scatter plot. To make a 3d scatter plot, we just need to use the ‘scatter3D’ function and pass x, y, and z values. I choose to use the height, width, and length for x, y, and z values. To add some more information and also to add some style I will pass the price as a size parameter. I feel like a scatter plot looks nice when it has different sizes of bubbles and different colors. At the same time, size includes some more information. So, the bigger the bubbles more the price. This same plot will give an idea of how price differs with height, width, and length. Colors are also changing with peak RPM. %matplotlib notebookfig = plt.figure(figsize=(10, 10))ax = plt.axes(projection="3d")ax.scatter3D(df['length'], df['width'], df['height'], c = df['peak-rpm'], s = df['price']/50, alpha = 0.4)ax.set_xlabel("Length")ax.set_ylabel("Width")ax.set_zlabel("Height")ax.set_title("Relationship between height, weight, and length")plt.show() This plot is interactive that helps to understand the data even better: Bar plot is always useful. But when it is a 3D bar plot can be even more useful. Here I will plot the price with respect to the body style and peak RPM. For doing that a little data preparation is necessary. First of all, body style is a categorical variable. The values of the body_style column are as follows: df['body-style'].unique() Output: array(['convertible', 'hatchback', 'sedan', 'wagon', 'hardtop'], dtype=object) These strings need to be replaced with numeric values: df['body_style1'] = df['body-style'].replace({"convertible": 1, "hatchback": 2, "sedan": 3, "wagon": 4, "hardtop": 5}) Now, I will find the average peak rpm and price for each body style. gr = df.groupby("body_style1")['peak-rpm', 'price'].agg('mean') Output: For the 3d bar plot, we obviously need to pass the x, y, and z values to the bar3d function as you can expect. But also it asks for dx, dy, and dz. First, think of the 2d plane where the bars will be placed, where we only can use x and y values, and z values are zeros. So, we will use body_style1 in the x-axis and peak-rpm in the y axis, and z values will be zeros on the 2d plane as discussed already. Next, we should specify the size of the bars. I am using the width of 0 .3 on the x-axis, a width of 30 on the y-axis and the height will be the value of the price column. That means, dx = 0.3 dy = 30 dz = gr[‘price’] Here is the code snippet for the bar plot: %matplotlib notebookx = gr.indexy = gr['peak-rpm']z = [0]*5colors = ["b", "g", "crimson", 'r', 'pink']dx = 0.3 * np.ones_like(z)dy = [30]*5dz = gr['price']fig = plt.figure(figsize=(10, 8))ax = fig.add_subplot(111, projection="3d")ax.set_xticklabels(['convertible', 'hatchback', 'sedan', 'wagon', 'hardtop'])ax.set_xlabel("Body Style", labelpad = 7)ax.set_yticks(np.linspace(5000, 5250, 6))ax.set_ylabel("Peak Rpm", labelpad=10)ax.set_zlabel("Price")ax.set_zticks(np.linspace(7000, 22250, 6))ax.set_title("Change of Price with Body_style and Peak RPM")ax.bar3d(x, y, z, dx, dy, dz) Here is the full view of the bar plot: Here is the bar plot! For this type of plot one-dimensional x and y values do not work. So, we need to use the ‘meshgrid’ function to generate a rectangular grid out of two one-dimensional arrays. This plot shows the relationship between two variables in a 3d setting. I choose to see the relationship between the length and width in this plot. Here is the code for this surface plot: def z_function(x, y): return np.sin(np.sqrt(x**2 + y**2))plt.figure(figsize=(10, 10))ax = plt.axes(projection="3d")x = df['length']y = df['width']X, Y = np.meshgrid(x, y)Z = z_function(X, Y)ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='winter', edgecolor='none')ax.set_xlabel("Length")ax.set_ylabel("Width")ax.set_title("Peak RPM vs City-MPG")ax.view_init(65, 30) Here is the full view of the surface plot Maybe you already know the 2d contour plot. Here I am showing the relationship between the peak RPM and the city-MPG using a 3d contour plot. In this example, I am using the sin function for z values. Feel free to try it with the cosine function. Here is the code snippet: %matplotlib notebookdef z_function(x, y): return np.sin(np.sqrt(x**2 + y**2))plt.figure(figsize=(10, 10))ax = plt.axes(projection="3d")x = df['peak-rpm']y = df['city-mpg']X, Y = np.meshgrid(x, y)Z = z_function(X, Y)ax.contour3D(X, Y, Z, rstride=1, cstride=1, cmap='binary', edgecolor='none')ax.set_xlabel("Peak RPM")ax.set_ylabel("City-MPG")ax.set_title("Peak RPM vs City-MPG")ax.view_init(60, 35)plt.show() Here is the full view of this contour plot Please try with cosine for the z-function and see how the contour with cosine looks with the same data. Let’s see how a tri-surf plot looks like. We do not need a mesh grid for the tri-surf plot. Simple one-dimensional data is good for x and y-direction. Here is the code. %matplotlib notebookplt.figure(figsize=(8, 8))ax = plt.axes(projection="3d")x = df['peak-rpm']y = df['city-mpg']z = z_function(x, y)ax.plot_trisurf(x, y, z, cmap='viridis', edgecolor='none');ax.set_xlabel("Peak RPM")ax.set_ylabel("City-MPG")ax.set_title("Peak RPM vs City-MPG")ax.view_init(60, 25)plt.show() Here is the full shape of the plot These are the five plots I wanted to share in this article. I hope you will be using them in your own projects. Feel free to follow me on Twitter and check out my new YouTube channel.
[ { "code": null, "e": 562, "s": 172, "text": "Data visualization is probably the most widely used feature in data science for obvious reasons. Visualization is the best way to present and understand data. So, it is a good idea to have a lot of visualization tools in hand. Because different kind of visualization is appropriate in a different situation. In this article, I will share some code for five 3d visualizations in Matplotlib." }, { "code": null, "e": 717, "s": 562, "text": "I am assuming, you know 2d plots in Matplotlib. So, I won’t go for too much discussion. This article will simply demonstrate how to make these five plots." }, { "code": null, "e": 771, "s": 717, "text": "The five 3d plots I will demonstrate in this article:" }, { "code": null, "e": 829, "s": 771, "text": "Scatter PlotContour PlotTri-Surf PlotSurface PlotBar Plot" }, { "code": null, "e": 842, "s": 829, "text": "Scatter Plot" }, { "code": null, "e": 855, "s": 842, "text": "Contour Plot" }, { "code": null, "e": 869, "s": 855, "text": "Tri-Surf Plot" }, { "code": null, "e": 882, "s": 869, "text": "Surface Plot" }, { "code": null, "e": 891, "s": 882, "text": "Bar Plot" }, { "code": null, "e": 942, "s": 891, "text": "I am using a dataset from Kaggle for this article." }, { "code": null, "e": 1085, "s": 942, "text": "Please feel free to download the dataset from this link if you want to run this code yourself. This is an open dataset that is mentioned here." }, { "code": null, "e": 1138, "s": 1085, "text": "First import the necessary packages and the dataset:" }, { "code": null, "e": 1273, "s": 1138, "text": "import pandas as pdimport numpy as npfrom mpl_toolkits import mplot3dimport matplotlib.pyplot as pltdf = pd.read_csv(\"auto_clean.csv\")" }, { "code": null, "e": 1381, "s": 1273, "text": "The dataset is pretty big. So I am not showing any screenshots here. These are the columns of this dataset:" }, { "code": null, "e": 1392, "s": 1381, "text": "df.columns" }, { "code": null, "e": 1400, "s": 1392, "text": "Output:" }, { "code": null, "e": 1823, "s": 1400, "text": "Index(['symboling', 'normalized-losses', 'make', 'aspiration', 'num-of-doors','body-style', 'drive-wheels', 'engine-location', 'wheel-base', 'length', 'width', 'height', 'curb-weight', 'engine-type', 'num-of-cylinders', 'engine-size', 'fuel-system', 'bore', 'stroke', 'compression-ratio', 'horsepower', 'peak-rpm', 'city-mpg', 'highway-mpg', 'price', 'city-L/100km', 'horsepower-binned', 'diesel', 'gas'] ,dtype='object')" }, { "code": null, "e": 1856, "s": 1823, "text": "Let’s move to the plotting part." }, { "code": null, "e": 2121, "s": 1856, "text": "The scatter plot is pretty self-explanatory. I am assuming that you know the 2d scatter plot. To make a 3d scatter plot, we just need to use the ‘scatter3D’ function and pass x, y, and z values. I choose to use the height, width, and length for x, y, and z values." }, { "code": null, "e": 2374, "s": 2121, "text": "To add some more information and also to add some style I will pass the price as a size parameter. I feel like a scatter plot looks nice when it has different sizes of bubbles and different colors. At the same time, size includes some more information." }, { "code": null, "e": 2543, "s": 2374, "text": "So, the bigger the bubbles more the price. This same plot will give an idea of how price differs with height, width, and length. Colors are also changing with peak RPM." }, { "code": null, "e": 2888, "s": 2543, "text": "%matplotlib notebookfig = plt.figure(figsize=(10, 10))ax = plt.axes(projection=\"3d\")ax.scatter3D(df['length'], df['width'], df['height'], c = df['peak-rpm'], s = df['price']/50, alpha = 0.4)ax.set_xlabel(\"Length\")ax.set_ylabel(\"Width\")ax.set_zlabel(\"Height\")ax.set_title(\"Relationship between height, weight, and length\")plt.show()" }, { "code": null, "e": 2960, "s": 2888, "text": "This plot is interactive that helps to understand the data even better:" }, { "code": null, "e": 3272, "s": 2960, "text": "Bar plot is always useful. But when it is a 3D bar plot can be even more useful. Here I will plot the price with respect to the body style and peak RPM. For doing that a little data preparation is necessary. First of all, body style is a categorical variable. The values of the body_style column are as follows:" }, { "code": null, "e": 3298, "s": 3272, "text": "df['body-style'].unique()" }, { "code": null, "e": 3306, "s": 3298, "text": "Output:" }, { "code": null, "e": 3390, "s": 3306, "text": "array(['convertible', 'hatchback', 'sedan', 'wagon', 'hardtop'], dtype=object)" }, { "code": null, "e": 3445, "s": 3390, "text": "These strings need to be replaced with numeric values:" }, { "code": null, "e": 3740, "s": 3445, "text": "df['body_style1'] = df['body-style'].replace({\"convertible\": 1, \"hatchback\": 2, \"sedan\": 3, \"wagon\": 4, \"hardtop\": 5})" }, { "code": null, "e": 3809, "s": 3740, "text": "Now, I will find the average peak rpm and price for each body style." }, { "code": null, "e": 3873, "s": 3809, "text": "gr = df.groupby(\"body_style1\")['peak-rpm', 'price'].agg('mean')" }, { "code": null, "e": 3881, "s": 3873, "text": "Output:" }, { "code": null, "e": 4029, "s": 3881, "text": "For the 3d bar plot, we obviously need to pass the x, y, and z values to the bar3d function as you can expect. But also it asks for dx, dy, and dz." }, { "code": null, "e": 4286, "s": 4029, "text": "First, think of the 2d plane where the bars will be placed, where we only can use x and y values, and z values are zeros. So, we will use body_style1 in the x-axis and peak-rpm in the y axis, and z values will be zeros on the 2d plane as discussed already." }, { "code": null, "e": 4470, "s": 4286, "text": "Next, we should specify the size of the bars. I am using the width of 0 .3 on the x-axis, a width of 30 on the y-axis and the height will be the value of the price column. That means," }, { "code": null, "e": 4479, "s": 4470, "text": "dx = 0.3" }, { "code": null, "e": 4487, "s": 4479, "text": "dy = 30" }, { "code": null, "e": 4504, "s": 4487, "text": "dz = gr[‘price’]" }, { "code": null, "e": 4547, "s": 4504, "text": "Here is the code snippet for the bar plot:" }, { "code": null, "e": 5128, "s": 4547, "text": "%matplotlib notebookx = gr.indexy = gr['peak-rpm']z = [0]*5colors = [\"b\", \"g\", \"crimson\", 'r', 'pink']dx = 0.3 * np.ones_like(z)dy = [30]*5dz = gr['price']fig = plt.figure(figsize=(10, 8))ax = fig.add_subplot(111, projection=\"3d\")ax.set_xticklabels(['convertible', 'hatchback', 'sedan', 'wagon', 'hardtop'])ax.set_xlabel(\"Body Style\", labelpad = 7)ax.set_yticks(np.linspace(5000, 5250, 6))ax.set_ylabel(\"Peak Rpm\", labelpad=10)ax.set_zlabel(\"Price\")ax.set_zticks(np.linspace(7000, 22250, 6))ax.set_title(\"Change of Price with Body_style and Peak RPM\")ax.bar3d(x, y, z, dx, dy, dz)" }, { "code": null, "e": 5167, "s": 5128, "text": "Here is the full view of the bar plot:" }, { "code": null, "e": 5189, "s": 5167, "text": "Here is the bar plot!" }, { "code": null, "e": 5364, "s": 5189, "text": "For this type of plot one-dimensional x and y values do not work. So, we need to use the ‘meshgrid’ function to generate a rectangular grid out of two one-dimensional arrays." }, { "code": null, "e": 5436, "s": 5364, "text": "This plot shows the relationship between two variables in a 3d setting." }, { "code": null, "e": 5552, "s": 5436, "text": "I choose to see the relationship between the length and width in this plot. Here is the code for this surface plot:" }, { "code": null, "e": 5940, "s": 5552, "text": "def z_function(x, y): return np.sin(np.sqrt(x**2 + y**2))plt.figure(figsize=(10, 10))ax = plt.axes(projection=\"3d\")x = df['length']y = df['width']X, Y = np.meshgrid(x, y)Z = z_function(X, Y)ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='winter', edgecolor='none')ax.set_xlabel(\"Length\")ax.set_ylabel(\"Width\")ax.set_title(\"Peak RPM vs City-MPG\")ax.view_init(65, 30)" }, { "code": null, "e": 5982, "s": 5940, "text": "Here is the full view of the surface plot" }, { "code": null, "e": 6124, "s": 5982, "text": "Maybe you already know the 2d contour plot. Here I am showing the relationship between the peak RPM and the city-MPG using a 3d contour plot." }, { "code": null, "e": 6229, "s": 6124, "text": "In this example, I am using the sin function for z values. Feel free to try it with the cosine function." }, { "code": null, "e": 6255, "s": 6229, "text": "Here is the code snippet:" }, { "code": null, "e": 6680, "s": 6255, "text": "%matplotlib notebookdef z_function(x, y): return np.sin(np.sqrt(x**2 + y**2))plt.figure(figsize=(10, 10))ax = plt.axes(projection=\"3d\")x = df['peak-rpm']y = df['city-mpg']X, Y = np.meshgrid(x, y)Z = z_function(X, Y)ax.contour3D(X, Y, Z, rstride=1, cstride=1, cmap='binary', edgecolor='none')ax.set_xlabel(\"Peak RPM\")ax.set_ylabel(\"City-MPG\")ax.set_title(\"Peak RPM vs City-MPG\")ax.view_init(60, 35)plt.show()" }, { "code": null, "e": 6723, "s": 6680, "text": "Here is the full view of this contour plot" }, { "code": null, "e": 6827, "s": 6723, "text": "Please try with cosine for the z-function and see how the contour with cosine looks with the same data." }, { "code": null, "e": 6978, "s": 6827, "text": "Let’s see how a tri-surf plot looks like. We do not need a mesh grid for the tri-surf plot. Simple one-dimensional data is good for x and y-direction." }, { "code": null, "e": 6996, "s": 6978, "text": "Here is the code." }, { "code": null, "e": 7319, "s": 6996, "text": "%matplotlib notebookplt.figure(figsize=(8, 8))ax = plt.axes(projection=\"3d\")x = df['peak-rpm']y = df['city-mpg']z = z_function(x, y)ax.plot_trisurf(x, y, z, cmap='viridis', edgecolor='none');ax.set_xlabel(\"Peak RPM\")ax.set_ylabel(\"City-MPG\")ax.set_title(\"Peak RPM vs City-MPG\")ax.view_init(60, 25)plt.show()" }, { "code": null, "e": 7354, "s": 7319, "text": "Here is the full shape of the plot" }, { "code": null, "e": 7466, "s": 7354, "text": "These are the five plots I wanted to share in this article. I hope you will be using them in your own projects." } ]
Filter null from an array in JavaScript?
To filter null from an array and display only non-null values instead, use filter(). Following is the code − var names=[null,"John",null,"David","","Mike",null,undefined,"Bob","Adam",null,null]; console.log("Before filter null="); console.log(names); var filterNull=[]; filterNullValues=names.filter(obj=>obj); console.log("After filtering the null values="); console.log(filterNullValues); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo148.js. This will produce the following output − PS C:\Users\Amit\JavaScript-code> node demo148.js Before filter null=[ null, 'John', null, 'David', '', 'Mike', null, undefined, 'Bob', 'Adam', null, null ] After filtering the null values= [ 'John', 'David', 'Mike', 'Bob', 'Adam' ]
[ { "code": null, "e": 1171, "s": 1062, "text": "To filter null from an array and display only non-null values instead, use filter(). Following is the\ncode −" }, { "code": null, "e": 1453, "s": 1171, "text": "var\nnames=[null,\"John\",null,\"David\",\"\",\"Mike\",null,undefined,\"Bob\",\"Adam\",null,null];\nconsole.log(\"Before filter null=\");\nconsole.log(names);\nvar filterNull=[];\nfilterNullValues=names.filter(obj=>obj);\nconsole.log(\"After filtering the null values=\");\nconsole.log(filterNullValues);" }, { "code": null, "e": 1519, "s": 1453, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1537, "s": 1519, "text": "node fileName.js." }, { "code": null, "e": 1612, "s": 1537, "text": "Here, my file name is demo148.js. This will produce the following output −" }, { "code": null, "e": 1863, "s": 1612, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo148.js\nBefore filter null=[\n null, 'John',\n null, 'David',\n '', 'Mike',\n null, undefined,\n 'Bob', 'Adam',\n null, null\n]\nAfter filtering the null values=\n[ 'John', 'David', 'Mike', 'Bob', 'Adam' ]" } ]
C++ Program to Implement Trie
Here we shall discuss a C++ Program to implement Trie. It is a tree based data structure, used for efficient retrieval of a key in a large data-set of strings. Begin function insert() : If key not present, inserts key into trie. If the key is prefix of trie node, just mark leaf node. End Begin function deleteNode() If tree is empty then return null. If last character of the key is being processed, then that node will be no more end of string after deleting it. If given key is not prefix of any other string, then delete it and set root = NULL. If key is not the last character, Then recur for the child which will be obtained by using ASCII value. If root does not have any child left and it is not end of another word, Then delete it and set root = NULL. End #include <bits/stdc++.h> using namespace std; const int ALPHA_SIZE = 26; struct Trie { struct Trie *child[ALPHA_SIZE]; bool endofstring; //It is true if node represents end of word. }; struct Trie *createNode(void) //creation of new node { struct Trie *tNode = new Trie; tNode->endofstring = false; for (int i = 0; i < ALPHA_SIZE; i++) tNode->child[i] = NULL; return tNode; } void insert(struct Trie *root, string key) { struct Trie *curr = root; for (int i = 0; i < key.length(); i++) { int index = key[i] - 'A'; if (!curr->child[index]) curr->child[index] = createNode(); curr = curr->child[index]; } curr->endofstring= true; //last node as leaf } bool search(struct Trie *root, string key) { //check if key is present in trie. If present returns true struct Trie *curr = root; for (int i = 0; i < key.length(); i++) { int index = key[i] - 'A'; if (!curr->child[index]) return false; curr = curr->child[index]; } return (curr != NULL && curr->endofstring); } bool isEmpty(Trie* root) //check if root has children or not { for (int i = 0; i < ALPHA_SIZE; i++) if (root->child[i]) return false; return true; } Trie* deletion(Trie* root, string key, int depth = 0) { //If tree is empty return null. if (!root) return NULL; if (depth == key.size()) { //If last character of key is being processed, if (root->endofstring) root->endofstring = false; //then that node will be no more end of string after deleting it. if (isEmpty(root)) { //If given key is not prefix of any other string, delete (root); root = NULL; } return root; } //If key not last character, int index = key[depth] - 'A'; root->child[index] = deletion(root->child[index], key, depth + 1); //Then recur for the child which will be obtained by using ASCII value. if (isEmpty(root) && root->endofstring == false) { //If root does not have any child leftand it is not end of another word delete (root); root = NULL; } return root; } int main() { string inputs[] = {"HELLOWORLD","HI","BYE", "THE","THENA"}; // Input keys ( only A to Z in upper case) int n = sizeof(inputs)/sizeof(inputs[0]); struct Trie *root = createNode(); for (int i = 0; i < n; i++) insert(root, inputs[i]); search(root, "HELLOWORLD")? cout << "Key is Found\n" : cout << "Key is not Found\n"; search(root, "HE")? cout << "Key is Found\n" : cout << "Key is not Found\n"; deletion(root, "THEN")? cout << "Key is deleted\n" : cout << "Key is not Deleted\n"; return 0; } Key is Found Key is not Found Key is deleted
[ { "code": null, "e": 1222, "s": 1062, "text": "Here we shall discuss a C++ Program to implement Trie. It is a tree based data structure, used for efficient retrieval of a key in a large data-set of strings." }, { "code": null, "e": 1866, "s": 1222, "text": "Begin\nfunction insert() :\n If key not present, inserts key into trie. If the key is prefix of trie node, just mark leaf node.\nEnd\nBegin\nfunction deleteNode()\n If tree is empty then return null.\n If last character of the key is being processed,\n then that node will be no more end of string after deleting it.\n If given key is not prefix of any other string, then delete it and set root = NULL.\n If key is not the last character,\n Then recur for the child which will be obtained by using ASCII value.\n If root does not have any child left and it is not end of another word,\n Then delete it and set root = NULL.\nEnd" }, { "code": null, "e": 4514, "s": 1866, "text": "#include <bits/stdc++.h>\nusing namespace std;\nconst int ALPHA_SIZE = 26;\n\nstruct Trie {\n struct Trie *child[ALPHA_SIZE];\n bool endofstring; //It is true if node represents end of word.\n};\nstruct Trie *createNode(void) //creation of new node {\n struct Trie *tNode = new Trie;\n tNode->endofstring = false;\n for (int i = 0; i < ALPHA_SIZE; i++)\n tNode->child[i] = NULL;\n return tNode;\n}\nvoid insert(struct Trie *root, string key) {\n struct Trie *curr = root;\n for (int i = 0; i < key.length(); i++) {\n int index = key[i] - 'A';\n if (!curr->child[index])\n curr->child[index] = createNode();\n curr = curr->child[index];\n }\n curr->endofstring= true; //last node as leaf\n}\nbool search(struct Trie *root, string key) { //check if key is present in trie. If present returns true\n struct Trie *curr = root;\n for (int i = 0; i < key.length(); i++) {\n int index = key[i] - 'A';\n if (!curr->child[index])\n return false;\n curr = curr->child[index];\n }\n return (curr != NULL && curr->endofstring);\n}\nbool isEmpty(Trie* root) //check if root has children or not {\n for (int i = 0; i < ALPHA_SIZE; i++)\n if (root->child[i])\n return false;\n return true;\n}\nTrie* deletion(Trie* root, string key, int depth = 0) {\n //If tree is empty return null.\n if (!root)\n return NULL;\n if (depth == key.size()) { //If last character of key is being processed,\n if (root->endofstring)\n root->endofstring = false; //then that node will be no more end of string after deleting it.\n if (isEmpty(root)) { //If given key is not prefix of any other string,\n delete (root);\n root = NULL;\n }\n return root;\n }\n //If key not last character,\n int index = key[depth] - 'A';\n root->child[index] =\n deletion(root->child[index], key, depth + 1); //Then recur for the child which will be obtained by using ASCII value.\n if (isEmpty(root) && root->endofstring == false) { //If root does not have any child leftand it is not end of another word\n delete (root);\n root = NULL;\n }\n return root;\n}\nint main() {\n string inputs[] = {\"HELLOWORLD\",\"HI\",\"BYE\", \"THE\",\"THENA\"}; // Input keys ( only A to Z in upper case)\n int n = sizeof(inputs)/sizeof(inputs[0]);\n struct Trie *root = createNode();\n for (int i = 0; i < n; i++)\n insert(root, inputs[i]);\n search(root, \"HELLOWORLD\")? cout << \"Key is Found\\n\" :\n cout << \"Key is not Found\\n\";\n search(root, \"HE\")? cout << \"Key is Found\\n\" :\n cout << \"Key is not Found\\n\";\n deletion(root, \"THEN\")? cout << \"Key is deleted\\n\" :\n cout << \"Key is not Deleted\\n\";\n return 0;\n}" }, { "code": null, "e": 4559, "s": 4514, "text": "Key is Found\nKey is not Found\nKey is deleted" } ]
Java 8 - Method References
Method references help to point to methods by their names. A method reference is described using "::" symbol. A method reference can be used to point the following types of methods − Static methods Instance methods Constructors using new operator (TreeSet::new) Create the following Java program using any editor of your choice in, say, C:\> JAVA. import java.util.List; import java.util.ArrayList; public class Java8Tester { public static void main(String args[]) { List names = new ArrayList(); names.add("Mahesh"); names.add("Suresh"); names.add("Ramesh"); names.add("Naresh"); names.add("Kalpesh"); names.forEach(System.out::println); } } Here we have passed System.out::println method as a static method reference. Compile the class using javac compiler as follows − C:\JAVA>javac Java8Tester.java Now run the Java8Tester as follows − C:\JAVA>java Java8Tester It should produce the following output − Mahesh Suresh Ramesh Naresh Kalpesh 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2057, "s": 1874, "text": "Method references help to point to methods by their names. A method reference is described using \"::\" symbol. A method reference can be used to point the following types of methods −" }, { "code": null, "e": 2072, "s": 2057, "text": "Static methods" }, { "code": null, "e": 2089, "s": 2072, "text": "Instance methods" }, { "code": null, "e": 2136, "s": 2089, "text": "Constructors using new operator (TreeSet::new)" }, { "code": null, "e": 2222, "s": 2136, "text": "Create the following Java program using any editor of your choice in, say, C:\\> JAVA." }, { "code": null, "e": 2573, "s": 2222, "text": "import java.util.List;\nimport java.util.ArrayList;\n\npublic class Java8Tester {\n\n public static void main(String args[]) {\n List names = new ArrayList();\n\t\t\n names.add(\"Mahesh\");\n names.add(\"Suresh\");\n names.add(\"Ramesh\");\n names.add(\"Naresh\");\n names.add(\"Kalpesh\");\n\t\t\n names.forEach(System.out::println);\n }\n}" }, { "code": null, "e": 2650, "s": 2573, "text": "Here we have passed System.out::println method as a static method reference." }, { "code": null, "e": 2702, "s": 2650, "text": "Compile the class using javac compiler as follows −" }, { "code": null, "e": 2734, "s": 2702, "text": "C:\\JAVA>javac Java8Tester.java\n" }, { "code": null, "e": 2771, "s": 2734, "text": "Now run the Java8Tester as follows −" }, { "code": null, "e": 2797, "s": 2771, "text": "C:\\JAVA>java Java8Tester\n" }, { "code": null, "e": 2838, "s": 2797, "text": "It should produce the following output −" }, { "code": null, "e": 2875, "s": 2838, "text": "Mahesh\nSuresh\nRamesh\nNaresh\nKalpesh\n" }, { "code": null, "e": 2908, "s": 2875, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 2924, "s": 2908, "text": " Malhar Lathkar" }, { "code": null, "e": 2957, "s": 2924, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 2973, "s": 2957, "text": " Malhar Lathkar" }, { "code": null, "e": 3008, "s": 2973, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3022, "s": 3008, "text": " Anadi Sharma" }, { "code": null, "e": 3056, "s": 3022, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 3070, "s": 3056, "text": " Tushar Kale" }, { "code": null, "e": 3107, "s": 3070, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3122, "s": 3107, "text": " Monica Mittal" }, { "code": null, "e": 3155, "s": 3122, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 3174, "s": 3155, "text": " Arnab Chakraborty" }, { "code": null, "e": 3181, "s": 3174, "text": " Print" }, { "code": null, "e": 3192, "s": 3181, "text": " Add Notes" } ]
Minimum element in a max heap - GeeksforGeeks
10 May, 2021 Given a max heap, find the minimum element present in the heap. Examples: Input : 100 / \ 75 50 / \ / \ 55 10 2 40 Output : 2 Input : 20 / \ 4 18 Output : 4 Brute force approach: We can check all the nodes in the max heap to get the minimum element. Note that this approach works on any binary tree and does not makes use of any property of the max heap. It has a time and space complexity of O(n). Since max heap is a complete binary tree, we generally use arrays to store them, so we can check all the nodes by simply traversing the array. If the heap is stored using pointers, then we can use recursion to check all the nodes. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to find the// minimum element in a// max heapint findMinimumElement(int heap[], int n){ int minimumElement = heap[0]; for (int i = 1; i < n; ++i) minimumElement = min(minimumElement, heap[i]); return minimumElement;} // Driver codeint main(){ // Number of nodes int n = 10; // heap represents the following max heap: // 20 // / \ // 18 10 // / \ / \ // 12 9 9 3 // / \ / // 5 6 8 int heap[] = { 20, 18, 10, 12, 9, 9, 3, 5, 6, 8 }; cout << findMinimumElement(heap, n); return 0;} // Java implementation of above approach public class Improve { // Function to find the // minimum element in a // max heap static int findMinimumElement(int heap[], int n) { int minimumElement = heap[0]; for (int i = 1; i < n; ++i) minimumElement = Math.min(minimumElement, heap[i]); return minimumElement; } // Driver code public static void main(String args[]) { // Number of nodes int n = 10; // heap represents the following max heap: // 20 // / \ // 18 10 // / \ / \ // 12 9 9 3 // / \ / // 5 6 8 int heap[] = { 20, 18, 10, 12, 9, 9, 3, 5, 6, 8 }; System.out.println(findMinimumElement(heap, n)); } // This Code is contributed by ANKITRAI1} # Python 3 implementation of above approach # Function to find the minimum# element in a max heap def findMiniumumElement(heap, n): minimumElement = heap[0] for i in range(1, n): minimumElement = min(minimumElement, heap[i]) return minimumElement # Driver Coden = 10 # Numbers Of Node # heap represents the following max heap:# 20# / \# 18 10# / \ / \# 12 9 9 3# / \ /# 5 6 8# heap = [20, 18, 10, 12, 8, 9, 3, 5, 6, 8] print(findMiniumumElement(heap, n)) # This code is contributed by SANKAR // C# implementation of above approachusing System;class GFG { // Function to find the // minimum element in a // max heap static int findMinimumElement(int[] heap, int n) { int minimumElement = heap[0]; for (int i = 1; i < n; ++i) minimumElement = Math.Min(minimumElement, heap[i]); return minimumElement; } // Driver code public static void Main() { // Number of nodes int n = 10; // heap represents the following max heap: // 20 // / \ // 18 10 // / \ / \ // 12 9 9 3 // / \ / // 5 6 8 int[] heap = { 20, 18, 10, 12, 9, 9, 3, 5, 6, 8 }; Console.Write(findMinimumElement(heap, n)); }} // This code is contributed by ChitraNayal <?php// PHP implementation of above approach // Function to find the// minimum element in a// max heapfunction findMinimumElement(&$heap, $n){ $minimumElement = $heap[0]; for ($i = 1; $i < $n; ++$i) $minimumElement = min($minimumElement, $heap[$i]); return $minimumElement;} // Driver code // Number of nodes$n = 10; // heap represents the following// max heap:// 20// / \// 18 10// / \ / \// 12 9 9 3// / \ /// 5 6 8$heap = array(20, 18, 10, 12, 9, 9, 3, 5, 6, 8 ); echo findMinimumElement($heap, $n); // This code is contributed// by Shivi_Aggarwal?> <script> // Javascript implementation of above approach // Function to find the // minimum element in a // max heap function findMinimumElement(heap, n) { let minimumElement = heap[0]; for (let i = 1; i < n; ++i) minimumElement = Math.min(minimumElement, heap[i]); return minimumElement; } // Number of nodes let n = 10; // heap represents the following max heap: // 20 // / \ // 18 10 // / \ / \ // 12 9 9 3 // / \ / // 5 6 8 let heap = [ 20, 18, 10, 12, 9, 9, 3, 5, 6, 8 ]; document.write(findMinimumElement(heap, n)); </script> 3 Efficient approach: The max heap property requires that the parent node be greater than its child node(s). Due to this, we can conclude that a non-leaf node cannot be the minimum element as its child node has a lower value. So we can narrow down our search space to only leaf nodes. In a max heap having n elements, there is ceil(n/2) leaf nodes. The time and space complexity remains O(n) as a constant factor of 1/2 does not affect the asymptotic complexity. Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to find the// minimum element in a// max heapint findMinimumElement(int heap[], int n){ int minimumElement = heap[n / 2]; for (int i = 1 + n / 2; i < n; ++i) minimumElement = min(minimumElement, heap[i]); return minimumElement;} // Driver codeint main(){ // Number of nodes int n = 10; // heap represents the following max heap: // 20 // / \ // 18 10 // / \ / \ // 12 9 9 3 // / \ / // 5 6 8 int heap[] = { 20, 18, 10, 12, 9, 9, 3, 5, 6, 8 }; cout << findMinimumElement(heap, n); return 0;} // Java implementation of above approachimport java.util.*;import java.lang.*; class GFG { // Function to find the // minimum element in a // max heap static int findMinimumElement(int heap[], int n) { int minimumElement = heap[n / 2]; for (int i = 1 + n / 2; i < n; ++i) minimumElement = Math.min(minimumElement, heap[i]); return minimumElement; } // Driver code public static void main(String args[]) { // Number of nodes int n = 10; // heap represents the following max heap: // 20 // / \ // 18 10 // / \ / \ // 12 9 9 3 // / \ / // 5 6 8 int heap[] = new int[] { 20, 18, 10, 12, 9, 9, 3, 5, 6, 8 }; System.out.println(findMinimumElement(heap, n)); }} // This code is contributed// by Akanksha Rai(Abby_akku) # Python 3 implementation of# above approach # Function to find the minimum# element in a max heap def findMiniumumElement(heap, n): # // -->Floor Division Arithmetic Operator minimumElement = heap[n // 2] for i in range(1 + n // 2, n): minimumElement = min(minimumElement, heap[i]) return minimumElement # Driver Coden = 10 # Numbers Of Node # heap represents the# following max heap:# 20# / \# 18 10# / \ / \# 12 9 9 3# / \ \# 5 6 8# heap = [20, 18, 10, 12, 9, 9, 3, 5, 6, 8] print(findMiniumumElement(heap, n)) # This code is contributed by SANKAR // C# implementation of above approachusing System; class GFG { // Function to find the minimum element // in a max heap static int findMinimumElement(int[] heap, int n) { int minimumElement = heap[n / 2]; for (int i = 1 + n / 2; i < n; ++i) minimumElement = Math.Min(minimumElement, heap[i]); return minimumElement; } // Driver code static public void Main() { // Number of nodes int n = 10; // heap represents the following // max heap: // 20 // / \ // 18 10 // / \ / \ // 12 9 9 3 // / \ / // 5 6 8 int[] heap = new int[] { 20, 18, 10, 12, 9, 9, 3, 5, 6, 8 }; Console.WriteLine(findMinimumElement(heap, n)); }} // This code is contributed// by ajit <?php// PHP implementation of above approach // Function to find the// minimum element in a// max heapfunction findMinimumElement($heap, $n){ $minimumElement = $heap[$n/2]; for ($i = 1 + $n / 2; $i < $n; ++$i) $minimumElement = min($minimumElement, $heap[$i]); return $minimumElement;} // Driver code // Number of nodes $n = 10; // heap represents the following max heap: // 20 // / \ // 18 10 // / \ / \ // 12 9 9 3 // / \ / // 5 6 8 $heap = Array(20, 18, 10, 12, 9, 9, 3, 5, 6, 8 ); echo(findMinimumElement($heap, $n)); // This code is contributed to Rajput-Ji?> <script> // Javascript implementation of above approach // Function to find the minimum element // in a max heap function findMinimumElement(heap, n) { let minimumElement = heap[parseInt(n / 2, 10)]; for (let i = 1 + parseInt(n / 2, 10); i < n; ++i) minimumElement = Math.min(minimumElement, heap[i]); return minimumElement; } // Number of nodes let n = 10; // heap represents the following // max heap: // 20 // / \ // 18 10 // / \ / \ // 12 9 9 3 // / \ / // 5 6 8 let heap = [ 20, 18, 10, 12, 9, 9, 3, 5, 6, 8 ]; document.write(findMinimumElement(heap, n)); </script> 3 Shivi_Aggarwal ankthon ukasp Akanksha_Rai vaibhav29498 jit_t sankarguru63 Rajput-Ji nemanjaboskovic17 suresh07 divyeshrabadiya07 Arrays Heap Technical Scripter Arrays Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Huffman Coding | Greedy Algo-3 K'th Smallest/Largest Element in Unsorted Array | Set 1 k largest(or smallest) elements in an array Building Heap from Array Insertion and Deletion in Heaps
[ { "code": null, "e": 25380, "s": 25352, "text": "\n10 May, 2021" }, { "code": null, "e": 25444, "s": 25380, "text": "Given a max heap, find the minimum element present in the heap." }, { "code": null, "e": 25456, "s": 25444, "text": "Examples: " }, { "code": null, "e": 25629, "s": 25456, "text": "Input : 100\n / \\ \n 75 50 \n / \\ / \\\n 55 10 2 40\nOutput : 2\n\nInput : 20\n / \\ \n 4 18\nOutput : 4" }, { "code": null, "e": 26102, "s": 25629, "text": "Brute force approach: We can check all the nodes in the max heap to get the minimum element. Note that this approach works on any binary tree and does not makes use of any property of the max heap. It has a time and space complexity of O(n). Since max heap is a complete binary tree, we generally use arrays to store them, so we can check all the nodes by simply traversing the array. If the heap is stored using pointers, then we can use recursion to check all the nodes." }, { "code": null, "e": 26155, "s": 26102, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26159, "s": 26155, "text": "C++" }, { "code": null, "e": 26164, "s": 26159, "text": "Java" }, { "code": null, "e": 26172, "s": 26164, "text": "Python3" }, { "code": null, "e": 26175, "s": 26172, "text": "C#" }, { "code": null, "e": 26179, "s": 26175, "text": "PHP" }, { "code": null, "e": 26190, "s": 26179, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to find the// minimum element in a// max heapint findMinimumElement(int heap[], int n){ int minimumElement = heap[0]; for (int i = 1; i < n; ++i) minimumElement = min(minimumElement, heap[i]); return minimumElement;} // Driver codeint main(){ // Number of nodes int n = 10; // heap represents the following max heap: // 20 // / \\ // 18 10 // / \\ / \\ // 12 9 9 3 // / \\ / // 5 6 8 int heap[] = { 20, 18, 10, 12, 9, 9, 3, 5, 6, 8 }; cout << findMinimumElement(heap, n); return 0;}", "e": 26875, "s": 26190, "text": null }, { "code": "// Java implementation of above approach public class Improve { // Function to find the // minimum element in a // max heap static int findMinimumElement(int heap[], int n) { int minimumElement = heap[0]; for (int i = 1; i < n; ++i) minimumElement = Math.min(minimumElement, heap[i]); return minimumElement; } // Driver code public static void main(String args[]) { // Number of nodes int n = 10; // heap represents the following max heap: // 20 // / \\ // 18 10 // / \\ / \\ // 12 9 9 3 // / \\ / // 5 6 8 int heap[] = { 20, 18, 10, 12, 9, 9, 3, 5, 6, 8 }; System.out.println(findMinimumElement(heap, n)); } // This Code is contributed by ANKITRAI1}", "e": 27742, "s": 26875, "text": null }, { "code": "# Python 3 implementation of above approach # Function to find the minimum# element in a max heap def findMiniumumElement(heap, n): minimumElement = heap[0] for i in range(1, n): minimumElement = min(minimumElement, heap[i]) return minimumElement # Driver Coden = 10 # Numbers Of Node # heap represents the following max heap:# 20# / \\# 18 10# / \\ / \\# 12 9 9 3# / \\ /# 5 6 8# heap = [20, 18, 10, 12, 8, 9, 3, 5, 6, 8] print(findMiniumumElement(heap, n)) # This code is contributed by SANKAR", "e": 28303, "s": 27742, "text": null }, { "code": "// C# implementation of above approachusing System;class GFG { // Function to find the // minimum element in a // max heap static int findMinimumElement(int[] heap, int n) { int minimumElement = heap[0]; for (int i = 1; i < n; ++i) minimumElement = Math.Min(minimumElement, heap[i]); return minimumElement; } // Driver code public static void Main() { // Number of nodes int n = 10; // heap represents the following max heap: // 20 // / \\ // 18 10 // / \\ / \\ // 12 9 9 3 // / \\ / // 5 6 8 int[] heap = { 20, 18, 10, 12, 9, 9, 3, 5, 6, 8 }; Console.Write(findMinimumElement(heap, n)); }} // This code is contributed by ChitraNayal", "e": 29161, "s": 28303, "text": null }, { "code": "<?php// PHP implementation of above approach // Function to find the// minimum element in a// max heapfunction findMinimumElement(&$heap, $n){ $minimumElement = $heap[0]; for ($i = 1; $i < $n; ++$i) $minimumElement = min($minimumElement, $heap[$i]); return $minimumElement;} // Driver code // Number of nodes$n = 10; // heap represents the following// max heap:// 20// / \\// 18 10// / \\ / \\// 12 9 9 3// / \\ /// 5 6 8$heap = array(20, 18, 10, 12, 9, 9, 3, 5, 6, 8 ); echo findMinimumElement($heap, $n); // This code is contributed// by Shivi_Aggarwal?>", "e": 29812, "s": 29161, "text": null }, { "code": "<script> // Javascript implementation of above approach // Function to find the // minimum element in a // max heap function findMinimumElement(heap, n) { let minimumElement = heap[0]; for (let i = 1; i < n; ++i) minimumElement = Math.min(minimumElement, heap[i]); return minimumElement; } // Number of nodes let n = 10; // heap represents the following max heap: // 20 // / \\ // 18 10 // / \\ / \\ // 12 9 9 3 // / \\ / // 5 6 8 let heap = [ 20, 18, 10, 12, 9, 9, 3, 5, 6, 8 ]; document.write(findMinimumElement(heap, n)); </script>", "e": 30522, "s": 29812, "text": null }, { "code": null, "e": 30524, "s": 30522, "text": "3" }, { "code": null, "e": 30985, "s": 30524, "text": "Efficient approach: The max heap property requires that the parent node be greater than its child node(s). Due to this, we can conclude that a non-leaf node cannot be the minimum element as its child node has a lower value. So we can narrow down our search space to only leaf nodes. In a max heap having n elements, there is ceil(n/2) leaf nodes. The time and space complexity remains O(n) as a constant factor of 1/2 does not affect the asymptotic complexity." }, { "code": null, "e": 31034, "s": 30985, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 31038, "s": 31034, "text": "C++" }, { "code": null, "e": 31043, "s": 31038, "text": "Java" }, { "code": null, "e": 31051, "s": 31043, "text": "Python3" }, { "code": null, "e": 31054, "s": 31051, "text": "C#" }, { "code": null, "e": 31058, "s": 31054, "text": "PHP" }, { "code": null, "e": 31069, "s": 31058, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to find the// minimum element in a// max heapint findMinimumElement(int heap[], int n){ int minimumElement = heap[n / 2]; for (int i = 1 + n / 2; i < n; ++i) minimumElement = min(minimumElement, heap[i]); return minimumElement;} // Driver codeint main(){ // Number of nodes int n = 10; // heap represents the following max heap: // 20 // / \\ // 18 10 // / \\ / \\ // 12 9 9 3 // / \\ / // 5 6 8 int heap[] = { 20, 18, 10, 12, 9, 9, 3, 5, 6, 8 }; cout << findMinimumElement(heap, n); return 0;}", "e": 31764, "s": 31069, "text": null }, { "code": "// Java implementation of above approachimport java.util.*;import java.lang.*; class GFG { // Function to find the // minimum element in a // max heap static int findMinimumElement(int heap[], int n) { int minimumElement = heap[n / 2]; for (int i = 1 + n / 2; i < n; ++i) minimumElement = Math.min(minimumElement, heap[i]); return minimumElement; } // Driver code public static void main(String args[]) { // Number of nodes int n = 10; // heap represents the following max heap: // 20 // / \\ // 18 10 // / \\ / \\ // 12 9 9 3 // / \\ / // 5 6 8 int heap[] = new int[] { 20, 18, 10, 12, 9, 9, 3, 5, 6, 8 }; System.out.println(findMinimumElement(heap, n)); }} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 32698, "s": 31764, "text": null }, { "code": "# Python 3 implementation of# above approach # Function to find the minimum# element in a max heap def findMiniumumElement(heap, n): # // -->Floor Division Arithmetic Operator minimumElement = heap[n // 2] for i in range(1 + n // 2, n): minimumElement = min(minimumElement, heap[i]) return minimumElement # Driver Coden = 10 # Numbers Of Node # heap represents the# following max heap:# 20# / \\# 18 10# / \\ / \\# 12 9 9 3# / \\ \\# 5 6 8# heap = [20, 18, 10, 12, 9, 9, 3, 5, 6, 8] print(findMiniumumElement(heap, n)) # This code is contributed by SANKAR", "e": 33309, "s": 32698, "text": null }, { "code": "// C# implementation of above approachusing System; class GFG { // Function to find the minimum element // in a max heap static int findMinimumElement(int[] heap, int n) { int minimumElement = heap[n / 2]; for (int i = 1 + n / 2; i < n; ++i) minimumElement = Math.Min(minimumElement, heap[i]); return minimumElement; } // Driver code static public void Main() { // Number of nodes int n = 10; // heap represents the following // max heap: // 20 // / \\ // 18 10 // / \\ / \\ // 12 9 9 3 // / \\ / // 5 6 8 int[] heap = new int[] { 20, 18, 10, 12, 9, 9, 3, 5, 6, 8 }; Console.WriteLine(findMinimumElement(heap, n)); }} // This code is contributed// by ajit", "e": 34161, "s": 33309, "text": null }, { "code": "<?php// PHP implementation of above approach // Function to find the// minimum element in a// max heapfunction findMinimumElement($heap, $n){ $minimumElement = $heap[$n/2]; for ($i = 1 + $n / 2; $i < $n; ++$i) $minimumElement = min($minimumElement, $heap[$i]); return $minimumElement;} // Driver code // Number of nodes $n = 10; // heap represents the following max heap: // 20 // / \\ // 18 10 // / \\ / \\ // 12 9 9 3 // / \\ / // 5 6 8 $heap = Array(20, 18, 10, 12, 9, 9, 3, 5, 6, 8 ); echo(findMinimumElement($heap, $n)); // This code is contributed to Rajput-Ji?>", "e": 34806, "s": 34161, "text": null }, { "code": "<script> // Javascript implementation of above approach // Function to find the minimum element // in a max heap function findMinimumElement(heap, n) { let minimumElement = heap[parseInt(n / 2, 10)]; for (let i = 1 + parseInt(n / 2, 10); i < n; ++i) minimumElement = Math.min(minimumElement, heap[i]); return minimumElement; } // Number of nodes let n = 10; // heap represents the following // max heap: // 20 // / \\ // 18 10 // / \\ / \\ // 12 9 9 3 // / \\ / // 5 6 8 let heap = [ 20, 18, 10, 12, 9, 9, 3, 5, 6, 8 ]; document.write(findMinimumElement(heap, n)); </script>", "e": 35505, "s": 34806, "text": null }, { "code": null, "e": 35507, "s": 35505, "text": "3" }, { "code": null, "e": 35524, "s": 35509, "text": "Shivi_Aggarwal" }, { "code": null, "e": 35532, "s": 35524, "text": "ankthon" }, { "code": null, "e": 35538, "s": 35532, "text": "ukasp" }, { "code": null, "e": 35551, "s": 35538, "text": "Akanksha_Rai" }, { "code": null, "e": 35564, "s": 35551, "text": "vaibhav29498" }, { "code": null, "e": 35570, "s": 35564, "text": "jit_t" }, { "code": null, "e": 35583, "s": 35570, "text": "sankarguru63" }, { "code": null, "e": 35593, "s": 35583, "text": "Rajput-Ji" }, { "code": null, "e": 35611, "s": 35593, "text": "nemanjaboskovic17" }, { "code": null, "e": 35620, "s": 35611, "text": "suresh07" }, { "code": null, "e": 35638, "s": 35620, "text": "divyeshrabadiya07" }, { "code": null, "e": 35645, "s": 35638, "text": "Arrays" }, { "code": null, "e": 35650, "s": 35645, "text": "Heap" }, { "code": null, "e": 35669, "s": 35650, "text": "Technical Scripter" }, { "code": null, "e": 35676, "s": 35669, "text": "Arrays" }, { "code": null, "e": 35681, "s": 35676, "text": "Heap" }, { "code": null, "e": 35779, "s": 35681, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35847, "s": 35779, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 35891, "s": 35847, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 35939, "s": 35891, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 35962, "s": 35939, "text": "Introduction to Arrays" }, { "code": null, "e": 35994, "s": 35962, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 36025, "s": 35994, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 36081, "s": 36025, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 36125, "s": 36081, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 36150, "s": 36125, "text": "Building Heap from Array" } ]
What is the difference between Read(), ReadKey() and ReadLine() methods in C#?
The Read() reads the next characters from the standard input stream. If a key is pressed on the console, then it would close. int az = Console.Read() Console.WriteLine(z); It reads only a single charactare from the standard input stream. Reads the next line of characters from the standard input stream. Live Demo using System; class Program { static void Main() { int x = 10; Console.WriteLine(x); Console.Write("\nPress any key to continue... "); Console.ReadLine(); } } 10 Press any key to continue...
[ { "code": null, "e": 1188, "s": 1062, "text": "The Read() reads the next characters from the standard input stream. If a key is pressed on the console, then it would close." }, { "code": null, "e": 1234, "s": 1188, "text": "int az = Console.Read()\nConsole.WriteLine(z);" }, { "code": null, "e": 1300, "s": 1234, "text": "It reads only a single charactare from the standard input stream." }, { "code": null, "e": 1366, "s": 1300, "text": "Reads the next line of characters from the standard input stream." }, { "code": null, "e": 1377, "s": 1366, "text": " Live Demo" }, { "code": null, "e": 1567, "s": 1377, "text": "using System;\nclass Program {\n static void Main() {\n\n int x = 10;\n Console.WriteLine(x);\n Console.Write(\"\\nPress any key to continue... \");\n Console.ReadLine();\n }\n}" }, { "code": null, "e": 1600, "s": 1567, "text": "10\n\nPress any key to continue..." } ]
Express.js req.path Property - GeeksforGeeks
08 Jul, 2020 The req.path property contains the path of the request URL. This property is widely used to get the path part of the incoming request URL. Syntax: req.path Parameter: No parameters. Return Value: String Installation of express module: You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js You can visit the link to Install express module. You can install this package by using this command.npm install express npm install express After installing the express module, you can check your express version in command prompt using the command.npm version express npm version express After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js node index.js Example 1: Filename: index.js var express = require('express');var app = express(); var PORT = 3000; app.get('/', function (req, res) { console.log(req.path); res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Steps to run the program: The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000 Now open your browser and go to http://localhost:3000/, now you can see the following output on your console:Server listening on PORT 3000 / The project structure will look like this: Make sure you have installed express module using the following command:npm install express npm install express Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000 node index.js Output: Server listening on PORT 3000 Now open your browser and go to http://localhost:3000/, now you can see the following output on your console:Server listening on PORT 3000 / Server listening on PORT 3000 / Example 2: Filename: index.js var express = require('express');var app = express(); var PORT = 3000; app.get('/user', function (req, res) { console.log(req.path); res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Run index.js file using below command: node index.js Output: Now open your browser and make GET request to http://localhost:3000/user, now you can see the following output on your console: Server listening on PORT 3000 /user Reference: https://expressjs.com/en/4x/api.html#req.path Express.js Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between dependencies, devDependencies and peerDependencies Node.js Export Module Mongoose Populate() Method How to connect Node.js with React.js ? Mongoose find() Function Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26377, "s": 26349, "text": "\n08 Jul, 2020" }, { "code": null, "e": 26516, "s": 26377, "text": "The req.path property contains the path of the request URL. This property is widely used to get the path part of the incoming request URL." }, { "code": null, "e": 26524, "s": 26516, "text": "Syntax:" }, { "code": null, "e": 26533, "s": 26524, "text": "req.path" }, { "code": null, "e": 26559, "s": 26533, "text": "Parameter: No parameters." }, { "code": null, "e": 26580, "s": 26559, "text": "Return Value: String" }, { "code": null, "e": 26612, "s": 26580, "text": "Installation of express module:" }, { "code": null, "e": 27007, "s": 26612, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 27128, "s": 27007, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install express" }, { "code": null, "e": 27148, "s": 27128, "text": "npm install express" }, { "code": null, "e": 27276, "s": 27148, "text": "After installing the express module, you can check your express version in command prompt using the command.npm version express" }, { "code": null, "e": 27296, "s": 27276, "text": "npm version express" }, { "code": null, "e": 27444, "s": 27296, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 27458, "s": 27444, "text": "node index.js" }, { "code": null, "e": 27488, "s": 27458, "text": "Example 1: Filename: index.js" }, { "code": "var express = require('express');var app = express(); var PORT = 3000; app.get('/', function (req, res) { console.log(req.path); res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 27751, "s": 27488, "text": null }, { "code": null, "e": 27777, "s": 27751, "text": "Steps to run the program:" }, { "code": null, "e": 28140, "s": 27777, "text": "The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000\nNow open your browser and go to http://localhost:3000/, now you can see the following output on your console:Server listening on PORT 3000\n/\n" }, { "code": null, "e": 28183, "s": 28140, "text": "The project structure will look like this:" }, { "code": null, "e": 28275, "s": 28183, "text": "Make sure you have installed express module using the following command:npm install express" }, { "code": null, "e": 28295, "s": 28275, "text": "npm install express" }, { "code": null, "e": 28384, "s": 28295, "text": "Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000\n" }, { "code": null, "e": 28398, "s": 28384, "text": "node index.js" }, { "code": null, "e": 28406, "s": 28398, "text": "Output:" }, { "code": null, "e": 28437, "s": 28406, "text": "Server listening on PORT 3000\n" }, { "code": null, "e": 28579, "s": 28437, "text": "Now open your browser and go to http://localhost:3000/, now you can see the following output on your console:Server listening on PORT 3000\n/\n" }, { "code": null, "e": 28612, "s": 28579, "text": "Server listening on PORT 3000\n/\n" }, { "code": null, "e": 28642, "s": 28612, "text": "Example 2: Filename: index.js" }, { "code": "var express = require('express');var app = express(); var PORT = 3000; app.get('/user', function (req, res) { console.log(req.path); res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 28909, "s": 28642, "text": null }, { "code": null, "e": 28948, "s": 28909, "text": "Run index.js file using below command:" }, { "code": null, "e": 28962, "s": 28948, "text": "node index.js" }, { "code": null, "e": 29098, "s": 28962, "text": "Output: Now open your browser and make GET request to http://localhost:3000/user, now you can see the following output on your console:" }, { "code": null, "e": 29135, "s": 29098, "text": "Server listening on PORT 3000\n/user\n" }, { "code": null, "e": 29192, "s": 29135, "text": "Reference: https://expressjs.com/en/4x/api.html#req.path" }, { "code": null, "e": 29203, "s": 29192, "text": "Express.js" }, { "code": null, "e": 29211, "s": 29203, "text": "Node.js" }, { "code": null, "e": 29228, "s": 29211, "text": "Web Technologies" }, { "code": null, "e": 29326, "s": 29228, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29396, "s": 29326, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 29418, "s": 29396, "text": "Node.js Export Module" }, { "code": null, "e": 29445, "s": 29418, "text": "Mongoose Populate() Method" }, { "code": null, "e": 29484, "s": 29445, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 29509, "s": 29484, "text": "Mongoose find() Function" }, { "code": null, "e": 29549, "s": 29509, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29594, "s": 29549, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29637, "s": 29594, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29687, "s": 29637, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Vector capacity() Method in Java - GeeksforGeeks
17 Aug, 2018 The Java.util.Vector.capacity() method in Java is used to get the capacity of the Vector or the length of the array present in the Vector. Syntax: Vector.capacity() Parameters: The method does not take any parameter. Return Value: The method returns the capacity or the internal data array’s length present in the Vector, which is an integer value. Below programs illustrate the Java.util.Vector.capacity() method: Program 1: Vector with string elements. // Java code to illustrate capacity()import java.util.*; public class VectorDemo { public static void main(String args[]) { // Creating an empty Vector Vector<String> vec_tor = new Vector<String>(); // Use add() method to add elements into the Vector vec_tor.add("Welcome"); vec_tor.add("To"); vec_tor.add("Geeks"); vec_tor.add("4"); vec_tor.add("Geeks"); // Displaying the Vector System.out.println("Vector: " + vec_tor); // Displaying the capacity of Vector System.out.println("The capacity is: " + vec_tor.capacity()); }} Vector: [Welcome, To, Geeks, 4, Geeks] The capacity is: 10 Program 2: Vector with Integer elements. // Java code to illustrate capacity()import java.util.*; public class VectorDemo { public static void main(String args[]) { // Creating an empty Vector Vector<Integer> vec_tor = new Vector<Integer>(); // Use add() method to add elements into the Vector vec_tor.add(10); vec_tor.add(15); vec_tor.add(30); vec_tor.add(20); vec_tor.add(5); // Displaying the Vector System.out.println("Vector: " + vec_tor); // Displaying the capacity of Vector System.out.println("The capacity is: " + vec_tor.capacity()); }} Vector: [10, 15, 30, 20, 5] The capacity is: 10 Java - util package Java-Collections Java-Functions Java-Vector Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Arrays.sort() in Java with examples Reverse a string in Java Stream In Java Interfaces in Java How to iterate any Map in Java
[ { "code": null, "e": 25065, "s": 25037, "text": "\n17 Aug, 2018" }, { "code": null, "e": 25204, "s": 25065, "text": "The Java.util.Vector.capacity() method in Java is used to get the capacity of the Vector or the length of the array present in the Vector." }, { "code": null, "e": 25212, "s": 25204, "text": "Syntax:" }, { "code": null, "e": 25230, "s": 25212, "text": "Vector.capacity()" }, { "code": null, "e": 25282, "s": 25230, "text": "Parameters: The method does not take any parameter." }, { "code": null, "e": 25414, "s": 25282, "text": "Return Value: The method returns the capacity or the internal data array’s length present in the Vector, which is an integer value." }, { "code": null, "e": 25480, "s": 25414, "text": "Below programs illustrate the Java.util.Vector.capacity() method:" }, { "code": null, "e": 25520, "s": 25480, "text": "Program 1: Vector with string elements." }, { "code": "// Java code to illustrate capacity()import java.util.*; public class VectorDemo { public static void main(String args[]) { // Creating an empty Vector Vector<String> vec_tor = new Vector<String>(); // Use add() method to add elements into the Vector vec_tor.add(\"Welcome\"); vec_tor.add(\"To\"); vec_tor.add(\"Geeks\"); vec_tor.add(\"4\"); vec_tor.add(\"Geeks\"); // Displaying the Vector System.out.println(\"Vector: \" + vec_tor); // Displaying the capacity of Vector System.out.println(\"The capacity is: \" + vec_tor.capacity()); }}", "e": 26145, "s": 25520, "text": null }, { "code": null, "e": 26205, "s": 26145, "text": "Vector: [Welcome, To, Geeks, 4, Geeks]\nThe capacity is: 10\n" }, { "code": null, "e": 26246, "s": 26205, "text": "Program 2: Vector with Integer elements." }, { "code": "// Java code to illustrate capacity()import java.util.*; public class VectorDemo { public static void main(String args[]) { // Creating an empty Vector Vector<Integer> vec_tor = new Vector<Integer>(); // Use add() method to add elements into the Vector vec_tor.add(10); vec_tor.add(15); vec_tor.add(30); vec_tor.add(20); vec_tor.add(5); // Displaying the Vector System.out.println(\"Vector: \" + vec_tor); // Displaying the capacity of Vector System.out.println(\"The capacity is: \" + vec_tor.capacity()); }}", "e": 26852, "s": 26246, "text": null }, { "code": null, "e": 26901, "s": 26852, "text": "Vector: [10, 15, 30, 20, 5]\nThe capacity is: 10\n" }, { "code": null, "e": 26921, "s": 26901, "text": "Java - util package" }, { "code": null, "e": 26938, "s": 26921, "text": "Java-Collections" }, { "code": null, "e": 26953, "s": 26938, "text": "Java-Functions" }, { "code": null, "e": 26965, "s": 26953, "text": "Java-Vector" }, { "code": null, "e": 26970, "s": 26965, "text": "Java" }, { "code": null, "e": 26975, "s": 26970, "text": "Java" }, { "code": null, "e": 26992, "s": 26975, "text": "Java-Collections" }, { "code": null, "e": 27090, "s": 26992, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27105, "s": 27090, "text": "Arrays in Java" }, { "code": null, "e": 27149, "s": 27105, "text": "Split() String method in Java with examples" }, { "code": null, "e": 27171, "s": 27149, "text": "For-each loop in Java" }, { "code": null, "e": 27222, "s": 27171, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27252, "s": 27222, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27288, "s": 27252, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 27313, "s": 27288, "text": "Reverse a string in Java" }, { "code": null, "e": 27328, "s": 27313, "text": "Stream In Java" }, { "code": null, "e": 27347, "s": 27328, "text": "Interfaces in Java" } ]
Parallel Array - GeeksforGeeks
22 Jun, 2021 Parallel Array: Also known as structure an array (SoA), multiple arrays of the same size such that i-th element of each array is closely related and all i-th elements together represent an object or entity. An example parallel array is two arrays that represent x and y co-ordinates of n points. Below is another example where we store the first name, last name and heights of 5 people in three different arrays. first_name = ['Bones', 'Welma', 'Frank', 'Han', 'Jack'] last_name = ['Smith', 'Seger', 'Mathers', 'Solo', 'Jackles'] height = [169, 158, 201, 183, 172] This way we could easily store the information and for accessing, the first index of each array corresponds to the data belonging to the same person.Application: Two of the most essential applications performs on an array or a record are searching and sorting. Searching: Each index in a parallel array corresponds to the data belonging to the same entity in a record. Thus, for searching an entity based on a specific value of an attribute, e.g. we need to find the name of a person having height >200 cms in the above example. Thus, we search for the index in the height array having value greater than 200. Now, once we have obtained the index, we print the values of the index in the first_name and last_name arrays. This way searching becomes an easy task in parallel array. Sorting: Now, using the same fact that each index corresponds to data items in different arrays corresponding to the same entity. Thus, we sort all arrays based on the same criteria. For example, in the above-displayed example, we need to sort the people in increasing order of their respective heights. Thus, when we swap the two heights, we even swap the corresponding values in other arrays using the same index. Searching:Following steps are performed to search an entity based on a specific attribute in structure of array or parallel array. Search for the value of the required attribute in the respective array (e.g. search for values greater than 200 in the above example) using either of the linear search/binary search approaches. Store the index where the following values are obtained in the array Print the values at the evaluated indices in other arrays SortingThe arrays can be sorted in any way, numerical, alphabetical or any other way but the elements are placed at equally spaced addresses. Any of the sorting techniques can be used to sort the record based on a specified criteria. Following steps are performed to sort a record. Find the index in the array (the array according to which sorting shall be done is based on the specified criteria) where the sequence voids (i.e. we need to compute those two indices where the sorting sequence fails, which is to be corrected by swapping the values at those indices). Now swap the values of those two calculated indices in all the arrays. Thus, following the above steps, once the chosen array (the array to be chosen on a specified criterion) is sorted, all the arrays shall be sorted with respect to the chosen array. Implementation: 1) The code below stores the first name, second name, and height of 10 students. 2) Sorts them in increasing order of the height using quicksort algorithm. 3) Searches the name of the 2nd tallest student, the 3rd shortest student and the student having a height equal to 158 cms in the record. C++ Java C# PHP Javascript // C++ implementation of parallel arrays// and operations on them#include <iostream>using namespace std; /* This function takes the last element as pivot places the pivot element at its correct position in a sorted array, and places all smaller (smaller than pivot) to left of the pivot and all greater elements to right of pivot */int partition(string first_name[], string last_name[], int height[], int low, int high){ int pivot = height[high]; // pivot int i = (low - 1); // Index of smaller element for (int j = low; j <= high - 1; j++) { // If current element is smaller than // or equal to pivot. This means are // sorting sequence condition fails if // the condition becomes true. Thus the // two indices which shall be obtained // here will be i and j and therefore // we will be swapping values of i and j // in all the arrays. if (height[j] <= pivot) { // increment index of smaller element i++; // Swapping values of i and j in // all the arrays string temp = first_name[i]; first_name[i] = first_name[j]; first_name[j] = temp; temp = last_name[i]; last_name[i] = last_name[j]; last_name[j] = temp; int temp1 = height[i]; height[i] = height[j]; height[j] = temp1; } } string temp = first_name[i + 1]; first_name[i + 1] = first_name[high]; first_name[high] = temp; temp = last_name[i + 1]; last_name[i + 1] = last_name[high]; last_name[high] = temp; int temp1 = height[i + 1]; height[i + 1] = height[high]; height[high] = temp1; return (i + 1);} // Function which implements quick sortvoid quickSort(string first_name[], string last_name[], int height[], int low, int high){ if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(first_name, last_name, height, low, high); // Separately sort elements before // partition and after partition quickSort(first_name, last_name, height, low, pi - 1); quickSort(first_name, last_name, height, pi + 1, high); }} // Function which binary searches the height// array for value 158 and if found, prints// the corresponding value in other arrays// at that index.void binarySearch(string first_name[], string last_name[], int height[], int value, int n){ int low = 0, high = n - 1; int index; while (low <= high) { index = (high + low) / 2; if (height[index] == 158) { // This index of height array // corresponds to the name // of the person in first name // and last name array. cout << "Person having height 158" " cms is " << first_name[index] << " " << last_name[index] << endl; return; } else if (height[index] > 158) high = index - 1; else low = index + 1; } cout << "Sorry, no such person with" " height 158 cms"; cout << "is found in the record";} // Printing same index of each array. This// will give meaningful data as in parallel// array indices point to values in different// arrays belonging to the same entityvoid printParallelArray(string first_name[], string last_name[], int height[], int n){ cout << "Name of people in increasing"; cout << "order of their height: " << endl; for (int i = 0; i < n; i++) { cout << first_name[i] << " " << last_name[i] << " has height " << height[i] << " cms\n"; } cout << endl;} // Driver Functionint main(){ // These arrays together form a set // of arrays known as parallel array int n = 10; string first_name[] = { "Bones", "Welma", "Frank", "Han", "Jack", "Jinny", "Harry", "Emma", "Tony", "Sherlock" }; string last_name[] = { "Smith", "Seger", "Mathers", "Solo", "Jackles", "Weasly", "Potter", "Watson", "Stark", "Holmes" }; int height[] = { 169, 158, 201, 183, 172, 152, 160, 163, 173, 185 }; // Sorting the above arrays using quickSort // technique based on increasing order of // their heights. quickSort(first_name, last_name, height, 0, n - 1); printParallelArray(first_name, last_name, height, n); // Second tallest person in the sorted // list will be the second person from the // right end. cout << "Name of the second tallest person" " is " << first_name[n - 2] << " " << last_name[n - 2] << endl; // Third shortest person in the sorted // list will be the third person from the // left end. cout << "Name of the third shortest person is " << first_name[2] << " " << last_name[2] << endl; // We binary search the height array to // search for a person having height 158 // cms. binarySearch(first_name, last_name, height, 158, n); return 0;} // Java implementation of parallel arrays// and operations on themimport java.util.*;import java.lang.*; class parallel_array_java { /* This function takes the last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(String first_name[], String last_name[], int height[], int low, int high) { int pivot = height[high]; // pivot int i = (low - 1); // Index of smaller element for (int j = low; j <= high - 1; j++) { // If current element is smaller than // or equal to pivot. This means are // sorting sequence condition fails if // the condition becomes true. Thus the // two indices which shall be obtained // here will be i and jand therefore // we will be swapping values of i and j // in all the arrays. if (height[j] <= pivot) { i++; // increment index of smaller element // Swapping values of i and j in all the arrays String temp = first_name[i]; first_name[i] = first_name[j]; first_name[j] = temp; temp = last_name[i]; last_name[i] = last_name[j]; last_name[j] = temp; int temp1 = height[i]; height[i] = height[j]; height[j] = temp1; } } String temp = first_name[i + 1]; first_name[i + 1] = first_name[high]; first_name[high] = temp; temp = last_name[i + 1]; last_name[i + 1] = last_name[high]; last_name[high] = temp; int temp1 = height[i + 1]; height[i + 1] = height[high]; height[high] = temp1; return (i + 1); } // Function which implements quick sort static void quickSort(String first_name[], String last_name[], int height[], int low, int high) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(first_name, last_name, height, low, high); // Separately sort elements before // partition and after partition quickSort(first_name, last_name, height, low, pi - 1); quickSort(first_name, last_name, height, pi + 1, high); } } // Function which binary searches the height array // for value 158 and if found, prints the // corresponding value in other arrays at that index. static void binarySearch(String first_name[], String last_name[], int height[], int value, int n) { int low = 0, high = n - 1; int index; while (low <= high) { index = (high + low) / 2; if (height[index] == 158) { // This index of height array corresponds // to the name of the person in first // name and last name array. System.out.println("Person having height" + " 158 cms is " + first_name[index] + " " + last_name[index]); return; } else if (height[index] > 158) high = index - 1; else low = index + 1; } System.out.print("Sorry, no such person" + " with height"); System.out.println("158 cms is found in" + " the record"); } // Printing same index of each array. This // will give meaningful data as in parallel // array indices point to the values in // different arrays belonging to the same // entity static void printParallelArray(String first_name[], String last_name[], int height[], int n) { System.out.print("Name of people in increasing" + " order of"); System.out.println("their height: "); for (int i = 0; i < n; i++) { System.out.println(first_name[i] + " " + last_name[i] + " has height " + height[i] + " cms"); } System.out.println(); } public static void main(String args[]) { // These arrays together form a set of arrays // known as parallel array int n = 10; String[] first_name = { "Bones", "Welma", "Frank", "Han", "Jack", "Jinny", "Harry", "Emma", "Tony", "Sherlock" }; String[] last_name = { "Smith", "Seger", "Mathers", "Solo", "Jackles", "Weasly", "Potter", "Watson", "Stark", "Holmes" }; int[] height = { 169, 158, 201, 183, 172, 152, 160, 163, 173, 185 }; // Sorting the above arrays using quickSort // technique based on increasing order of // their heights. quickSort(first_name, last_name, height, 0, n - 1); printParallelArray(first_name, last_name, height, n); // Second tallest person in the sorted list // will be the second person from the right end. System.out.println("Name of the second tallest" + "person is " + first_name[n - 2] + " " + last_name[n - 2]); // Third shortest person in the sorted list // will be the third person from the left end. System.out.println("Name of the third shortest" + " person is " + first_name[2] + " " + last_name[2]); // We binary search the height array to // search for a person having height 158 cms. binarySearch(first_name, last_name, height, 158, n); }} // C# implementation of parallel arrays// and operations on themusing System; class GFG { /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(String[] first_name, String[] last_name, int[] height, int low, int high) { // pivot int pivot = height[high]; // Index of smaller element int i = (low - 1); for (int j = low; j <= high - 1; j++) { // If current element is smaller // than or equal to pivot. This // means are sorting sequence // condition fails if the condition // becomes true. Thus the two // indices which shall be obtained // here will be i and jand therefore // we will be swapping values of i // and j in all the arrays. if (height[j] <= pivot) { // increment index of smaller // element i++; // Swapping values of i and j // in all the arrays String temp = first_name[i]; first_name[i] = first_name[j]; first_name[j] = temp; temp = last_name[i]; last_name[i] = last_name[j]; last_name[j] = temp; int temp1 = height[i]; height[i] = height[j]; height[j] = temp1; } } String tempp = first_name[i + 1]; first_name[i + 1] = first_name[high]; first_name[high] = tempp; tempp = last_name[i + 1]; last_name[i + 1] = last_name[high]; last_name[high] = tempp; int temp2 = height[i + 1]; height[i + 1] = height[high]; height[high] = temp2; return (i + 1); } // Function which implements quick sort static void quickSort(String[] first_name, String[] last_name, int[] height, int low, int high) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(first_name, last_name, height, low, high); // Separately sort elements before // partition and after partition quickSort(first_name, last_name, height, low, pi - 1); quickSort(first_name, last_name, height, pi + 1, high); } } // Function which binary searches the // height array for value 158 and if // found, prints the corresponding value // in other arrays at that index. static void binarySearch(String[] first_name, String[] last_name, int[] height, int value, int n) { int low = 0, high = n - 1; int index; while (low <= high) { index = (high + low) / 2; if (height[index] == 158) { // This index of height array // corresponds to the name of // the person in first name and // last name array. Console.Write("Person having height" + " 158 cms is " + first_name[index] + " " + last_name[index]); return; } else if (height[index] > 158) high = index - 1; else low = index + 1; } Console.Write("Sorry, no such person" + " with height 158 cms is " + "found in the record"); } // Printing same index of each array. This // will give meaningful data as in parallel // array indices point to the values in // different arrays belonging to the same // entity static void printParallelArray(String[] first_name, String[] last_name, int[] height, int n) { Console.WriteLine("Name of people in increasing" + " order of their height: "); for (int i = 0; i < n; i++) { Console.WriteLine(first_name[i] + " " + last_name[i] + " has height " + height[i] + " cms"); } Console.WriteLine(); } // Driver function public static void Main() { // These arrays together form a set of // arrays known as parallel array int n = 10; String[] first_name = { "Bones", "Welma", "Frank", "Han", "Jack", "Jinny", "Harry", "Emma", "Tony", "Sherlock" }; String[] last_name = { "Smith", "Seger", "Mathers", "Solo", "Jackles", "Weasly", "Potter", "Watson", "Stark", "Holmes" }; int[] height = { 169, 158, 201, 183, 172, 152, 160, 163, 173, 185 }; // Sorting the above arrays using quickSort // technique based on increasing order of // their heights. quickSort(first_name, last_name, height, 0, n - 1); printParallelArray(first_name, last_name, height, n); // Second tallest person in the sorted list // will be the second person from the right end. Console.WriteLine("Name of the second tallest" + "person is " + first_name[n - 2] + " " + last_name[n - 2]); // Third shortest person in the sorted list // will be the third person from the left end. Console.WriteLine("Name of the third shortest" + " person is " + first_name[2] + " " + last_name[2]); // We binary search the height array to // search for a person having height 158 cms. binarySearch(first_name, last_name, height, 158, n); }} // This codecontribute by parashar. <?php// PHP implementation of parallel// arrays and operations on them /* This function takes last elementas pivot, places the pivot elementat its correct position in sortedarray, and places all smaller(smaller than pivot) to left of pivotand all greater elements to rightof pivot */function partition(&$first_name, &$last_name, &$height, $low, $high){ $pivot = $height[$high]; // pivot $i = ($low - 1); // Index of smaller element for ($j = $low; $j <= $high - 1; $j++) { // If current element is smaller // than or equal to pivot. This // means are sorting sequence // condition fails if the condition // becomes true. Thus the two indices // which shall be obtained here will // be i and j and therefore we will // be swapping values of i and j // in all the arrays. if ($height[$j] <= $pivot) { // increment index of // smaller element $i++; // Swapping values // of i and j in // all the arrays $temp = $first_name[$i]; $first_name[$i] = $first_name[$j]; $first_name[$j] = $temp; $temp = $last_name[$i]; $last_name[$i] = $last_name[$j]; $last_name[$j] = $temp; $temp1 = $height[$i]; $height[$i] = $height[$j]; $height[$j] = $temp1; } } $temp = $first_name[$i + 1]; $first_name[$i + 1] = $first_name[$high]; $first_name[$high] = $temp; $temp = $last_name[$i + 1]; $last_name[$i + 1] = $last_name[$high]; $last_name[$high] = $temp; $temp1 = $height[$i + 1]; $height[$i + 1] = $height[$high]; $height[$high] = $temp1; return ($i + 1);} // Function which// implements quick sortfunction quickSort(&$first_name, &$last_name, &$height, $low, $high){ if ($low < $high) { /* pi is partitioning index, arr[p] is now at right place */ $pi = partition($first_name, $last_name, $height, $low, $high); // Separately sort elements // before partition and // after partition quickSort($first_name, $last_name, $height, $low, $pi - 1); quickSort($first_name, $last_name, $height, $pi + 1, $high); }} // Function which binary searches// the height array for value 158// and if found, prints the// corresponding value in other// arrays at that index.function binarySearch(&$first_name, &$last_name, &$height, $value, $n){ $low = 0; $high = $n - 1; $index = 0; while ($low <= $high) { $index = ($high + $low) / 2; if ($height[$index] == 158) { // This index of height array // corresponds to the name // of the person in first name // and last name array. echo ("Person having height 158". " cms is " . $first_name[$index] . " " . $last_name[$index] . "\n"); return; } else if ($height[$index] > 158) $high = $index - 1; else $low = $index + 1; } echo ("Sorry, no such person with" . " height 158 cms"); echo ("is found in the record");} // Printing same index of each// array. This will give meaningful// data as in parallel array indices// po$to values in different arrays// belonging to the same entityfunction printParallelArray(&$first_name, &$last_name, &$height, &$n){ echo ("Name of people in increasing"); echo (" order of their height: " . "\n"); for ($i = 0; $i < $n; $i++) { echo ($first_name[$i] . " " . $last_name[$i] . " has height " . $height[$i] . " cms\n"); } echo ("\n");} // Driver Code // These arrays together// form a set of arrays// known as parallel array$n = 10;$first_name = array("Bones", "Welma", "Frank", "Han", "Jack", "Jinny", "Harry", "Emma", "Tony", "Sherlock");$last_name = array("Smith", "Seger", "Mathers", "Solo", "Jackles", "Weasly", "Potter", "Watson", "Stark", "Holmes");$height = array(169, 158, 201, 183, 172, 152, 160, 163, 173, 185); // Sorting the above arrays// using quickSort technique// based on increasing order// of their heights.quickSort($first_name, $last_name, $height, 0, $n - 1);printParallelArray($first_name, $last_name, $height, $n); // Second tallest person in// the sorted list will be// second person from the// right end.echo ("Name of the second ". "tallest person is " . $first_name[$n - 2] . " " . $last_name[$n - 2] . "\n"); // Third shortest person in// the sorted list will be// third person from the// left end.echo ("Name of the third shortest person is " . $first_name[2] . " " . $last_name[2] . "\n"); // We binary search the height// array to search for a person// having height 158 cms.binarySearch($first_name, $last_name, $height, 158, $n); // This code is contributed by// Manish Shaw(manishshaw1)?> <script>// Javascript implementation of parallel arrays// and operations on them /* This function takes the last element aspivot, places the pivot element at itscorrect position in sorted array, andplaces all smaller (smaller than pivot)to left of pivot and all greater elementsto right of pivot */function partition(first_name, last_name, height, low, high) { let pivot = height[high]; // pivot let i = (low - 1); // Index of smaller element for (let j = low; j <= high - 1; j++) { // If current element is smaller than // or equal to pivot. This means are // sorting sequence condition fails if // the condition becomes true. Thus the // two indices which shall be obtained // here will be i and jand therefore // we will be swapping values of i and j // in all the arrays. if (height[j] <= pivot) { i++; // increment index of smaller element // Swapping values of i and j in all the arrays let temp = first_name[i]; first_name[i] = first_name[j]; first_name[j] = temp; temp = last_name[i]; last_name[i] = last_name[j]; last_name[j] = temp; let temp1 = height[i]; height[i] = height[j]; height[j] = temp1; } } let temp = first_name[i + 1]; first_name[i + 1] = first_name[high]; first_name[high] = temp; temp = last_name[i + 1]; last_name[i + 1] = last_name[high]; last_name[high] = temp; let temp1 = height[i + 1]; height[i + 1] = height[high]; height[high] = temp1; return (i + 1);} // Function which implements quick sortfunction quickSort(first_name, last_name, height, low, high) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ let pi = partition(first_name, last_name, height, low, high); // Separately sort elements before // partition and after partition quickSort(first_name, last_name, height, low, pi - 1); quickSort(first_name, last_name, height, pi + 1, high); }} // Function which binary searches the height array// for value 158 and if found, prints the// corresponding value in other arrays at that index.function binarySearch(first_name, last_name, height, value, n) { let low = 0, high = n - 1; let index; while (low <= high) { index = Math.floor((high + low) / 2); if (height[index] == 158) { // This index of height array corresponds // to the name of the person in first // name and last name array. document.write("Person having height" + " 158 cms is " + first_name[index] + " " + last_name[index] + "<br>"); return; } else if (height[index] > 158) high = index - 1; else low = index + 1; } document.write("Sorry, no such person" + " with height" + "<br>"); document.write("158 cms is found in" + " the record <br>");} // Printing same index of each array. This// will give meaningful data as in parallel// array indices point to the values in// different arrays belonging to the same// entityfunction printParallelArray(first_name, last_name, height, n) { document.write("Name of people in increasing" + " order of their height: <br>"); for (let i = 0; i < n; i++) { document.write(first_name[i] + " " + last_name[i] + " has height " + height[i] + " cms <br>"); } document.write();} // These arrays together form a set of arrays// known as parallel arraylet n = 10;let first_name = ["Bones", "Welma", "Frank", "Han", "Jack", "Jinny", "Harry", "Emma", "Tony", "Sherlock"];let last_name = ["Smith", "Seger", "Mathers", "Solo", "Jackles", "Weasly", "Potter", "Watson", "Stark", "Holmes"];let height = [169, 158, 201, 183, 172, 152, 160, 163, 173, 185]; // Sorting the above arrays using quickSort// technique based on increasing order of// their heights.quickSort(first_name, last_name, height, 0, n - 1);printParallelArray(first_name, last_name, height, n); // Second tallest person in the sorted list// will be the second person from the right end.document.write("<br><br>Name of the second tallest" + " person is " + first_name[n - 2] + " " + last_name[n - 2] + "<br>"); // Third shortest person in the sorted list// will be the third person from the left end.document.write("Name of the third shortest" + " person is " + first_name[2] + " " + last_name[2] + "<br>"); // We binary search the height array to// search for a person having height 158 cms.binarySearch(first_name, last_name, height, 158, n); // This code is contributed by gfgking.</script> Output: Name of people in increasing order of their height: Jinny Weasly has height 152 cms Welma Seger has height 158 cms Harry Potter has height 160 cms Emma Watson has height 163 cms Bones Smith has height 169 cms Jack Jackles has height 172 cms Tony Stark has height 173 cms Han Solo has height 183 cms Sherlock Holmes has height 185 cms Frank Mathers has height 201 cms Name of the second tallest person is Sherlock Holmes Name of the third shortest person is Harry Potter Person having height 158 cms is Welma Seger Advantages: They can be used in languages which support only arrays of primitive types and not of records (or perhaps don’t support records at all). Parallel arrays are simple to understand and use, and are often used where declaring a record is more trouble than it’s worth. They can save a substantial amount of space in some cases by avoiding alignment issues. If the number of items is small, array indices can occupy significantly less space than full pointers, particularly on architectures with large words. Sequentially examining a single field of each record in the array is very fast on modern machines, since this amounts to a linear traversal of a single array, exhibiting ideal locality of reference and cache behavior. Disadvantages: They have significantly worse locality of reference when visiting the records non-sequentially and examining multiple fields of each record. They have little direct language support (the language and its syntax typically express no relationship between the arrays in the parallel array). They are expensive to grow or shrink since each of several arrays must be reallocated. Multi-level arrays can ameliorate this problem, but impacts performance due to the additional indirection needed to find the desired elements. parashar manishshaw1 Akanksha_Rai gfgking Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Python | Using 2D arrays/lists the right way Search an element in a sorted and rotated array
[ { "code": null, "e": 26385, "s": 26357, "text": "\n22 Jun, 2021" }, { "code": null, "e": 26799, "s": 26385, "text": "Parallel Array: Also known as structure an array (SoA), multiple arrays of the same size such that i-th element of each array is closely related and all i-th elements together represent an object or entity. An example parallel array is two arrays that represent x and y co-ordinates of n points. Below is another example where we store the first name, last name and heights of 5 people in three different arrays. " }, { "code": null, "e": 26956, "s": 26799, "text": "first_name = ['Bones', 'Welma', 'Frank', 'Han', 'Jack']\nlast_name = ['Smith', 'Seger', 'Mathers', 'Solo', 'Jackles']\nheight = [169, 158, 201, 183, 172]" }, { "code": null, "e": 27219, "s": 26956, "text": "This way we could easily store the information and for accessing, the first index of each array corresponds to the data belonging to the same person.Application: Two of the most essential applications performs on an array or a record are searching and sorting. " }, { "code": null, "e": 27738, "s": 27219, "text": "Searching: Each index in a parallel array corresponds to the data belonging to the same entity in a record. Thus, for searching an entity based on a specific value of an attribute, e.g. we need to find the name of a person having height >200 cms in the above example. Thus, we search for the index in the height array having value greater than 200. Now, once we have obtained the index, we print the values of the index in the first_name and last_name arrays. This way searching becomes an easy task in parallel array." }, { "code": null, "e": 28154, "s": 27738, "text": "Sorting: Now, using the same fact that each index corresponds to data items in different arrays corresponding to the same entity. Thus, we sort all arrays based on the same criteria. For example, in the above-displayed example, we need to sort the people in increasing order of their respective heights. Thus, when we swap the two heights, we even swap the corresponding values in other arrays using the same index." }, { "code": null, "e": 28287, "s": 28154, "text": "Searching:Following steps are performed to search an entity based on a specific attribute in structure of array or parallel array. " }, { "code": null, "e": 28481, "s": 28287, "text": "Search for the value of the required attribute in the respective array (e.g. search for values greater than 200 in the above example) using either of the linear search/binary search approaches." }, { "code": null, "e": 28550, "s": 28481, "text": "Store the index where the following values are obtained in the array" }, { "code": null, "e": 28608, "s": 28550, "text": "Print the values at the evaluated indices in other arrays" }, { "code": null, "e": 28892, "s": 28608, "text": "SortingThe arrays can be sorted in any way, numerical, alphabetical or any other way but the elements are placed at equally spaced addresses. Any of the sorting techniques can be used to sort the record based on a specified criteria. Following steps are performed to sort a record. " }, { "code": null, "e": 29177, "s": 28892, "text": "Find the index in the array (the array according to which sorting shall be done is based on the specified criteria) where the sequence voids (i.e. we need to compute those two indices where the sorting sequence fails, which is to be corrected by swapping the values at those indices)." }, { "code": null, "e": 29248, "s": 29177, "text": "Now swap the values of those two calculated indices in all the arrays." }, { "code": null, "e": 29740, "s": 29248, "text": "Thus, following the above steps, once the chosen array (the array to be chosen on a specified criterion) is sorted, all the arrays shall be sorted with respect to the chosen array. Implementation: 1) The code below stores the first name, second name, and height of 10 students. 2) Sorts them in increasing order of the height using quicksort algorithm. 3) Searches the name of the 2nd tallest student, the 3rd shortest student and the student having a height equal to 158 cms in the record. " }, { "code": null, "e": 29744, "s": 29740, "text": "C++" }, { "code": null, "e": 29749, "s": 29744, "text": "Java" }, { "code": null, "e": 29752, "s": 29749, "text": "C#" }, { "code": null, "e": 29756, "s": 29752, "text": "PHP" }, { "code": null, "e": 29767, "s": 29756, "text": "Javascript" }, { "code": "// C++ implementation of parallel arrays// and operations on them#include <iostream>using namespace std; /* This function takes the last element as pivot places the pivot element at its correct position in a sorted array, and places all smaller (smaller than pivot) to left of the pivot and all greater elements to right of pivot */int partition(string first_name[], string last_name[], int height[], int low, int high){ int pivot = height[high]; // pivot int i = (low - 1); // Index of smaller element for (int j = low; j <= high - 1; j++) { // If current element is smaller than // or equal to pivot. This means are // sorting sequence condition fails if // the condition becomes true. Thus the // two indices which shall be obtained // here will be i and j and therefore // we will be swapping values of i and j // in all the arrays. if (height[j] <= pivot) { // increment index of smaller element i++; // Swapping values of i and j in // all the arrays string temp = first_name[i]; first_name[i] = first_name[j]; first_name[j] = temp; temp = last_name[i]; last_name[i] = last_name[j]; last_name[j] = temp; int temp1 = height[i]; height[i] = height[j]; height[j] = temp1; } } string temp = first_name[i + 1]; first_name[i + 1] = first_name[high]; first_name[high] = temp; temp = last_name[i + 1]; last_name[i + 1] = last_name[high]; last_name[high] = temp; int temp1 = height[i + 1]; height[i + 1] = height[high]; height[high] = temp1; return (i + 1);} // Function which implements quick sortvoid quickSort(string first_name[], string last_name[], int height[], int low, int high){ if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(first_name, last_name, height, low, high); // Separately sort elements before // partition and after partition quickSort(first_name, last_name, height, low, pi - 1); quickSort(first_name, last_name, height, pi + 1, high); }} // Function which binary searches the height// array for value 158 and if found, prints// the corresponding value in other arrays// at that index.void binarySearch(string first_name[], string last_name[], int height[], int value, int n){ int low = 0, high = n - 1; int index; while (low <= high) { index = (high + low) / 2; if (height[index] == 158) { // This index of height array // corresponds to the name // of the person in first name // and last name array. cout << \"Person having height 158\" \" cms is \" << first_name[index] << \" \" << last_name[index] << endl; return; } else if (height[index] > 158) high = index - 1; else low = index + 1; } cout << \"Sorry, no such person with\" \" height 158 cms\"; cout << \"is found in the record\";} // Printing same index of each array. This// will give meaningful data as in parallel// array indices point to values in different// arrays belonging to the same entityvoid printParallelArray(string first_name[], string last_name[], int height[], int n){ cout << \"Name of people in increasing\"; cout << \"order of their height: \" << endl; for (int i = 0; i < n; i++) { cout << first_name[i] << \" \" << last_name[i] << \" has height \" << height[i] << \" cms\\n\"; } cout << endl;} // Driver Functionint main(){ // These arrays together form a set // of arrays known as parallel array int n = 10; string first_name[] = { \"Bones\", \"Welma\", \"Frank\", \"Han\", \"Jack\", \"Jinny\", \"Harry\", \"Emma\", \"Tony\", \"Sherlock\" }; string last_name[] = { \"Smith\", \"Seger\", \"Mathers\", \"Solo\", \"Jackles\", \"Weasly\", \"Potter\", \"Watson\", \"Stark\", \"Holmes\" }; int height[] = { 169, 158, 201, 183, 172, 152, 160, 163, 173, 185 }; // Sorting the above arrays using quickSort // technique based on increasing order of // their heights. quickSort(first_name, last_name, height, 0, n - 1); printParallelArray(first_name, last_name, height, n); // Second tallest person in the sorted // list will be the second person from the // right end. cout << \"Name of the second tallest person\" \" is \" << first_name[n - 2] << \" \" << last_name[n - 2] << endl; // Third shortest person in the sorted // list will be the third person from the // left end. cout << \"Name of the third shortest person is \" << first_name[2] << \" \" << last_name[2] << endl; // We binary search the height array to // search for a person having height 158 // cms. binarySearch(first_name, last_name, height, 158, n); return 0;}", "e": 35153, "s": 29767, "text": null }, { "code": "// Java implementation of parallel arrays// and operations on themimport java.util.*;import java.lang.*; class parallel_array_java { /* This function takes the last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(String first_name[], String last_name[], int height[], int low, int high) { int pivot = height[high]; // pivot int i = (low - 1); // Index of smaller element for (int j = low; j <= high - 1; j++) { // If current element is smaller than // or equal to pivot. This means are // sorting sequence condition fails if // the condition becomes true. Thus the // two indices which shall be obtained // here will be i and jand therefore // we will be swapping values of i and j // in all the arrays. if (height[j] <= pivot) { i++; // increment index of smaller element // Swapping values of i and j in all the arrays String temp = first_name[i]; first_name[i] = first_name[j]; first_name[j] = temp; temp = last_name[i]; last_name[i] = last_name[j]; last_name[j] = temp; int temp1 = height[i]; height[i] = height[j]; height[j] = temp1; } } String temp = first_name[i + 1]; first_name[i + 1] = first_name[high]; first_name[high] = temp; temp = last_name[i + 1]; last_name[i + 1] = last_name[high]; last_name[high] = temp; int temp1 = height[i + 1]; height[i + 1] = height[high]; height[high] = temp1; return (i + 1); } // Function which implements quick sort static void quickSort(String first_name[], String last_name[], int height[], int low, int high) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(first_name, last_name, height, low, high); // Separately sort elements before // partition and after partition quickSort(first_name, last_name, height, low, pi - 1); quickSort(first_name, last_name, height, pi + 1, high); } } // Function which binary searches the height array // for value 158 and if found, prints the // corresponding value in other arrays at that index. static void binarySearch(String first_name[], String last_name[], int height[], int value, int n) { int low = 0, high = n - 1; int index; while (low <= high) { index = (high + low) / 2; if (height[index] == 158) { // This index of height array corresponds // to the name of the person in first // name and last name array. System.out.println(\"Person having height\" + \" 158 cms is \" + first_name[index] + \" \" + last_name[index]); return; } else if (height[index] > 158) high = index - 1; else low = index + 1; } System.out.print(\"Sorry, no such person\" + \" with height\"); System.out.println(\"158 cms is found in\" + \" the record\"); } // Printing same index of each array. This // will give meaningful data as in parallel // array indices point to the values in // different arrays belonging to the same // entity static void printParallelArray(String first_name[], String last_name[], int height[], int n) { System.out.print(\"Name of people in increasing\" + \" order of\"); System.out.println(\"their height: \"); for (int i = 0; i < n; i++) { System.out.println(first_name[i] + \" \" + last_name[i] + \" has height \" + height[i] + \" cms\"); } System.out.println(); } public static void main(String args[]) { // These arrays together form a set of arrays // known as parallel array int n = 10; String[] first_name = { \"Bones\", \"Welma\", \"Frank\", \"Han\", \"Jack\", \"Jinny\", \"Harry\", \"Emma\", \"Tony\", \"Sherlock\" }; String[] last_name = { \"Smith\", \"Seger\", \"Mathers\", \"Solo\", \"Jackles\", \"Weasly\", \"Potter\", \"Watson\", \"Stark\", \"Holmes\" }; int[] height = { 169, 158, 201, 183, 172, 152, 160, 163, 173, 185 }; // Sorting the above arrays using quickSort // technique based on increasing order of // their heights. quickSort(first_name, last_name, height, 0, n - 1); printParallelArray(first_name, last_name, height, n); // Second tallest person in the sorted list // will be the second person from the right end. System.out.println(\"Name of the second tallest\" + \"person is \" + first_name[n - 2] + \" \" + last_name[n - 2]); // Third shortest person in the sorted list // will be the third person from the left end. System.out.println(\"Name of the third shortest\" + \" person is \" + first_name[2] + \" \" + last_name[2]); // We binary search the height array to // search for a person having height 158 cms. binarySearch(first_name, last_name, height, 158, n); }}", "e": 41141, "s": 35153, "text": null }, { "code": "// C# implementation of parallel arrays// and operations on themusing System; class GFG { /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(String[] first_name, String[] last_name, int[] height, int low, int high) { // pivot int pivot = height[high]; // Index of smaller element int i = (low - 1); for (int j = low; j <= high - 1; j++) { // If current element is smaller // than or equal to pivot. This // means are sorting sequence // condition fails if the condition // becomes true. Thus the two // indices which shall be obtained // here will be i and jand therefore // we will be swapping values of i // and j in all the arrays. if (height[j] <= pivot) { // increment index of smaller // element i++; // Swapping values of i and j // in all the arrays String temp = first_name[i]; first_name[i] = first_name[j]; first_name[j] = temp; temp = last_name[i]; last_name[i] = last_name[j]; last_name[j] = temp; int temp1 = height[i]; height[i] = height[j]; height[j] = temp1; } } String tempp = first_name[i + 1]; first_name[i + 1] = first_name[high]; first_name[high] = tempp; tempp = last_name[i + 1]; last_name[i + 1] = last_name[high]; last_name[high] = tempp; int temp2 = height[i + 1]; height[i + 1] = height[high]; height[high] = temp2; return (i + 1); } // Function which implements quick sort static void quickSort(String[] first_name, String[] last_name, int[] height, int low, int high) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(first_name, last_name, height, low, high); // Separately sort elements before // partition and after partition quickSort(first_name, last_name, height, low, pi - 1); quickSort(first_name, last_name, height, pi + 1, high); } } // Function which binary searches the // height array for value 158 and if // found, prints the corresponding value // in other arrays at that index. static void binarySearch(String[] first_name, String[] last_name, int[] height, int value, int n) { int low = 0, high = n - 1; int index; while (low <= high) { index = (high + low) / 2; if (height[index] == 158) { // This index of height array // corresponds to the name of // the person in first name and // last name array. Console.Write(\"Person having height\" + \" 158 cms is \" + first_name[index] + \" \" + last_name[index]); return; } else if (height[index] > 158) high = index - 1; else low = index + 1; } Console.Write(\"Sorry, no such person\" + \" with height 158 cms is \" + \"found in the record\"); } // Printing same index of each array. This // will give meaningful data as in parallel // array indices point to the values in // different arrays belonging to the same // entity static void printParallelArray(String[] first_name, String[] last_name, int[] height, int n) { Console.WriteLine(\"Name of people in increasing\" + \" order of their height: \"); for (int i = 0; i < n; i++) { Console.WriteLine(first_name[i] + \" \" + last_name[i] + \" has height \" + height[i] + \" cms\"); } Console.WriteLine(); } // Driver function public static void Main() { // These arrays together form a set of // arrays known as parallel array int n = 10; String[] first_name = { \"Bones\", \"Welma\", \"Frank\", \"Han\", \"Jack\", \"Jinny\", \"Harry\", \"Emma\", \"Tony\", \"Sherlock\" }; String[] last_name = { \"Smith\", \"Seger\", \"Mathers\", \"Solo\", \"Jackles\", \"Weasly\", \"Potter\", \"Watson\", \"Stark\", \"Holmes\" }; int[] height = { 169, 158, 201, 183, 172, 152, 160, 163, 173, 185 }; // Sorting the above arrays using quickSort // technique based on increasing order of // their heights. quickSort(first_name, last_name, height, 0, n - 1); printParallelArray(first_name, last_name, height, n); // Second tallest person in the sorted list // will be the second person from the right end. Console.WriteLine(\"Name of the second tallest\" + \"person is \" + first_name[n - 2] + \" \" + last_name[n - 2]); // Third shortest person in the sorted list // will be the third person from the left end. Console.WriteLine(\"Name of the third shortest\" + \" person is \" + first_name[2] + \" \" + last_name[2]); // We binary search the height array to // search for a person having height 158 cms. binarySearch(first_name, last_name, height, 158, n); }} // This codecontribute by parashar.", "e": 47809, "s": 41141, "text": null }, { "code": "<?php// PHP implementation of parallel// arrays and operations on them /* This function takes last elementas pivot, places the pivot elementat its correct position in sortedarray, and places all smaller(smaller than pivot) to left of pivotand all greater elements to rightof pivot */function partition(&$first_name, &$last_name, &$height, $low, $high){ $pivot = $height[$high]; // pivot $i = ($low - 1); // Index of smaller element for ($j = $low; $j <= $high - 1; $j++) { // If current element is smaller // than or equal to pivot. This // means are sorting sequence // condition fails if the condition // becomes true. Thus the two indices // which shall be obtained here will // be i and j and therefore we will // be swapping values of i and j // in all the arrays. if ($height[$j] <= $pivot) { // increment index of // smaller element $i++; // Swapping values // of i and j in // all the arrays $temp = $first_name[$i]; $first_name[$i] = $first_name[$j]; $first_name[$j] = $temp; $temp = $last_name[$i]; $last_name[$i] = $last_name[$j]; $last_name[$j] = $temp; $temp1 = $height[$i]; $height[$i] = $height[$j]; $height[$j] = $temp1; } } $temp = $first_name[$i + 1]; $first_name[$i + 1] = $first_name[$high]; $first_name[$high] = $temp; $temp = $last_name[$i + 1]; $last_name[$i + 1] = $last_name[$high]; $last_name[$high] = $temp; $temp1 = $height[$i + 1]; $height[$i + 1] = $height[$high]; $height[$high] = $temp1; return ($i + 1);} // Function which// implements quick sortfunction quickSort(&$first_name, &$last_name, &$height, $low, $high){ if ($low < $high) { /* pi is partitioning index, arr[p] is now at right place */ $pi = partition($first_name, $last_name, $height, $low, $high); // Separately sort elements // before partition and // after partition quickSort($first_name, $last_name, $height, $low, $pi - 1); quickSort($first_name, $last_name, $height, $pi + 1, $high); }} // Function which binary searches// the height array for value 158// and if found, prints the// corresponding value in other// arrays at that index.function binarySearch(&$first_name, &$last_name, &$height, $value, $n){ $low = 0; $high = $n - 1; $index = 0; while ($low <= $high) { $index = ($high + $low) / 2; if ($height[$index] == 158) { // This index of height array // corresponds to the name // of the person in first name // and last name array. echo (\"Person having height 158\". \" cms is \" . $first_name[$index] . \" \" . $last_name[$index] . \"\\n\"); return; } else if ($height[$index] > 158) $high = $index - 1; else $low = $index + 1; } echo (\"Sorry, no such person with\" . \" height 158 cms\"); echo (\"is found in the record\");} // Printing same index of each// array. This will give meaningful// data as in parallel array indices// po$to values in different arrays// belonging to the same entityfunction printParallelArray(&$first_name, &$last_name, &$height, &$n){ echo (\"Name of people in increasing\"); echo (\" order of their height: \" . \"\\n\"); for ($i = 0; $i < $n; $i++) { echo ($first_name[$i] . \" \" . $last_name[$i] . \" has height \" . $height[$i] . \" cms\\n\"); } echo (\"\\n\");} // Driver Code // These arrays together// form a set of arrays// known as parallel array$n = 10;$first_name = array(\"Bones\", \"Welma\", \"Frank\", \"Han\", \"Jack\", \"Jinny\", \"Harry\", \"Emma\", \"Tony\", \"Sherlock\");$last_name = array(\"Smith\", \"Seger\", \"Mathers\", \"Solo\", \"Jackles\", \"Weasly\", \"Potter\", \"Watson\", \"Stark\", \"Holmes\");$height = array(169, 158, 201, 183, 172, 152, 160, 163, 173, 185); // Sorting the above arrays// using quickSort technique// based on increasing order// of their heights.quickSort($first_name, $last_name, $height, 0, $n - 1);printParallelArray($first_name, $last_name, $height, $n); // Second tallest person in// the sorted list will be// second person from the// right end.echo (\"Name of the second \". \"tallest person is \" . $first_name[$n - 2] . \" \" . $last_name[$n - 2] . \"\\n\"); // Third shortest person in// the sorted list will be// third person from the// left end.echo (\"Name of the third shortest person is \" . $first_name[2] . \" \" . $last_name[2] . \"\\n\"); // We binary search the height// array to search for a person// having height 158 cms.binarySearch($first_name, $last_name, $height, 158, $n); // This code is contributed by// Manish Shaw(manishshaw1)?>", "e": 53127, "s": 47809, "text": null }, { "code": "<script>// Javascript implementation of parallel arrays// and operations on them /* This function takes the last element aspivot, places the pivot element at itscorrect position in sorted array, andplaces all smaller (smaller than pivot)to left of pivot and all greater elementsto right of pivot */function partition(first_name, last_name, height, low, high) { let pivot = height[high]; // pivot let i = (low - 1); // Index of smaller element for (let j = low; j <= high - 1; j++) { // If current element is smaller than // or equal to pivot. This means are // sorting sequence condition fails if // the condition becomes true. Thus the // two indices which shall be obtained // here will be i and jand therefore // we will be swapping values of i and j // in all the arrays. if (height[j] <= pivot) { i++; // increment index of smaller element // Swapping values of i and j in all the arrays let temp = first_name[i]; first_name[i] = first_name[j]; first_name[j] = temp; temp = last_name[i]; last_name[i] = last_name[j]; last_name[j] = temp; let temp1 = height[i]; height[i] = height[j]; height[j] = temp1; } } let temp = first_name[i + 1]; first_name[i + 1] = first_name[high]; first_name[high] = temp; temp = last_name[i + 1]; last_name[i + 1] = last_name[high]; last_name[high] = temp; let temp1 = height[i + 1]; height[i + 1] = height[high]; height[high] = temp1; return (i + 1);} // Function which implements quick sortfunction quickSort(first_name, last_name, height, low, high) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ let pi = partition(first_name, last_name, height, low, high); // Separately sort elements before // partition and after partition quickSort(first_name, last_name, height, low, pi - 1); quickSort(first_name, last_name, height, pi + 1, high); }} // Function which binary searches the height array// for value 158 and if found, prints the// corresponding value in other arrays at that index.function binarySearch(first_name, last_name, height, value, n) { let low = 0, high = n - 1; let index; while (low <= high) { index = Math.floor((high + low) / 2); if (height[index] == 158) { // This index of height array corresponds // to the name of the person in first // name and last name array. document.write(\"Person having height\" + \" 158 cms is \" + first_name[index] + \" \" + last_name[index] + \"<br>\"); return; } else if (height[index] > 158) high = index - 1; else low = index + 1; } document.write(\"Sorry, no such person\" + \" with height\" + \"<br>\"); document.write(\"158 cms is found in\" + \" the record <br>\");} // Printing same index of each array. This// will give meaningful data as in parallel// array indices point to the values in// different arrays belonging to the same// entityfunction printParallelArray(first_name, last_name, height, n) { document.write(\"Name of people in increasing\" + \" order of their height: <br>\"); for (let i = 0; i < n; i++) { document.write(first_name[i] + \" \" + last_name[i] + \" has height \" + height[i] + \" cms <br>\"); } document.write();} // These arrays together form a set of arrays// known as parallel arraylet n = 10;let first_name = [\"Bones\", \"Welma\", \"Frank\", \"Han\", \"Jack\", \"Jinny\", \"Harry\", \"Emma\", \"Tony\", \"Sherlock\"];let last_name = [\"Smith\", \"Seger\", \"Mathers\", \"Solo\", \"Jackles\", \"Weasly\", \"Potter\", \"Watson\", \"Stark\", \"Holmes\"];let height = [169, 158, 201, 183, 172, 152, 160, 163, 173, 185]; // Sorting the above arrays using quickSort// technique based on increasing order of// their heights.quickSort(first_name, last_name, height, 0, n - 1);printParallelArray(first_name, last_name, height, n); // Second tallest person in the sorted list// will be the second person from the right end.document.write(\"<br><br>Name of the second tallest\" + \" person is \" + first_name[n - 2] + \" \" + last_name[n - 2] + \"<br>\"); // Third shortest person in the sorted list// will be the third person from the left end.document.write(\"Name of the third shortest\" + \" person is \" + first_name[2] + \" \" + last_name[2] + \"<br>\"); // We binary search the height array to// search for a person having height 158 cms.binarySearch(first_name, last_name, height, 158, n); // This code is contributed by gfgking.</script>", "e": 57885, "s": 53127, "text": null }, { "code": null, "e": 57895, "s": 57885, "text": "Output: " }, { "code": null, "e": 58411, "s": 57895, "text": "Name of people in increasing order of their height:\nJinny Weasly has height 152 cms\nWelma Seger has height 158 cms\nHarry Potter has height 160 cms\nEmma Watson has height 163 cms\nBones Smith has height 169 cms\nJack Jackles has height 172 cms\nTony Stark has height 173 cms\nHan Solo has height 183 cms\nSherlock Holmes has height 185 cms\nFrank Mathers has height 201 cms\n\n\nName of the second tallest person is Sherlock Holmes\nName of the third shortest person is Harry Potter\nPerson having height 158 cms is Welma Seger" }, { "code": null, "e": 58424, "s": 58411, "text": "Advantages: " }, { "code": null, "e": 58561, "s": 58424, "text": "They can be used in languages which support only arrays of primitive types and not of records (or perhaps don’t support records at all)." }, { "code": null, "e": 58688, "s": 58561, "text": "Parallel arrays are simple to understand and use, and are often used where declaring a record is more trouble than it’s worth." }, { "code": null, "e": 58776, "s": 58688, "text": "They can save a substantial amount of space in some cases by avoiding alignment issues." }, { "code": null, "e": 58929, "s": 58776, "text": "If the number of items is small, array indices can occupy significantly less space than full pointers, particularly on architectures with large words. " }, { "code": null, "e": 59147, "s": 58929, "text": "Sequentially examining a single field of each record in the array is very fast on modern machines, since this amounts to a linear traversal of a single array, exhibiting ideal locality of reference and cache behavior." }, { "code": null, "e": 59163, "s": 59147, "text": "Disadvantages: " }, { "code": null, "e": 59304, "s": 59163, "text": "They have significantly worse locality of reference when visiting the records non-sequentially and examining multiple fields of each record." }, { "code": null, "e": 59451, "s": 59304, "text": "They have little direct language support (the language and its syntax typically express no relationship between the arrays in the parallel array)." }, { "code": null, "e": 59681, "s": 59451, "text": "They are expensive to grow or shrink since each of several arrays must be reallocated. Multi-level arrays can ameliorate this problem, but impacts performance due to the additional indirection needed to find the desired elements." }, { "code": null, "e": 59690, "s": 59681, "text": "parashar" }, { "code": null, "e": 59702, "s": 59690, "text": "manishshaw1" }, { "code": null, "e": 59715, "s": 59702, "text": "Akanksha_Rai" }, { "code": null, "e": 59723, "s": 59715, "text": "gfgking" }, { "code": null, "e": 59730, "s": 59723, "text": "Arrays" }, { "code": null, "e": 59737, "s": 59730, "text": "Arrays" }, { "code": null, "e": 59835, "s": 59737, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 59903, "s": 59835, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 59947, "s": 59903, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 59995, "s": 59947, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 60018, "s": 59995, "text": "Introduction to Arrays" }, { "code": null, "e": 60050, "s": 60018, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 60064, "s": 60050, "text": "Linear Search" }, { "code": null, "e": 60085, "s": 60064, "text": "Linked List vs Array" }, { "code": null, "e": 60170, "s": 60085, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 60215, "s": 60170, "text": "Python | Using 2D arrays/lists the right way" } ]
Introduction to ADO.NET - GeeksforGeeks
23 Jun, 2021 The .NET Framework includes its own data access technology i.e. ADO.NET. ADO.NET is the latest implementation of Microsoft’s Universal Data Access strategy. ADO.NET consists of managed classes that allows .NET applications to connect to data sources such as Microsoft SQL Server, Microsoft Access, Oracle, XML, etc., execute commands and manage disconnected data..t Microsoft ADO.NET is the latest improvement after ADO. Firstly, ADO.NET was introduced in the 10th version of the .NET framework, which helps in providing an extensive array of various features to handle data in different modes, such as connected mode and disconnected mode. In connected mode, we are dealing with live data and in disconnected mode, data is provided from the data store.ADO.NET was primarily developed to address two ways to work with data that we are getting from data sources. The two ways are as follows : The first is to do with the user’s need to access data once and to iterate through a collection of data in a single instance.The second way to work with data is disconnected architecture mode, in which we have to grab a collection of data and we use this data separately from the data store itself. The first is to do with the user’s need to access data once and to iterate through a collection of data in a single instance. The second way to work with data is disconnected architecture mode, in which we have to grab a collection of data and we use this data separately from the data store itself. Architecture of ADO.NET :ADO.NET uses a multilayered architecture that revolves around a few key concepts as – asConnection Command DataSet objects The ADO.NET architecture is a little bit different from the ADO, which can be shown from the following figure of the architecture of ADO.NET. Architecture of ADO.NET One of the key differences between ADO and ADO.NET is how they deal with the challenge of different data sources. In ADO.NET, programmers always use a generic set of objects, no matter what the underlying data source is. For example, if we want to retrieve a record from an Oracle Database, we use the same connection class that we use to tackle the same task with SQL Server. This is not the case with ADO.NET, which uses a data provider model and the DataSet. Features of ADO.NET :The following are the features of ADO.NET – Interoperability- We know that XML documents are text-based formats. So, one can edit and edit XML documents using standard text-editing tools. ADO.NET uses XML in all data exchanges and for internal representation of data. Maintainability – ADO.NET is built around the idea of separation of data logic and user interface. It means that we can create our application in independent layers. Programmability (Typed Programming) –It is a programming style in which user words are used to construct statements or evaluate expressions. For example: If we want to select the “Marks” column from “Kawal” from the “Student” table, the following is the way to do so: DataSet.Student("Kawal").Marks; Performance –It uses disconnected data architecture which is easy to scale as it reduces the load on the database. Everything is handled on the client-side, so it improves performance. Scalability –It means meeting the needs of the growing number of clients, which degrading performance. As it uses disconnected data access, applications do not retain database lock connections for a longer time. Thus, it accommodates scalability by encouraging programmers to conserve limited resources and allow users to access data simultaneously. Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Software Engineering | Integration Testing System Testing Software Engineering | Black box testing Software Engineering | Software Quality Assurance What is DFD(Data Flow Diagram)? Difference between IAAS, PAAS and SAAS Difference between Unit Testing and Integration Testing Use Case Diagram for Library Management System Object Oriented Analysis and Design Software Development Life Cycle (SDLC)
[ { "code": null, "e": 26261, "s": 26233, "text": "\n23 Jun, 2021" }, { "code": null, "e": 26627, "s": 26261, "text": "The .NET Framework includes its own data access technology i.e. ADO.NET. ADO.NET is the latest implementation of Microsoft’s Universal Data Access strategy. ADO.NET consists of managed classes that allows .NET applications to connect to data sources such as Microsoft SQL Server, Microsoft Access, Oracle, XML, etc., execute commands and manage disconnected data..t" }, { "code": null, "e": 27154, "s": 26627, "text": "Microsoft ADO.NET is the latest improvement after ADO. Firstly, ADO.NET was introduced in the 10th version of the .NET framework, which helps in providing an extensive array of various features to handle data in different modes, such as connected mode and disconnected mode. In connected mode, we are dealing with live data and in disconnected mode, data is provided from the data store.ADO.NET was primarily developed to address two ways to work with data that we are getting from data sources. The two ways are as follows :" }, { "code": null, "e": 27453, "s": 27154, "text": "The first is to do with the user’s need to access data once and to iterate through a collection of data in a single instance.The second way to work with data is disconnected architecture mode, in which we have to grab a collection of data and we use this data separately from the data store itself." }, { "code": null, "e": 27579, "s": 27453, "text": "The first is to do with the user’s need to access data once and to iterate through a collection of data in a single instance." }, { "code": null, "e": 27753, "s": 27579, "text": "The second way to work with data is disconnected architecture mode, in which we have to grab a collection of data and we use this data separately from the data store itself." }, { "code": null, "e": 27864, "s": 27753, "text": "Architecture of ADO.NET :ADO.NET uses a multilayered architecture that revolves around a few key concepts as –" }, { "code": null, "e": 27877, "s": 27864, "text": "asConnection" }, { "code": null, "e": 27885, "s": 27877, "text": "Command" }, { "code": null, "e": 27901, "s": 27885, "text": "DataSet objects" }, { "code": null, "e": 28043, "s": 27901, "text": "The ADO.NET architecture is a little bit different from the ADO, which can be shown from the following figure of the architecture of ADO.NET." }, { "code": null, "e": 28067, "s": 28043, "text": "Architecture of ADO.NET" }, { "code": null, "e": 28529, "s": 28067, "text": "One of the key differences between ADO and ADO.NET is how they deal with the challenge of different data sources. In ADO.NET, programmers always use a generic set of objects, no matter what the underlying data source is. For example, if we want to retrieve a record from an Oracle Database, we use the same connection class that we use to tackle the same task with SQL Server. This is not the case with ADO.NET, which uses a data provider model and the DataSet." }, { "code": null, "e": 28594, "s": 28529, "text": "Features of ADO.NET :The following are the features of ADO.NET –" }, { "code": null, "e": 28818, "s": 28594, "text": "Interoperability- We know that XML documents are text-based formats. So, one can edit and edit XML documents using standard text-editing tools. ADO.NET uses XML in all data exchanges and for internal representation of data." }, { "code": null, "e": 28984, "s": 28818, "text": "Maintainability – ADO.NET is built around the idea of separation of data logic and user interface. It means that we can create our application in independent layers." }, { "code": null, "e": 29252, "s": 28984, "text": "Programmability (Typed Programming) –It is a programming style in which user words are used to construct statements or evaluate expressions. For example: If we want to select the “Marks” column from “Kawal” from the “Student” table, the following is the way to do so:" }, { "code": null, "e": 29284, "s": 29252, "text": "DataSet.Student(\"Kawal\").Marks;" }, { "code": null, "e": 29469, "s": 29284, "text": "Performance –It uses disconnected data architecture which is easy to scale as it reduces the load on the database. Everything is handled on the client-side, so it improves performance." }, { "code": null, "e": 29819, "s": 29469, "text": "Scalability –It means meeting the needs of the growing number of clients, which degrading performance. As it uses disconnected data access, applications do not retain database lock connections for a longer time. Thus, it accommodates scalability by encouraging programmers to conserve limited resources and allow users to access data simultaneously." }, { "code": null, "e": 29840, "s": 29819, "text": "Software Engineering" }, { "code": null, "e": 29938, "s": 29840, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29981, "s": 29938, "text": "Software Engineering | Integration Testing" }, { "code": null, "e": 29996, "s": 29981, "text": "System Testing" }, { "code": null, "e": 30037, "s": 29996, "text": "Software Engineering | Black box testing" }, { "code": null, "e": 30087, "s": 30037, "text": "Software Engineering | Software Quality Assurance" }, { "code": null, "e": 30119, "s": 30087, "text": "What is DFD(Data Flow Diagram)?" }, { "code": null, "e": 30158, "s": 30119, "text": "Difference between IAAS, PAAS and SAAS" }, { "code": null, "e": 30214, "s": 30158, "text": "Difference between Unit Testing and Integration Testing" }, { "code": null, "e": 30261, "s": 30214, "text": "Use Case Diagram for Library Management System" }, { "code": null, "e": 30297, "s": 30261, "text": "Object Oriented Analysis and Design" } ]
HTML 5 <summary> Tag - GeeksforGeeks
25 Jan, 2022 The <summary> tag in HTML is used to define a summary for the <details> element. The <summary> element is used along with the <details> element and provides a summary visible to the user. When the summary is clicked by the user, the content placed inside the <details> element becomes visible which was previously hidden. The <summary> tag was added in HTML 5. The <summary> tag requires both starting and ending tag. Note: The <summary> element should be the first child element of the <details> element. Syntax: <summary> Content </summary> Below program illustrates the <summary> element:Input : HTML <!DOCTYPE html><html><body> <details> <!-- html summary tag is used here --> <summary>GeeksforGeeks.</summary> <p> It is a portal for geeks.</p> </details> </body></html> Output : Supported Browsers: Google Chrome 12.0 Firefox 48.0 Opera 15.0 Safari 6.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. nidhi_biet shubhamyadav4 hritikbhatnagar2182 HTML5 HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property 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": 24644, "s": 24616, "text": "\n25 Jan, 2022" }, { "code": null, "e": 24726, "s": 24644, "text": "The <summary> tag in HTML is used to define a summary for the <details> element. " }, { "code": null, "e": 24833, "s": 24726, "text": "The <summary> element is used along with the <details> element and provides a summary visible to the user." }, { "code": null, "e": 24967, "s": 24833, "text": "When the summary is clicked by the user, the content placed inside the <details> element becomes visible which was previously hidden." }, { "code": null, "e": 25006, "s": 24967, "text": "The <summary> tag was added in HTML 5." }, { "code": null, "e": 25063, "s": 25006, "text": "The <summary> tag requires both starting and ending tag." }, { "code": null, "e": 25151, "s": 25063, "text": "Note: The <summary> element should be the first child element of the <details> element." }, { "code": null, "e": 25160, "s": 25151, "text": "Syntax: " }, { "code": null, "e": 25189, "s": 25160, "text": "<summary> Content </summary>" }, { "code": null, "e": 25246, "s": 25189, "text": "Below program illustrates the <summary> element:Input : " }, { "code": null, "e": 25251, "s": 25246, "text": "HTML" }, { "code": "<!DOCTYPE html><html><body> <details> <!-- html summary tag is used here --> <summary>GeeksforGeeks.</summary> <p> It is a portal for geeks.</p> </details> </body></html>", "e": 25428, "s": 25251, "text": null }, { "code": null, "e": 25439, "s": 25428, "text": "Output : " }, { "code": null, "e": 25460, "s": 25439, "text": "Supported Browsers: " }, { "code": null, "e": 25479, "s": 25460, "text": "Google Chrome 12.0" }, { "code": null, "e": 25492, "s": 25479, "text": "Firefox 48.0" }, { "code": null, "e": 25503, "s": 25492, "text": "Opera 15.0" }, { "code": null, "e": 25514, "s": 25503, "text": "Safari 6.0" }, { "code": null, "e": 25653, "s": 25516, "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": 25664, "s": 25653, "text": "nidhi_biet" }, { "code": null, "e": 25678, "s": 25664, "text": "shubhamyadav4" }, { "code": null, "e": 25698, "s": 25678, "text": "hritikbhatnagar2182" }, { "code": null, "e": 25704, "s": 25698, "text": "HTML5" }, { "code": null, "e": 25709, "s": 25704, "text": "HTML" }, { "code": null, "e": 25726, "s": 25709, "text": "Web Technologies" }, { "code": null, "e": 25731, "s": 25726, "text": "HTML" }, { "code": null, "e": 25829, "s": 25731, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25879, "s": 25829, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 25941, "s": 25879, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 25989, "s": 25941, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26049, "s": 25989, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 26102, "s": 26049, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 26142, "s": 26102, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 26175, "s": 26142, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26220, "s": 26175, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26263, "s": 26220, "text": "How to fetch data from an API in ReactJS ?" } ]
StringTokenizer hasMoreElements() Method in Java with Examples - GeeksforGeeks
28 Jan, 2019 The hasMoreElements() method of StringTokenizer class also checks whether there are any more tokens available with this StringTokenizer. It is similar to the hasMoreTokens(). The method exists exclusively so that the Enumeration interface of this class can be implemented. Syntax: public boolean hasMoreElements() Parameters: The method does not take any parameters. Return Value: The method returns boolean True if the availability of at least one more token is found in the string after the current position else false. Below programs illustrate the working of hasMoreElements() Method of StringTokenizer:Example 1: // Java code to illustrate hasMoreElements() method import java.util.*; public class StringTokenizer_Demo { public static void main(String args[]) { // Creating a StringTokenizer StringTokenizer str_arr = new StringTokenizer( "Lets practice at GeeksforGeeks"); // Counting the tokens System.out.println("The number of Tokens are: " + str_arr.countTokens()); // Checking for any tokens System.out.println(str_arr.hasMoreElements()); // Checking and displaying the Tokens while (str_arr.hasMoreElements()) { System.out.println("The Next token: " + str_arr.nextToken()); } }} The number of Tokens are: 4 true The Next token: Lets The Next token: practice The Next token: at The Next token: GeeksforGeeks Example 2: // Java code to illustrate hasMoreElements() method import java.util.*; public class StringTokenizer_Demo { public static void main(String args[]) { // Creating a StringTokenizer StringTokenizer str_arr = new StringTokenizer(""); // Counting the tokens System.out.println("The number of Tokens are: " + str_arr.countTokens()); // Checking for any tokens System.out.println(str_arr.hasMoreElements()); }} The number of Tokens are: 0 false Java - util package Java-Functions Java-StringTokenizer Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java Stream In Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 25916, "s": 25888, "text": "\n28 Jan, 2019" }, { "code": null, "e": 26189, "s": 25916, "text": "The hasMoreElements() method of StringTokenizer class also checks whether there are any more tokens available with this StringTokenizer. It is similar to the hasMoreTokens(). The method exists exclusively so that the Enumeration interface of this class can be implemented." }, { "code": null, "e": 26197, "s": 26189, "text": "Syntax:" }, { "code": null, "e": 26230, "s": 26197, "text": "public boolean hasMoreElements()" }, { "code": null, "e": 26283, "s": 26230, "text": "Parameters: The method does not take any parameters." }, { "code": null, "e": 26438, "s": 26283, "text": "Return Value: The method returns boolean True if the availability of at least one more token is found in the string after the current position else false." }, { "code": null, "e": 26534, "s": 26438, "text": "Below programs illustrate the working of hasMoreElements() Method of StringTokenizer:Example 1:" }, { "code": "// Java code to illustrate hasMoreElements() method import java.util.*; public class StringTokenizer_Demo { public static void main(String args[]) { // Creating a StringTokenizer StringTokenizer str_arr = new StringTokenizer( \"Lets practice at GeeksforGeeks\"); // Counting the tokens System.out.println(\"The number of Tokens are: \" + str_arr.countTokens()); // Checking for any tokens System.out.println(str_arr.hasMoreElements()); // Checking and displaying the Tokens while (str_arr.hasMoreElements()) { System.out.println(\"The Next token: \" + str_arr.nextToken()); } }}", "e": 27280, "s": 26534, "text": null }, { "code": null, "e": 27409, "s": 27280, "text": "The number of Tokens are: 4\ntrue\nThe Next token: Lets\nThe Next token: practice\nThe Next token: at\nThe Next token: GeeksforGeeks\n" }, { "code": null, "e": 27420, "s": 27409, "text": "Example 2:" }, { "code": "// Java code to illustrate hasMoreElements() method import java.util.*; public class StringTokenizer_Demo { public static void main(String args[]) { // Creating a StringTokenizer StringTokenizer str_arr = new StringTokenizer(\"\"); // Counting the tokens System.out.println(\"The number of Tokens are: \" + str_arr.countTokens()); // Checking for any tokens System.out.println(str_arr.hasMoreElements()); }}", "e": 27918, "s": 27420, "text": null }, { "code": null, "e": 27953, "s": 27918, "text": "The number of Tokens are: 0\nfalse\n" }, { "code": null, "e": 27973, "s": 27953, "text": "Java - util package" }, { "code": null, "e": 27988, "s": 27973, "text": "Java-Functions" }, { "code": null, "e": 28009, "s": 27988, "text": "Java-StringTokenizer" }, { "code": null, "e": 28014, "s": 28009, "text": "Java" }, { "code": null, "e": 28019, "s": 28014, "text": "Java" }, { "code": null, "e": 28117, "s": 28019, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28168, "s": 28117, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28198, "s": 28168, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28217, "s": 28198, "text": "Interfaces in Java" }, { "code": null, "e": 28232, "s": 28217, "text": "Stream In Java" }, { "code": null, "e": 28263, "s": 28232, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28281, "s": 28263, "text": "ArrayList in Java" }, { "code": null, "e": 28313, "s": 28281, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28333, "s": 28313, "text": "Stack Class in Java" }, { "code": null, "e": 28365, "s": 28333, "text": "Multidimensional Arrays in Java" } ]
Create a Registration Form using PyWebIO Module in Python - GeeksforGeeks
06 Jun, 2021 In this article, we are going to create a registration form using the PyWebIO module. This is a Python module mostly used to create simple and interactive interfaces on the local web using Python Programming. This form will take username, name, password, email, website link as input. Talking about passwords, it will also check your password again to confirm whether your password is correct or not. It will also validate your phone number, website link, email address. After that, you will get the radio button consisting of Gender, and you will also get the comment section so that you can write your feedback. To create a proper form with validations we will learn different form elements one by one with examples. 1. input_group: This element is used to get the inputs in the group. When we use input_group, we need to provide the name parameter to each input function to identify the input items in the result. Syntax: input_group(“Title”, [input(‘Any name’, name=’Anything’),input(‘Any name’, name=’Anything’)]) Python3 info = input_group("Group inputs", [ input('Username', name='username'), input('Password', name='pass')]) Output: 2. input: This element is used to take all kinds of inputs of the user from the browser. Syntax: input(‘Some text’) Python3 input("Your name") Output: 3. type: This is defined inside the input function or input_group function. This depends on user choice whether the user wants a number in the input or a text in the input. If the type equals the number, it will only accept numbers and a similar case for the text. Syntax: input(‘Some text’, type=TEXT) input(‘Some text’, type=NUMBER) input(‘Some text’, type=PASSWORD) Python3 input('Name', type=TEXT)input('PIN', type=NUMBER)input('Password', type=PASSWORD) Output: 4. required: If required is true, that means you have to input something, we can’t leave blank, otherwise, it will through an error called “Please fill out this field”. By default, it’s false. Syntax: input(‘Some text’, required=True) Python3 input('Name', required=True) Output: 5. validate: This element receives input as a parameter, when the input value is valid, it returns True, when the user input is invalid, it returns an error message. Syntax: input(‘Some text’, validate=is_valid) Python3 def is_valid(data): if data <= 0: return 'Age cannot be negative!' input('Age', type=NUMBER, validate=is_valid) Output: 6. cancelable: Whether the form can be canceled. Default is False. If cancelable=True, a “Cancel” button will be displayed at the bottom of the form. Syntax: input_group(“Title”, [input(‘Any name’, name=’Anything’),input(‘Any name’, name=’Anything’)], cancelable=True) Python3 input_group("Info", [input('Name', name='name'),input('PIN ', name='pin')], cancelable=True) Output: 7. PlaceHolder: This element is used only in the input_group function, this is used to show a very light text. Syntax: input(‘Some text’, placeholder=”some text”) Python3 input('Name', placeholder="Please Enter your name") Output: 8. radio: The radio button is used when we have to choose only one option in the many options, i.e., only a single can be selected. Syntax: radio(“Some text”, options=[‘Option 1’, ‘Option 2’]) Python3 radio("Gender", options=['Male', 'Female']) Output: 9. select: This is also called Drop-Down selection. By default, only one option can be selected at a time. You can also select multiple options by setting the “multiple” parameter to True. Syntax: select(“Some text”, options=[‘Option 1’, ‘Option 2’, ‘Option 3’, ‘Option 4’], multiple=True) Python3 select("Tech Stack", options=[ 'C Programming', 'Python', 'Web Development', 'Android Development']) Output: 10. textarea: This element is used to take multi-line input in a text input area. The row is an element defined inside the textarea which is used for a number of visible text lines. Syntax: textarea(“Some text”, rows=3) Python3 textarea("Comments/Questions", rows=3) Output: 11. checkbox: The Checkbox allows users to select/deselect multiple values, we have to provide the options so that the user can select any values. Syntax: checkbox(“Some text”, options=[‘Option 1’, ‘Option 2’, ‘Option 3’]) Python3 checkbox("Languages", options=['Hindi', 'English', 'French']) Output: 12. popup: The pop is used to produce output in a popup manner, multiple pops-ups can’t show at a time. Before displaying a new pop-up window, the existing popup on the page will be automatically closed or you can close manually. Syntax: popup(“Title”, “Text”) Python3 popup("Who are you?", "Geeks for Geeks") Output: Python3 # Import following modulesfrom pywebio.input import *from pywebio.output import *from pywebio.session import *import re # For checking Email, whether Valid or not.regex = '^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$' # For checking Phone Number, whether Valid or # not.Pattern = re.compile("(0/91)?[6-9][0-9]{9}") # For Checking URL, whether valid or notregex_1 = ("((http|https)://)(www.)?" + "[a-zA-Z0-9@:%._\\+~#?&//=]" + "{2,256}\\.[a-z]" + "{2,6}\\b([-a-zA-Z0-9@:%" + "._\\+~#?&//=]*)")Pattern_1 = re.compile(regex_1) def check_form(data): # for checking Name if data['name'].isdigit(): return ('name', 'Invalid name!') # for checking UserName if data['username'].isdigit(): return ('username', 'Invalid username!') # for checking Age if data['age'] <= 0: return ('age', 'Invalid age!') # for checking Email if not (re.search(regex, data['email'])): return ('email', 'Invalid email!') # for checking Phone Number if not (Pattern.match(str(data['phone']))) or len(str(data['phone'])) != 10: return ('phone', 'Invalid phone!') # for checking Website URL if not re.search(Pattern_1, data['website']): return ('website', 'Invalid URL!') # for matching Passwords if data['pass'] != data['passes']: return ('passes', "Please make sure your passwords match") # Taking input from the userdata = input_group("Fill out the form:", [ input('Username', name='username', type=TEXT, required=True, PlaceHolder="@username"), input('Password', name='pass', type=PASSWORD, required=True, PlaceHolder="Password"), input('Confirm Password', name='passes', type=PASSWORD, required=True, PlaceHolder="Confirm Password"), input('Name', name='name', type=TEXT, required=True, PlaceHolder="name"), input('Phone', name='phone', type=NUMBER, required=True, PlaceHolder="12345"), input('Email', name='email', type=TEXT, required=True, PlaceHolder="[email protected]"), input('Age', name='age', type=NUMBER, required=True, PlaceHolder="age"), input('Portfolio website', name='website', type=TEXT, required=True, PlaceHolder="www.XYZ.com") ], validate=check_form, cancelable=True) # Create a radio buttongender = radio("Gender", options=['Male', 'Female'], required=True) # Create a skills markdownskills = select("Tech Stack", options=[ 'C Programming', 'Python', 'Web Development', 'Android Development'], required=True) # Create a textareatext = textarea("Comments/Questions", rows=3, placeholder="Write something...", required=True) # Create a checkboxagree = checkbox("Agreement", options=[ 'I agree to terms and conditions'], required=True) # Display output using popuppopup("Your Details", f"Username: @{data['username']}\nName: {data['name']}\ \nPhone: {str(data['phone'])}\nEmail: {data['email']}\ \nAge: {str(data['age'])}\nWebsite: {data['website']}\ \nGender: {gender}\nSkill: {skills}\nComments: {text}", closable=True) Output: python-modules python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n06 Jun, 2021" }, { "code": null, "e": 25747, "s": 25537, "text": "In this article, we are going to create a registration form using the PyWebIO module. This is a Python module mostly used to create simple and interactive interfaces on the local web using Python Programming. " }, { "code": null, "e": 26152, "s": 25747, "text": "This form will take username, name, password, email, website link as input. Talking about passwords, it will also check your password again to confirm whether your password is correct or not. It will also validate your phone number, website link, email address. After that, you will get the radio button consisting of Gender, and you will also get the comment section so that you can write your feedback." }, { "code": null, "e": 26257, "s": 26152, "text": "To create a proper form with validations we will learn different form elements one by one with examples." }, { "code": null, "e": 26455, "s": 26257, "text": "1. input_group: This element is used to get the inputs in the group. When we use input_group, we need to provide the name parameter to each input function to identify the input items in the result." }, { "code": null, "e": 26557, "s": 26455, "text": "Syntax: input_group(“Title”, [input(‘Any name’, name=’Anything’),input(‘Any name’, name=’Anything’)])" }, { "code": null, "e": 26565, "s": 26557, "text": "Python3" }, { "code": "info = input_group(\"Group inputs\", [ input('Username', name='username'), input('Password', name='pass')])", "e": 26679, "s": 26565, "text": null }, { "code": null, "e": 26688, "s": 26679, "text": "Output: " }, { "code": null, "e": 26777, "s": 26688, "text": "2. input: This element is used to take all kinds of inputs of the user from the browser." }, { "code": null, "e": 26804, "s": 26777, "text": "Syntax: input(‘Some text’)" }, { "code": null, "e": 26812, "s": 26804, "text": "Python3" }, { "code": "input(\"Your name\")", "e": 26831, "s": 26812, "text": null }, { "code": null, "e": 26840, "s": 26831, "text": "Output: " }, { "code": null, "e": 27105, "s": 26840, "text": "3. type: This is defined inside the input function or input_group function. This depends on user choice whether the user wants a number in the input or a text in the input. If the type equals the number, it will only accept numbers and a similar case for the text." }, { "code": null, "e": 27114, "s": 27105, "text": "Syntax: " }, { "code": null, "e": 27144, "s": 27114, "text": "input(‘Some text’, type=TEXT)" }, { "code": null, "e": 27176, "s": 27144, "text": "input(‘Some text’, type=NUMBER)" }, { "code": null, "e": 27210, "s": 27176, "text": "input(‘Some text’, type=PASSWORD)" }, { "code": null, "e": 27218, "s": 27210, "text": "Python3" }, { "code": "input('Name', type=TEXT)input('PIN', type=NUMBER)input('Password', type=PASSWORD)", "e": 27300, "s": 27218, "text": null }, { "code": null, "e": 27309, "s": 27300, "text": "Output: " }, { "code": null, "e": 27502, "s": 27309, "text": "4. required: If required is true, that means you have to input something, we can’t leave blank, otherwise, it will through an error called “Please fill out this field”. By default, it’s false." }, { "code": null, "e": 27544, "s": 27502, "text": "Syntax: input(‘Some text’, required=True)" }, { "code": null, "e": 27552, "s": 27544, "text": "Python3" }, { "code": "input('Name', required=True)", "e": 27581, "s": 27552, "text": null }, { "code": null, "e": 27590, "s": 27581, "text": "Output: " }, { "code": null, "e": 27756, "s": 27590, "text": "5. validate: This element receives input as a parameter, when the input value is valid, it returns True, when the user input is invalid, it returns an error message." }, { "code": null, "e": 27802, "s": 27756, "text": "Syntax: input(‘Some text’, validate=is_valid)" }, { "code": null, "e": 27810, "s": 27802, "text": "Python3" }, { "code": "def is_valid(data): if data <= 0: return 'Age cannot be negative!' input('Age', type=NUMBER, validate=is_valid)", "e": 27933, "s": 27810, "text": null }, { "code": null, "e": 27942, "s": 27933, "text": "Output: " }, { "code": null, "e": 28092, "s": 27942, "text": "6. cancelable: Whether the form can be canceled. Default is False. If cancelable=True, a “Cancel” button will be displayed at the bottom of the form." }, { "code": null, "e": 28211, "s": 28092, "text": "Syntax: input_group(“Title”, [input(‘Any name’, name=’Anything’),input(‘Any name’, name=’Anything’)], cancelable=True)" }, { "code": null, "e": 28219, "s": 28211, "text": "Python3" }, { "code": "input_group(\"Info\", [input('Name', name='name'),input('PIN ', name='pin')], cancelable=True)", "e": 28312, "s": 28219, "text": null }, { "code": null, "e": 28321, "s": 28312, "text": "Output: " }, { "code": null, "e": 28432, "s": 28321, "text": "7. PlaceHolder: This element is used only in the input_group function, this is used to show a very light text." }, { "code": null, "e": 28484, "s": 28432, "text": "Syntax: input(‘Some text’, placeholder=”some text”)" }, { "code": null, "e": 28492, "s": 28484, "text": "Python3" }, { "code": "input('Name', placeholder=\"Please Enter your name\")", "e": 28544, "s": 28492, "text": null }, { "code": null, "e": 28553, "s": 28544, "text": "Output: " }, { "code": null, "e": 28685, "s": 28553, "text": "8. radio: The radio button is used when we have to choose only one option in the many options, i.e., only a single can be selected." }, { "code": null, "e": 28746, "s": 28685, "text": "Syntax: radio(“Some text”, options=[‘Option 1’, ‘Option 2’])" }, { "code": null, "e": 28754, "s": 28746, "text": "Python3" }, { "code": "radio(\"Gender\", options=['Male', 'Female'])", "e": 28798, "s": 28754, "text": null }, { "code": null, "e": 28807, "s": 28798, "text": "Output: " }, { "code": null, "e": 28997, "s": 28807, "text": "9. select: This is also called Drop-Down selection. By default, only one option can be selected at a time. You can also select multiple options by setting the “multiple” parameter to True." }, { "code": null, "e": 29098, "s": 28997, "text": "Syntax: select(“Some text”, options=[‘Option 1’, ‘Option 2’, ‘Option 3’, ‘Option 4’], multiple=True)" }, { "code": null, "e": 29106, "s": 29098, "text": "Python3" }, { "code": "select(\"Tech Stack\", options=[ 'C Programming', 'Python', 'Web Development', 'Android Development'])", "e": 29208, "s": 29106, "text": null }, { "code": null, "e": 29217, "s": 29208, "text": "Output: " }, { "code": null, "e": 29399, "s": 29217, "text": "10. textarea: This element is used to take multi-line input in a text input area. The row is an element defined inside the textarea which is used for a number of visible text lines." }, { "code": null, "e": 29437, "s": 29399, "text": "Syntax: textarea(“Some text”, rows=3)" }, { "code": null, "e": 29445, "s": 29437, "text": "Python3" }, { "code": "textarea(\"Comments/Questions\", rows=3)", "e": 29484, "s": 29445, "text": null }, { "code": null, "e": 29493, "s": 29484, "text": "Output: " }, { "code": null, "e": 29640, "s": 29493, "text": "11. checkbox: The Checkbox allows users to select/deselect multiple values, we have to provide the options so that the user can select any values." }, { "code": null, "e": 29717, "s": 29640, "text": "Syntax: checkbox(“Some text”, options=[‘Option 1’, ‘Option 2’, ‘Option 3’]) " }, { "code": null, "e": 29725, "s": 29717, "text": "Python3" }, { "code": "checkbox(\"Languages\", options=['Hindi', 'English', 'French'])", "e": 29787, "s": 29725, "text": null }, { "code": null, "e": 29796, "s": 29787, "text": "Output: " }, { "code": null, "e": 30026, "s": 29796, "text": "12. popup: The pop is used to produce output in a popup manner, multiple pops-ups can’t show at a time. Before displaying a new pop-up window, the existing popup on the page will be automatically closed or you can close manually." }, { "code": null, "e": 30057, "s": 30026, "text": "Syntax: popup(“Title”, “Text”)" }, { "code": null, "e": 30065, "s": 30057, "text": "Python3" }, { "code": "popup(\"Who are you?\", \"Geeks for Geeks\")", "e": 30106, "s": 30065, "text": null }, { "code": null, "e": 30115, "s": 30106, "text": "Output: " }, { "code": null, "e": 30123, "s": 30115, "text": "Python3" }, { "code": "# Import following modulesfrom pywebio.input import *from pywebio.output import *from pywebio.session import *import re # For checking Email, whether Valid or not.regex = '^(\\w|\\.|\\_|\\-)+[@](\\w|\\_|\\-|\\.)+[.]\\w{2,3}$' # For checking Phone Number, whether Valid or # not.Pattern = re.compile(\"(0/91)?[6-9][0-9]{9}\") # For Checking URL, whether valid or notregex_1 = (\"((http|https)://)(www.)?\" + \"[a-zA-Z0-9@:%._\\\\+~#?&//=]\" + \"{2,256}\\\\.[a-z]\" + \"{2,6}\\\\b([-a-zA-Z0-9@:%\" + \"._\\\\+~#?&//=]*)\")Pattern_1 = re.compile(regex_1) def check_form(data): # for checking Name if data['name'].isdigit(): return ('name', 'Invalid name!') # for checking UserName if data['username'].isdigit(): return ('username', 'Invalid username!') # for checking Age if data['age'] <= 0: return ('age', 'Invalid age!') # for checking Email if not (re.search(regex, data['email'])): return ('email', 'Invalid email!') # for checking Phone Number if not (Pattern.match(str(data['phone']))) or len(str(data['phone'])) != 10: return ('phone', 'Invalid phone!') # for checking Website URL if not re.search(Pattern_1, data['website']): return ('website', 'Invalid URL!') # for matching Passwords if data['pass'] != data['passes']: return ('passes', \"Please make sure your passwords match\") # Taking input from the userdata = input_group(\"Fill out the form:\", [ input('Username', name='username', type=TEXT, required=True, PlaceHolder=\"@username\"), input('Password', name='pass', type=PASSWORD, required=True, PlaceHolder=\"Password\"), input('Confirm Password', name='passes', type=PASSWORD, required=True, PlaceHolder=\"Confirm Password\"), input('Name', name='name', type=TEXT, required=True, PlaceHolder=\"name\"), input('Phone', name='phone', type=NUMBER, required=True, PlaceHolder=\"12345\"), input('Email', name='email', type=TEXT, required=True, PlaceHolder=\"[email protected]\"), input('Age', name='age', type=NUMBER, required=True, PlaceHolder=\"age\"), input('Portfolio website', name='website', type=TEXT, required=True, PlaceHolder=\"www.XYZ.com\") ], validate=check_form, cancelable=True) # Create a radio buttongender = radio(\"Gender\", options=['Male', 'Female'], required=True) # Create a skills markdownskills = select(\"Tech Stack\", options=[ 'C Programming', 'Python', 'Web Development', 'Android Development'], required=True) # Create a textareatext = textarea(\"Comments/Questions\", rows=3, placeholder=\"Write something...\", required=True) # Create a checkboxagree = checkbox(\"Agreement\", options=[ 'I agree to terms and conditions'], required=True) # Display output using popuppopup(\"Your Details\", f\"Username: @{data['username']}\\nName: {data['name']}\\ \\nPhone: {str(data['phone'])}\\nEmail: {data['email']}\\ \\nAge: {str(data['age'])}\\nWebsite: {data['website']}\\ \\nGender: {gender}\\nSkill: {skills}\\nComments: {text}\", closable=True)", "e": 33314, "s": 30123, "text": null }, { "code": null, "e": 33323, "s": 33314, "text": "Output: " }, { "code": null, "e": 33338, "s": 33323, "text": "python-modules" }, { "code": null, "e": 33353, "s": 33338, "text": "python-utility" }, { "code": null, "e": 33360, "s": 33353, "text": "Python" }, { "code": null, "e": 33458, "s": 33360, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33490, "s": 33458, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 33532, "s": 33490, "text": "Check if element exists in list in Python" }, { "code": null, "e": 33574, "s": 33532, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 33630, "s": 33574, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 33657, "s": 33630, "text": "Python Classes and Objects" }, { "code": null, "e": 33696, "s": 33657, "text": "Python | Get unique values from a list" }, { "code": null, "e": 33727, "s": 33696, "text": "Python | os.path.join() method" }, { "code": null, "e": 33749, "s": 33727, "text": "Defaultdict in Python" }, { "code": null, "e": 33778, "s": 33749, "text": "Create a directory in Python" } ]
Sum of the series 1^1 + 2^2 + 3^3 + ..... + n^n using recursion - GeeksforGeeks
17 Mar, 2021 Given an integer n, the task is to find the sum of the series 11 + 22 + 33 + ..... + nn using recursion.Examples: Input: n = 2 Output: 5 11 + 22 = 1 + 4 = 5 Input: n = 3 Output: 32 11 + 22 + 33 = 1 + 4 + 27 = 32 Approach: Starting from n, start adding all the terms of the series one by one with the value of n getting decremented by 1 in each recursive call until the value of n = 1 for which return 1 as 11 = 1.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define ll long long int // Recursive function to return// the sum of the given seriesll sum(int n){ // 1^1 = 1 if (n == 1) return 1; else // Recursive call return ((ll)pow(n, n) + sum(n - 1));} // Driver codeint main(){ int n = 2; cout << sum(n); return 0;} // Java implementation of the approachclass GFG { // Recursive function to return // the sum of the given series static long sum(int n) { // 1^1 = 1 if (n == 1) return 1; else // Recursive call return ((long)Math.pow(n, n) + sum(n - 1)); } // Driver code public static void main(String args[]) { int n = 2; System.out.println(sum(n)); }} # Python3 implementation of the approach # Recursive function to return# the sum of the given seriesdef sum(n): if n == 1: return 1 else: # Recursive call return pow(n, n) + sum(n - 1) # Driver coden = 2print(sum(n)) # This code is contributed# by Shrikant13 // C# implementation of the approachusing System;class GFG { // Recursive function to return // the sum of the given series static long sum(int n) { // 1^1 = 1 if (n == 1) return 1; else // Recursive call return ((long)Math.Pow(n, n) + sum(n - 1)); } // Driver code public static void Main() { int n = 2; Console.Write(sum(n)); }} <?php// PHP implementation of the approach // Recursive function to return// the sum of the given seriesfunction sum($n){ // 1^1 = 1 if ($n == 1) return 1; else // Recursive call return (pow($n, $n) + sum($n - 1));} // Driver code$n = 2;echo(sum($n)); // This code is contributed// by Code_Mech?> <script> // Javascript implementation of the approach // Recursive function to return// the sum of the given seriesfunction sum(n){ // 1^1 = 1 if (n == 1) return 1; else // Recursive call return (Math.pow(n, n) + sum(n - 1));} // Driver codevar n = 2;document.write(sum(n)); // This code is contributed by rutvik_56.</script> 5 shrikanth13 Code_Mech rutvik_56 maths-power series-sum Mathematical Recursion Mathematical Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Print all possible combinations of r elements in a given array of size n Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Program for Tower of Hanoi Backtracking | Introduction Print all possible combinations of r elements in a given array of size n Program for Sum of the digits of a given number
[ { "code": null, "e": 26281, "s": 26253, "text": "\n17 Mar, 2021" }, { "code": null, "e": 26397, "s": 26281, "text": "Given an integer n, the task is to find the sum of the series 11 + 22 + 33 + ..... + nn using recursion.Examples: " }, { "code": null, "e": 26497, "s": 26397, "text": "Input: n = 2 Output: 5 11 + 22 = 1 + 4 = 5 Input: n = 3 Output: 32 11 + 22 + 33 = 1 + 4 + 27 = 32 " }, { "code": null, "e": 26752, "s": 26499, "text": "Approach: Starting from n, start adding all the terms of the series one by one with the value of n getting decremented by 1 in each recursive call until the value of n = 1 for which return 1 as 11 = 1.Below is the implementation of the above approach: " }, { "code": null, "e": 26756, "s": 26752, "text": "C++" }, { "code": null, "e": 26761, "s": 26756, "text": "Java" }, { "code": null, "e": 26769, "s": 26761, "text": "Python3" }, { "code": null, "e": 26772, "s": 26769, "text": "C#" }, { "code": null, "e": 26776, "s": 26772, "text": "PHP" }, { "code": null, "e": 26787, "s": 26776, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define ll long long int // Recursive function to return// the sum of the given seriesll sum(int n){ // 1^1 = 1 if (n == 1) return 1; else // Recursive call return ((ll)pow(n, n) + sum(n - 1));} // Driver codeint main(){ int n = 2; cout << sum(n); return 0;}", "e": 27169, "s": 26787, "text": null }, { "code": "// Java implementation of the approachclass GFG { // Recursive function to return // the sum of the given series static long sum(int n) { // 1^1 = 1 if (n == 1) return 1; else // Recursive call return ((long)Math.pow(n, n) + sum(n - 1)); } // Driver code public static void main(String args[]) { int n = 2; System.out.println(sum(n)); }}", "e": 27606, "s": 27169, "text": null }, { "code": "# Python3 implementation of the approach # Recursive function to return# the sum of the given seriesdef sum(n): if n == 1: return 1 else: # Recursive call return pow(n, n) + sum(n - 1) # Driver coden = 2print(sum(n)) # This code is contributed# by Shrikant13", "e": 27893, "s": 27606, "text": null }, { "code": "// C# implementation of the approachusing System;class GFG { // Recursive function to return // the sum of the given series static long sum(int n) { // 1^1 = 1 if (n == 1) return 1; else // Recursive call return ((long)Math.Pow(n, n) + sum(n - 1)); } // Driver code public static void Main() { int n = 2; Console.Write(sum(n)); }}", "e": 28322, "s": 27893, "text": null }, { "code": "<?php// PHP implementation of the approach // Recursive function to return// the sum of the given seriesfunction sum($n){ // 1^1 = 1 if ($n == 1) return 1; else // Recursive call return (pow($n, $n) + sum($n - 1));} // Driver code$n = 2;echo(sum($n)); // This code is contributed// by Code_Mech?>", "e": 28651, "s": 28322, "text": null }, { "code": "<script> // Javascript implementation of the approach // Recursive function to return// the sum of the given seriesfunction sum(n){ // 1^1 = 1 if (n == 1) return 1; else // Recursive call return (Math.pow(n, n) + sum(n - 1));} // Driver codevar n = 2;document.write(sum(n)); // This code is contributed by rutvik_56.</script>", "e": 29010, "s": 28651, "text": null }, { "code": null, "e": 29012, "s": 29010, "text": "5" }, { "code": null, "e": 29026, "s": 29014, "text": "shrikanth13" }, { "code": null, "e": 29036, "s": 29026, "text": "Code_Mech" }, { "code": null, "e": 29046, "s": 29036, "text": "rutvik_56" }, { "code": null, "e": 29058, "s": 29046, "text": "maths-power" }, { "code": null, "e": 29069, "s": 29058, "text": "series-sum" }, { "code": null, "e": 29082, "s": 29069, "text": "Mathematical" }, { "code": null, "e": 29092, "s": 29082, "text": "Recursion" }, { "code": null, "e": 29105, "s": 29092, "text": "Mathematical" }, { "code": null, "e": 29115, "s": 29105, "text": "Recursion" }, { "code": null, "e": 29213, "s": 29115, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29237, "s": 29213, "text": "Merge two sorted arrays" }, { "code": null, "e": 29280, "s": 29237, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 29294, "s": 29280, "text": "Prime Numbers" }, { "code": null, "e": 29336, "s": 29294, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 29409, "s": 29336, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 29494, "s": 29409, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 29521, "s": 29494, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 29549, "s": 29521, "text": "Backtracking | Introduction" }, { "code": null, "e": 29622, "s": 29549, "text": "Print all possible combinations of r elements in a given array of size n" } ]
C# Program to find whether a no is power of two - GeeksforGeeks
19 Jul, 2021 Given a positive integer, write a function to find if it is a power of two or not.Examples : Input : n = 4 Output : Yes 22 = 4 Input : n = 7 Output : No Input : n = 32 Output : Yes 25 = 32 1. A simple method for this is to simply take the log of the number on base 2 and if you get an integer then number is power of 2. // C# Program to find whether// a no is power of twousing System; class GFG { /* Function to check if x is power of 2*/ static bool isPowerOfTwo(int n) { return (int)(Math.Ceiling((Math.Log(n) / Math.Log(2)))) == (int)(Math.Floor(((Math.Log(n) / Math.Log(2))))); } // Driver Code public static void Main() { if (isPowerOfTwo(31)) Console.WriteLine("Yes"); else Console.WriteLine("No"); if (isPowerOfTwo(64)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed// by Akanksha Rai(Abby_akku) No Yes Time Complexity: O(log2n) Auxiliary Space: O(1) 2. Another solution is to keep dividing the number by two, i.e, do n = n/2 iteratively. In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2. // C# program to find whether// a no is power of twousing System; class GFG { // Function to check if // x is power of 2 static bool isPowerOfTwo(int n) { if (n == 0) return false; while (n != 1) { if (n % 2 != 0) return false; n = n / 2; } return true; } // Driver program public static void Main() { Console.WriteLine(isPowerOfTwo(31) ? "Yes" : "No"); Console.WriteLine(isPowerOfTwo(64) ? "Yes" : "No"); }} // This code is contributed by Sam007 No Yes 3. All power of two numbers have only one bit set. So count the no. of set bits and if you get 1 then number is a power of 2. Please see Count set bits in an integer for counting set bits.4. If we subtract a power of 2 numbers by 1 then all unset bits after the only set bit become set; and the set bit become unset.For example for 4 ( 100) and 16(10000), we get following after subtracting 1 3 –> 011 15 –> 01111So, if a number n is a power of 2 then bitwise & of n and n-1 will be zero. We can say n is a power of 2 or not based on value of n&(n-1). The expression n&(n-1) will not work when n is 0. To handle this case also, our expression will become n& (!n&(n-1)) (thanks to https://www.geeksforgeeks.org/program-to-find-whether-a-no-is-power-of-two/Mohammad for adding this case). Below is the implementation of this method. // C# program to efficiently// check for power for 2using System; class GFG { // Method to check if x is power of 2 static bool isPowerOfTwo(int x) { // First x in the below expression // is for the case when x is 0 return x != 0 && ((x & (x - 1)) == 0); } // Driver method public static void Main() { Console.WriteLine(isPowerOfTwo(31) ? "Yes" : "No"); Console.WriteLine(isPowerOfTwo(64) ? "Yes" : "No"); }} // This code is contributed by Sam007 No Yes Please refer complete article on Program to find whether a no is power of two for more details! souravmahato348 C# Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Program to Demonstrate the IList Interface How to Remove Duplicate Values From an Array in C#? Different Ways to Take Input and Print a Float Value in C# How to Convert ASCII Char to Byte in C#? C# Program to Check a Specified Type is an Enum or Not C# Program to Convert a Binary String to an Integer Hash Function for String data in C# C# Program to Sort a List of Integers Using the LINQ OrderBy() Method C# Program to Read and Write a Byte Array to File using FileStream Class How to Get a Total Number of Days in a Month using built in Functions in C#?
[ { "code": null, "e": 26579, "s": 26551, "text": "\n19 Jul, 2021" }, { "code": null, "e": 26674, "s": 26579, "text": "Given a positive integer, write a function to find if it is a power of two or not.Examples : " }, { "code": null, "e": 26772, "s": 26674, "text": "Input : n = 4\nOutput : Yes\n22 = 4\n\nInput : n = 7\nOutput : No\n\nInput : n = 32\nOutput : Yes\n25 = 32" }, { "code": null, "e": 26905, "s": 26772, "text": "1. A simple method for this is to simply take the log of the number on base 2 and if you get an integer then number is power of 2. " }, { "code": "// C# Program to find whether// a no is power of twousing System; class GFG { /* Function to check if x is power of 2*/ static bool isPowerOfTwo(int n) { return (int)(Math.Ceiling((Math.Log(n) / Math.Log(2)))) == (int)(Math.Floor(((Math.Log(n) / Math.Log(2))))); } // Driver Code public static void Main() { if (isPowerOfTwo(31)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); if (isPowerOfTwo(64)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 27550, "s": 26905, "text": null }, { "code": null, "e": 27557, "s": 27550, "text": "No\nYes" }, { "code": null, "e": 27585, "s": 27559, "text": "Time Complexity: O(log2n)" }, { "code": null, "e": 27607, "s": 27585, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 27821, "s": 27607, "text": "2. Another solution is to keep dividing the number by two, i.e, do n = n/2 iteratively. In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2. " }, { "code": "// C# program to find whether// a no is power of twousing System; class GFG { // Function to check if // x is power of 2 static bool isPowerOfTwo(int n) { if (n == 0) return false; while (n != 1) { if (n % 2 != 0) return false; n = n / 2; } return true; } // Driver program public static void Main() { Console.WriteLine(isPowerOfTwo(31) ? \"Yes\" : \"No\"); Console.WriteLine(isPowerOfTwo(64) ? \"Yes\" : \"No\"); }} // This code is contributed by Sam007", "e": 28389, "s": 27821, "text": null }, { "code": null, "e": 28396, "s": 28389, "text": "No\nYes" }, { "code": null, "e": 29231, "s": 28398, "text": "3. All power of two numbers have only one bit set. So count the no. of set bits and if you get 1 then number is a power of 2. Please see Count set bits in an integer for counting set bits.4. If we subtract a power of 2 numbers by 1 then all unset bits after the only set bit become set; and the set bit become unset.For example for 4 ( 100) and 16(10000), we get following after subtracting 1 3 –> 011 15 –> 01111So, if a number n is a power of 2 then bitwise & of n and n-1 will be zero. We can say n is a power of 2 or not based on value of n&(n-1). The expression n&(n-1) will not work when n is 0. To handle this case also, our expression will become n& (!n&(n-1)) (thanks to https://www.geeksforgeeks.org/program-to-find-whether-a-no-is-power-of-two/Mohammad for adding this case). Below is the implementation of this method. " }, { "code": "// C# program to efficiently// check for power for 2using System; class GFG { // Method to check if x is power of 2 static bool isPowerOfTwo(int x) { // First x in the below expression // is for the case when x is 0 return x != 0 && ((x & (x - 1)) == 0); } // Driver method public static void Main() { Console.WriteLine(isPowerOfTwo(31) ? \"Yes\" : \"No\"); Console.WriteLine(isPowerOfTwo(64) ? \"Yes\" : \"No\"); }} // This code is contributed by Sam007", "e": 29738, "s": 29231, "text": null }, { "code": null, "e": 29745, "s": 29738, "text": "No\nYes" }, { "code": null, "e": 29844, "s": 29747, "text": "Please refer complete article on Program to find whether a no is power of two for more details! " }, { "code": null, "e": 29860, "s": 29844, "text": "souravmahato348" }, { "code": null, "e": 29872, "s": 29860, "text": "C# Programs" }, { "code": null, "e": 29970, "s": 29872, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30016, "s": 29970, "text": "C# Program to Demonstrate the IList Interface" }, { "code": null, "e": 30068, "s": 30016, "text": "How to Remove Duplicate Values From an Array in C#?" }, { "code": null, "e": 30127, "s": 30068, "text": "Different Ways to Take Input and Print a Float Value in C#" }, { "code": null, "e": 30168, "s": 30127, "text": "How to Convert ASCII Char to Byte in C#?" }, { "code": null, "e": 30223, "s": 30168, "text": "C# Program to Check a Specified Type is an Enum or Not" }, { "code": null, "e": 30275, "s": 30223, "text": "C# Program to Convert a Binary String to an Integer" }, { "code": null, "e": 30311, "s": 30275, "text": "Hash Function for String data in C#" }, { "code": null, "e": 30381, "s": 30311, "text": "C# Program to Sort a List of Integers Using the LINQ OrderBy() Method" }, { "code": null, "e": 30454, "s": 30381, "text": "C# Program to Read and Write a Byte Array to File using FileStream Class" } ]
Spacing in Bootstrap with Examples - GeeksforGeeks
28 Sep, 2021 Bootstrap has many facility of classes to easily style elements in HTML. It includes various responsive padding and margin classes for modification of the appearance of element. Spacing utilities have no breakpoints symbols to apply to the breakpoints.Following Syntax are used in the Various Classes for adding spacing: (property)(sides)-(size) for xs (property)(sides)-(breakpoint)-(size) for sm, md, lg, and xl. Property: There are two ways of adding spacing to the elements. m: This property defines the margin. Margin provides an edge or border. p: This property defines the padding. Padding properties are used to generate space around the content. Sides: This allows users to add spacing in content to a specific side wherever required. t : margin-top/padding-top. b : margin-bottom/padding-bottom. l : margin-left/padding-left. r : margin-right/padding-right. x : for padding-left and padding-right/margin-left and margin-right. y : for padding-top and padding-bottom/margin-top and margin-bottom. blank : margin/padding on all sides of the element. Size: This allows users to add a specific amount of spacing to a level. 0 – 0px margin/padding. 1 – 4px margin/padding. 2 – 8px margin/padding. 3 – 16px margin/padding. 4 – 24px margin/padding. 5 – 48px margin/padding. auto – auto margin. Breakpoint: Breakpoints are points where the website content can adjust according to the device and allow to show the best layout to the user. sm, md, lg, and xl are the following breakpoints. Syntax: For breakpoint – xs: <div class="mt-4"> For breakpoint – md: <div class="mt-md-4"> For breakpoint – lg: <div class="mt-lg-4"> For breakpoint – xl: <div class="mt-xl-4"> Responsive Spacing Table: Example 1: HTML <!DOCTYPE html><html> <head> <!-- Link Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <!-- Link Bootstrap Js and Jquery --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script> <title> GeeksForGeeks Bootstrap Spacing Example </title> </head> <body> <br> <tab> <h3>Padding And Margin</h3> <div class="container text-white"> <br><br> <div class="pt-5 bg-success"> GeeksForGeeks </div> <br> <div class="p-4 bg-success"> GeeksForGeeks </div> <div class="m-4 pb-5 bg-success"> GeeksForGeeks </div> </div> </body></html> Output: Example 2: HTML <!DOCTYPE html><html><head> <!-- Link bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <!-- Link bootstrap JS and Jquery --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script> <title> GeeksforGeeks Bootstrap Spacing Example </title></head> <body> <div class="container"><br> <h4 style="color:green;"> GeeksforGeeks is a regularly spaced. </h4> <h4 class="ml-5 ml-lg-0"style="color:green;"> GFG Geeks1 has left margin visible on xs, sm and md displays. </h4> </div> </body></html> Output: Example 3: HTML <!DOCTYPE html><html><head> <!-- Link Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <!-- Link Bootstrap JS and Jquery --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script> <title> GeeksForGeeks Bootstrap Spacing Example </title></head> <body> <div class="container"><br> <div class="mx-auto" style="width:300px; background-color:green;"> <h3 style="color:white;">GeeksForGeeks</h3> </div> </div></body></html> Output: Supported Browser: Google Chrome Internet Explorer Firefox Opera Safari ysachin2314 sweetyty Picked Web-Programs Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to change navigation bar color in Bootstrap ? Form validation using jQuery How to pass data into a bootstrap modal? How to align navbar items to the right in Bootstrap 4 ? How to Show Images on Click using HTML ? 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": 25395, "s": 25367, "text": "\n28 Sep, 2021" }, { "code": null, "e": 25717, "s": 25395, "text": "Bootstrap has many facility of classes to easily style elements in HTML. It includes various responsive padding and margin classes for modification of the appearance of element. Spacing utilities have no breakpoints symbols to apply to the breakpoints.Following Syntax are used in the Various Classes for adding spacing: " }, { "code": null, "e": 25749, "s": 25717, "text": "(property)(sides)-(size) for xs" }, { "code": null, "e": 25811, "s": 25749, "text": "(property)(sides)-(breakpoint)-(size) for sm, md, lg, and xl." }, { "code": null, "e": 25875, "s": 25811, "text": "Property: There are two ways of adding spacing to the elements." }, { "code": null, "e": 25947, "s": 25875, "text": "m: This property defines the margin. Margin provides an edge or border." }, { "code": null, "e": 26051, "s": 25947, "text": "p: This property defines the padding. Padding properties are used to generate space around the content." }, { "code": null, "e": 26140, "s": 26051, "text": "Sides: This allows users to add spacing in content to a specific side wherever required." }, { "code": null, "e": 26168, "s": 26140, "text": "t : margin-top/padding-top." }, { "code": null, "e": 26202, "s": 26168, "text": "b : margin-bottom/padding-bottom." }, { "code": null, "e": 26232, "s": 26202, "text": "l : margin-left/padding-left." }, { "code": null, "e": 26264, "s": 26232, "text": "r : margin-right/padding-right." }, { "code": null, "e": 26333, "s": 26264, "text": "x : for padding-left and padding-right/margin-left and margin-right." }, { "code": null, "e": 26402, "s": 26333, "text": "y : for padding-top and padding-bottom/margin-top and margin-bottom." }, { "code": null, "e": 26454, "s": 26402, "text": "blank : margin/padding on all sides of the element." }, { "code": null, "e": 26527, "s": 26454, "text": "Size: This allows users to add a specific amount of spacing to a level. " }, { "code": null, "e": 26551, "s": 26527, "text": "0 – 0px margin/padding." }, { "code": null, "e": 26575, "s": 26551, "text": "1 – 4px margin/padding." }, { "code": null, "e": 26599, "s": 26575, "text": "2 – 8px margin/padding." }, { "code": null, "e": 26624, "s": 26599, "text": "3 – 16px margin/padding." }, { "code": null, "e": 26649, "s": 26624, "text": "4 – 24px margin/padding." }, { "code": null, "e": 26674, "s": 26649, "text": "5 – 48px margin/padding." }, { "code": null, "e": 26694, "s": 26674, "text": "auto – auto margin." }, { "code": null, "e": 26839, "s": 26694, "text": "Breakpoint: Breakpoints are points where the website content can adjust according to the device and allow to show the best layout to the user. " }, { "code": null, "e": 26889, "s": 26839, "text": "sm, md, lg, and xl are the following breakpoints." }, { "code": null, "e": 26898, "s": 26889, "text": "Syntax: " }, { "code": null, "e": 26919, "s": 26898, "text": "For breakpoint – xs:" }, { "code": null, "e": 26938, "s": 26919, "text": "<div class=\"mt-4\">" }, { "code": null, "e": 26959, "s": 26938, "text": "For breakpoint – md:" }, { "code": null, "e": 26981, "s": 26959, "text": "<div class=\"mt-md-4\">" }, { "code": null, "e": 27002, "s": 26981, "text": "For breakpoint – lg:" }, { "code": null, "e": 27024, "s": 27002, "text": "<div class=\"mt-lg-4\">" }, { "code": null, "e": 27045, "s": 27024, "text": "For breakpoint – xl:" }, { "code": null, "e": 27067, "s": 27045, "text": "<div class=\"mt-xl-4\">" }, { "code": null, "e": 27094, "s": 27067, "text": "Responsive Spacing Table: " }, { "code": null, "e": 27106, "s": 27094, "text": "Example 1: " }, { "code": null, "e": 27111, "s": 27106, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- Link Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\"> <!-- Link Bootstrap Js and Jquery --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\"></script> <title> GeeksForGeeks Bootstrap Spacing Example </title> </head> <body> <br> <tab> <h3>Padding And Margin</h3> <div class=\"container text-white\"> <br><br> <div class=\"pt-5 bg-success\"> GeeksForGeeks </div> <br> <div class=\"p-4 bg-success\"> GeeksForGeeks </div> <div class=\"m-4 pb-5 bg-success\"> GeeksForGeeks </div> </div> </body></html>", "e": 28229, "s": 27111, "text": null }, { "code": null, "e": 28238, "s": 28229, "text": "Output: " }, { "code": null, "e": 28250, "s": 28238, "text": "Example 2: " }, { "code": null, "e": 28255, "s": 28250, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <!-- Link bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\"> <!-- Link bootstrap JS and Jquery --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\"></script> <title> GeeksforGeeks Bootstrap Spacing Example </title></head> <body> <div class=\"container\"><br> <h4 style=\"color:green;\"> GeeksforGeeks is a regularly spaced. </h4> <h4 class=\"ml-5 ml-lg-0\"style=\"color:green;\"> GFG Geeks1 has left margin visible on xs, sm and md displays. </h4> </div> </body></html> ", "e": 29180, "s": 28255, "text": null }, { "code": null, "e": 29189, "s": 29180, "text": "Output: " }, { "code": null, "e": 29201, "s": 29189, "text": "Example 3: " }, { "code": null, "e": 29206, "s": 29201, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <!-- Link Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\"> <!-- Link Bootstrap JS and Jquery --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\"></script> <title> GeeksForGeeks Bootstrap Spacing Example </title></head> <body> <div class=\"container\"><br> <div class=\"mx-auto\" style=\"width:300px; background-color:green;\"> <h3 style=\"color:white;\">GeeksForGeeks</h3> </div> </div></body></html> ", "e": 30022, "s": 29206, "text": null }, { "code": null, "e": 30030, "s": 30022, "text": "Output:" }, { "code": null, "e": 30049, "s": 30030, "text": "Supported Browser:" }, { "code": null, "e": 30063, "s": 30049, "text": "Google Chrome" }, { "code": null, "e": 30081, "s": 30063, "text": "Internet Explorer" }, { "code": null, "e": 30089, "s": 30081, "text": "Firefox" }, { "code": null, "e": 30095, "s": 30089, "text": "Opera" }, { "code": null, "e": 30102, "s": 30095, "text": "Safari" }, { "code": null, "e": 30114, "s": 30102, "text": "ysachin2314" }, { "code": null, "e": 30123, "s": 30114, "text": "sweetyty" }, { "code": null, "e": 30130, "s": 30123, "text": "Picked" }, { "code": null, "e": 30143, "s": 30130, "text": "Web-Programs" }, { "code": null, "e": 30153, "s": 30143, "text": "Bootstrap" }, { "code": null, "e": 30170, "s": 30153, "text": "Web Technologies" }, { "code": null, "e": 30268, "s": 30170, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30318, "s": 30268, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 30347, "s": 30318, "text": "Form validation using jQuery" }, { "code": null, "e": 30388, "s": 30347, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 30444, "s": 30388, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 30485, "s": 30444, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 30525, "s": 30485, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30558, "s": 30525, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30603, "s": 30558, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30646, "s": 30603, "text": "How to fetch data from an API in ReactJS ?" } ]
How to set the color of TextView span in Android using Kotlin?
This example demonstrates how to set the color of TextView span in Android using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:text="Tutorials Point" android:textAlignment="center" android:textColor="@android:color/holo_green_dark" android:textSize="32sp" android:textStyle="bold" /> <TextView android:textAlignment="center" android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textSize="24sp" android:textStyle="bold|italic" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import android.graphics.Color import android.os.Bundle import android.text.SpannableString import android.text.Spanned import android.text.style.ForegroundColorSpan import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { lateinit var textView:TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" textView = findViewById(R.id.textView) val text = "I appreciate the prayer but I've already got God on my side" val spannableString = SpannableString(text) val foregroundColorSpanCyan = ForegroundColorSpan(Color.MAGENTA) val foregroundColorSpanBlue = ForegroundColorSpan(Color.RED) val foregroundColorSpanGreen = ForegroundColorSpan(Color.GREEN) spannableString.setSpan(foregroundColorSpanCyan, 3, 15, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) spannableString.setSpan(foregroundColorSpanBlue, 22, 31, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) spannableString.setSpan(foregroundColorSpanGreen, 38, 49, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) textView.text = spannableString } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
[ { "code": null, "e": 1151, "s": 1062, "text": "This example demonstrates how to set the color of TextView span in Android using Kotlin." }, { "code": null, "e": 1280, "s": 1151, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1345, "s": 1280, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2298, "s": 1345, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:text=\"Tutorials Point\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"32sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:textAlignment=\"center\"\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold|italic\" />\n</RelativeLayout>" }, { "code": null, "e": 2353, "s": 2298, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 3578, "s": 2353, "text": "import android.graphics.Color\nimport android.os.Bundle\nimport android.text.SpannableString\nimport android.text.Spanned\nimport android.text.style.ForegroundColorSpan\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var textView:TextView\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n textView = findViewById(R.id.textView)\n val text = \"I appreciate the prayer but I've already got God on my side\"\n val spannableString = SpannableString(text)\n val foregroundColorSpanCyan = ForegroundColorSpan(Color.MAGENTA)\n val foregroundColorSpanBlue = ForegroundColorSpan(Color.RED)\n val foregroundColorSpanGreen = ForegroundColorSpan(Color.GREEN)\n spannableString.setSpan(foregroundColorSpanCyan, 3, 15,\n Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)\n spannableString.setSpan(foregroundColorSpanBlue, 22, 31,\n Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)\n spannableString.setSpan(foregroundColorSpanGreen, 38, 49,\n Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)\n textView.text = spannableString\n }\n}" }, { "code": null, "e": 3633, "s": 3578, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4300, "s": 3633, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4648, "s": 4300, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen" } ]
How to navigate back to current page from Frame in selenium webdriver?
We can navigate back to the current page from frame with Selenium webdriver. A frame is defined with <iframe>, <frame> or <frameset> tag in html code. A frame is used to embed an HTML document within another HTML document. Selenium by default has access to the main browser driver. In order to access a frame element, the driver focus has to shift from the main browser window to the frame. To again focus back to the current page from frame, the method switchTo().defaultContent() is used. Code Implementation. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class SwitchBackFrame{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://the-internet.herokuapp.com/frames"); driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS); // identify element and click driver.findElement(By.partialLinkText("Nested")).click(); // switching to frame with frame name driver.switchTo().frame("frame-bottom"); WebElement m = driver.findElement(By.cssSelector("body")); System.out.println("Frame text: " +m.getText()); // switch from frame to main page driver.switchTo().defaultContent(); driver.close(); } }
[ { "code": null, "e": 1285, "s": 1062, "text": "We can navigate back to the current page from frame with Selenium webdriver. A frame is defined with <iframe>, <frame> or <frameset> tag in html code. A frame is used to embed an HTML document within another HTML document." }, { "code": null, "e": 1553, "s": 1285, "text": "Selenium by default has access to the main browser driver. In order to access a frame element, the driver focus has to shift from the main browser window to the frame. To again focus back to the current page from frame, the method switchTo().defaultContent() is used." }, { "code": null, "e": 1574, "s": 1553, "text": "Code Implementation." }, { "code": null, "e": 2550, "s": 1574, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class SwitchBackFrame{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://the-internet.herokuapp.com/frames\");\n driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);\n // identify element and click\n driver.findElement(By.partialLinkText(\"Nested\")).click();\n // switching to frame with frame name\n driver.switchTo().frame(\"frame-bottom\");\n WebElement m = driver.findElement(By.cssSelector(\"body\"));\n System.out.println(\"Frame text: \" +m.getText());\n // switch from frame to main page\n driver.switchTo().defaultContent();\n driver.close();\n }\n}" } ]
Scope resolution operator in C++
The :: (scope resolution) operator is used to get hidden names due to variable scopes so that you can still use them. The scope resolution operator can be used as both unary and binary. You can use the unary scope operator if a namespace scope or global scope name is hidden by a particular declaration of an equivalent name during a block or class. For example, if you have a global variable of name my_var and a local variable of name my_var, to access global my_var, you'll need to use the scope resolution operator. #include <iostream> using namespace std; int my_var = 0; int main(void) { int my_var = 0; ::my_var = 1; // set global my_var to 1 my_var = 2; // set local my_var to 2 cout << ::my_var << ", " << my_var; return 0; } This will give the output − 1, 2 The declaration of my_var declared in the main function hides the integer named my_var declared in global namespace scope. The statement ::my_var = 1 accesses the variable named my_var declared in global namespace scope. You can also use the scope resolution operator to use class names or class member names. If a class member name is hidden, you can use it by prefixing it with its class name and the class scope operator. For example, #include <iostream> using namespace std; class X { public: static int count; }; int X::count = 10; // define static data member int main () { int X = 0; // hides class type X cout << X::count << endl; // use static member of class X } This will give the output − 10
[ { "code": null, "e": 1582, "s": 1062, "text": "The :: (scope resolution) operator is used to get hidden names due to variable scopes so that you can still use them. The scope resolution operator can be used as both unary and binary. You can use the unary scope operator if a namespace scope or global scope name is hidden by a particular declaration of an equivalent name during a block or class. For example, if you have a global variable of name my_var and a local variable of name my_var, to access global my_var, you'll need to use the scope resolution operator." }, { "code": null, "e": 1821, "s": 1582, "text": "#include <iostream> \nusing namespace std; \n\nint my_var = 0;\nint main(void) {\n int my_var = 0;\n ::my_var = 1; // set global my_var to 1\n my_var = 2; // set local my_var to 2\n cout << ::my_var << \", \" << my_var;\n return 0;\n}" }, { "code": null, "e": 1849, "s": 1821, "text": "This will give the output −" }, { "code": null, "e": 1854, "s": 1849, "text": "1, 2" }, { "code": null, "e": 2075, "s": 1854, "text": "The declaration of my_var declared in the main function hides the integer named my_var declared in global namespace scope. The statement ::my_var = 1 accesses the variable named my_var declared in global namespace scope." }, { "code": null, "e": 2292, "s": 2075, "text": "You can also use the scope resolution operator to use class names or class member names. If a class member name is hidden, you can use it by prefixing it with its class name and the class scope operator. For example," }, { "code": null, "e": 2545, "s": 2292, "text": "#include <iostream>\nusing namespace std;\nclass X {\n public:\n static int count;\n};\nint X::count = 10; // define static data member\n\nint main () {\n int X = 0; // hides class type X\n cout << X::count << endl; // use static member of class X\n}" }, { "code": null, "e": 2573, "s": 2545, "text": "This will give the output −" }, { "code": null, "e": 2576, "s": 2573, "text": "10" } ]
Python | Use of __slots__ - GeeksforGeeks
27 Dec, 2019 When we create objects for classes, it requires memory and the attribute are stored in the form of a dictionary. In case if we need to allocate thousands of objects, it will take a lot of memory space.slots provide a special mechanism to reduce the size of objects.It is a concept of memory optimisation on objects. Example of python object without slots : class GFG(object): def __init__(self, *args, **kwargs): self.a = 1 self.b = 2 if __name__ == "__main__": instance = GFG() print(instance.__dict__) Output : {'a': 1, 'b': 2} As every object in Python contains a dynamic dictionary that allows adding attributes. For every instance object, we will have an instance of a dictionary that consumes more space and wastes a lot of RAM. In Python, there is no default functionality to allocate a static amount of memory while creating the object to store all its attributes.Usage of __slots__ reduce the wastage of space and speed up the program by allocating space for a fixed amount of attributes. Example of python object with slots : class GFG(object): __slots__=['a', 'b'] def __init__(self, *args, **kwargs): self.a = 1 self.b = 2 if __name__ == "__main__": instance = GFG() print(instance.__slots__) Output : ['a', 'b'] Example of python if we use dict : class GFG(object): __slots__=['a', 'b'] def __init__(self, *args, **kwargs): self.a = 1 self.b = 2 if __name__ == "__main__": instance = GFG() print(instance.__dict__) Output : AttributeError: 'GFG' object has no attribute '__dict__' This error will be caused. Result of using __slots__: Fast access to attributesSaves memory space Fast access to attributes Saves memory space Python Python Programs 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 Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 24415, "s": 24387, "text": "\n27 Dec, 2019" }, { "code": null, "e": 24731, "s": 24415, "text": "When we create objects for classes, it requires memory and the attribute are stored in the form of a dictionary. In case if we need to allocate thousands of objects, it will take a lot of memory space.slots provide a special mechanism to reduce the size of objects.It is a concept of memory optimisation on objects." }, { "code": null, "e": 24772, "s": 24731, "text": "Example of python object without slots :" }, { "code": "class GFG(object): def __init__(self, *args, **kwargs): self.a = 1 self.b = 2 if __name__ == \"__main__\": instance = GFG() print(instance.__dict__)", "e": 24963, "s": 24772, "text": null }, { "code": null, "e": 24972, "s": 24963, "text": "Output :" }, { "code": null, "e": 24989, "s": 24972, "text": "{'a': 1, 'b': 2}" }, { "code": null, "e": 25457, "s": 24989, "text": "As every object in Python contains a dynamic dictionary that allows adding attributes. For every instance object, we will have an instance of a dictionary that consumes more space and wastes a lot of RAM. In Python, there is no default functionality to allocate a static amount of memory while creating the object to store all its attributes.Usage of __slots__ reduce the wastage of space and speed up the program by allocating space for a fixed amount of attributes." }, { "code": null, "e": 25495, "s": 25457, "text": "Example of python object with slots :" }, { "code": "class GFG(object): __slots__=['a', 'b'] def __init__(self, *args, **kwargs): self.a = 1 self.b = 2 if __name__ == \"__main__\": instance = GFG() print(instance.__slots__)", "e": 25713, "s": 25495, "text": null }, { "code": null, "e": 25722, "s": 25713, "text": "Output :" }, { "code": null, "e": 25733, "s": 25722, "text": "['a', 'b']" }, { "code": null, "e": 25768, "s": 25733, "text": "Example of python if we use dict :" }, { "code": "class GFG(object): __slots__=['a', 'b'] def __init__(self, *args, **kwargs): self.a = 1 self.b = 2 if __name__ == \"__main__\": instance = GFG() print(instance.__dict__)", "e": 25985, "s": 25768, "text": null }, { "code": null, "e": 25994, "s": 25985, "text": "Output :" }, { "code": null, "e": 26051, "s": 25994, "text": "AttributeError: 'GFG' object has no attribute '__dict__'" }, { "code": null, "e": 26078, "s": 26051, "text": "This error will be caused." }, { "code": null, "e": 26105, "s": 26078, "text": "Result of using __slots__:" }, { "code": null, "e": 26149, "s": 26105, "text": "Fast access to attributesSaves memory space" }, { "code": null, "e": 26175, "s": 26149, "text": "Fast access to attributes" }, { "code": null, "e": 26194, "s": 26175, "text": "Saves memory space" }, { "code": null, "e": 26201, "s": 26194, "text": "Python" }, { "code": null, "e": 26217, "s": 26201, "text": "Python Programs" }, { "code": null, "e": 26236, "s": 26217, "text": "Technical Scripter" }, { "code": null, "e": 26334, "s": 26236, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26352, "s": 26334, "text": "Python Dictionary" }, { "code": null, "e": 26387, "s": 26352, "text": "Read a file line by line in Python" }, { "code": null, "e": 26409, "s": 26387, "text": "Enumerate() in Python" }, { "code": null, "e": 26441, "s": 26409, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26483, "s": 26441, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26505, "s": 26483, "text": "Defaultdict in Python" }, { "code": null, "e": 26551, "s": 26505, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26590, "s": 26551, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26628, "s": 26590, "text": "Python | Convert a list to dictionary" } ]
IMS DB - SSA
SSA stands for Segment Search Arguments. SSA is used to identify the segment occurrence being accessed. It is an optional parameter. We can include any number of SSAs depending on the requirement. There are two types of SSAs − Unqualified SSA Qualified SSA An unqualified SSA provides the name of the segment being used inside the call. Given below is the syntax of an unqualified SSA − 01 UNQUALIFIED-SSA. 05 SEGMENT-NAME PIC X(8). 05 FILLER PIC X VALUE SPACE. The key points of unqualified SSA are as follows − A basic unqualified SSA is 9 bytes long. A basic unqualified SSA is 9 bytes long. The first 8 bytes hold the segment name which is being used for processing. The first 8 bytes hold the segment name which is being used for processing. The last byte always contains space. The last byte always contains space. DL/I uses the last byte to determine the type of SSA. DL/I uses the last byte to determine the type of SSA. To access a particular segment, move the name of the segment in the SEGMENT-NAME field. To access a particular segment, move the name of the segment in the SEGMENT-NAME field. The following images show the structures of unqualified and qualified SSAs − A Qualified SSA provides the segment type with the specific database occurrence of a segment. Given below is the syntax of a Qualified SSA − 01 QUALIFIED-SSA. 05 SEGMENT-NAME PIC X(8). 05 FILLER PIC X(01) VALUE '('. 05 FIELD-NAME PIC X(8). 05 REL-OPR PIC X(2). 05 SEARCH-VALUE PIC X(n). 05 FILLER PIC X(n+1) VALUE ')'. The key points of qualified SSA are as follows − The first 8 bytes of a qualified SSA holds the segment name being used for processing. The first 8 bytes of a qualified SSA holds the segment name being used for processing. The ninth byte is a left parenthesis '('. The ninth byte is a left parenthesis '('. The next 8 bytes starting from the tenth position specifies the field name which we want to search. The next 8 bytes starting from the tenth position specifies the field name which we want to search. After the field name, in the 18th and 19th positions, we specify two-character relational operator code. After the field name, in the 18th and 19th positions, we specify two-character relational operator code. Then we specify the field value and in the last byte, there is a right parenthesis ')'. Then we specify the field value and in the last byte, there is a right parenthesis ')'. The following table shows the relational operators used in a Qualified SSA. Command codes are used to enhance the functionality of DL/I calls. Command codes reduce the number of DL/I calls, making the programs simple. Also, it improves the performance as the number of calls is reduced. The following image shows how command codes are used in unqualified and qualified SSAs − The key points of command codes are as follows − To use command codes, specify an asterisk in the 9th position of the SSA as shown in the above image. To use command codes, specify an asterisk in the 9th position of the SSA as shown in the above image. Command code is coded at the tenth position. Command code is coded at the tenth position. From 10th position onwards, DL/I considers all characters to be command codes until it encounters a space for an unqualified SSA and a left parenthesis for a qualified SSA. From 10th position onwards, DL/I considers all characters to be command codes until it encounters a space for an unqualified SSA and a left parenthesis for a qualified SSA. The following table shows the list of command codes used in SSA − The fundamental points of multiple qualifications are as follows − Multiple qualifications are required when we need to use two or more qualifications or fields for comparison. Multiple qualifications are required when we need to use two or more qualifications or fields for comparison. We use Boolean operators like AND and OR to connect two or more qualifications. We use Boolean operators like AND and OR to connect two or more qualifications. Multiple qualifications can be used when we want to process a segment based on a range of possible values for a single field. Multiple qualifications can be used when we want to process a segment based on a range of possible values for a single field. Given below is the syntax of Multiple Qualifications − 01 QUALIFIED-SSA. 05 SEGMENT-NAME PIC X(8). 05 FILLER PIC X(01) VALUE '('. 05 FIELD-NAME1 PIC X(8). 05 REL-OPR PIC X(2). 05 SEARCH-VALUE1 PIC X(m). 05 MUL-QUAL PIC X VALUE '&'. 05 FIELD-NAME2 PIC X(8). 05 REL-OPR PIC X(2). 05 SEARCH-VALUE2 PIC X(n). 05 FILLER PIC X(n+1) VALUE ')'. MUL-QUAL is a short term for MULtiple QUALIification in which we can provide boolean operators like AND or OR. Print Add Notes Bookmark this page
[ { "code": null, "e": 2173, "s": 1946, "text": "SSA stands for Segment Search Arguments. SSA is used to identify the segment occurrence being accessed. It is an optional parameter. We can include any number of SSAs depending on the requirement. There are two types of SSAs −" }, { "code": null, "e": 2189, "s": 2173, "text": "Unqualified SSA" }, { "code": null, "e": 2203, "s": 2189, "text": "Qualified SSA" }, { "code": null, "e": 2333, "s": 2203, "text": "An unqualified SSA provides the name of the segment being used inside the call. Given below is the syntax of an unqualified SSA −" }, { "code": null, "e": 2429, "s": 2333, "text": "01 UNQUALIFIED-SSA.\n 05 SEGMENT-NAME PIC X(8).\n 05 FILLER PIC X VALUE SPACE.\n" }, { "code": null, "e": 2480, "s": 2429, "text": "The key points of unqualified SSA are as follows −" }, { "code": null, "e": 2521, "s": 2480, "text": "A basic unqualified SSA is 9 bytes long." }, { "code": null, "e": 2562, "s": 2521, "text": "A basic unqualified SSA is 9 bytes long." }, { "code": null, "e": 2638, "s": 2562, "text": "The first 8 bytes hold the segment name which is being used for processing." }, { "code": null, "e": 2714, "s": 2638, "text": "The first 8 bytes hold the segment name which is being used for processing." }, { "code": null, "e": 2751, "s": 2714, "text": "The last byte always contains space." }, { "code": null, "e": 2788, "s": 2751, "text": "The last byte always contains space." }, { "code": null, "e": 2842, "s": 2788, "text": "DL/I uses the last byte to determine the type of SSA." }, { "code": null, "e": 2896, "s": 2842, "text": "DL/I uses the last byte to determine the type of SSA." }, { "code": null, "e": 2984, "s": 2896, "text": "To access a particular segment, move the name of the segment in the SEGMENT-NAME field." }, { "code": null, "e": 3072, "s": 2984, "text": "To access a particular segment, move the name of the segment in the SEGMENT-NAME field." }, { "code": null, "e": 3149, "s": 3072, "text": "The following images show the structures of unqualified and qualified SSAs −" }, { "code": null, "e": 3290, "s": 3149, "text": "A Qualified SSA provides the segment type with the specific database occurrence of a segment. Given below is the syntax of a Qualified SSA −" }, { "code": null, "e": 3522, "s": 3290, "text": "01 QUALIFIED-SSA.\n 05 SEGMENT-NAME PIC X(8).\n 05 FILLER PIC X(01) VALUE '('.\n 05 FIELD-NAME PIC X(8).\n 05 REL-OPR PIC X(2).\n 05 SEARCH-VALUE PIC X(n).\n 05 FILLER PIC X(n+1) VALUE ')'.\n" }, { "code": null, "e": 3571, "s": 3522, "text": "The key points of qualified SSA are as follows −" }, { "code": null, "e": 3658, "s": 3571, "text": "The first 8 bytes of a qualified SSA holds the segment name being used for processing." }, { "code": null, "e": 3745, "s": 3658, "text": "The first 8 bytes of a qualified SSA holds the segment name being used for processing." }, { "code": null, "e": 3787, "s": 3745, "text": "The ninth byte is a left parenthesis '('." }, { "code": null, "e": 3829, "s": 3787, "text": "The ninth byte is a left parenthesis '('." }, { "code": null, "e": 3929, "s": 3829, "text": "The next 8 bytes starting from the tenth position specifies the field name which we want to search." }, { "code": null, "e": 4029, "s": 3929, "text": "The next 8 bytes starting from the tenth position specifies the field name which we want to search." }, { "code": null, "e": 4134, "s": 4029, "text": "After the field name, in the 18th and 19th positions, we specify two-character relational operator code." }, { "code": null, "e": 4239, "s": 4134, "text": "After the field name, in the 18th and 19th positions, we specify two-character relational operator code." }, { "code": null, "e": 4327, "s": 4239, "text": "Then we specify the field value and in the last byte, there is a right parenthesis ')'." }, { "code": null, "e": 4415, "s": 4327, "text": "Then we specify the field value and in the last byte, there is a right parenthesis ')'." }, { "code": null, "e": 4491, "s": 4415, "text": "The following table shows the relational operators used in a Qualified SSA." }, { "code": null, "e": 4791, "s": 4491, "text": "Command codes are used to enhance the functionality of DL/I calls. Command codes reduce the number of DL/I calls, making the programs simple. Also, it improves the performance as the number of calls is reduced. The following image shows how command codes are used in unqualified and qualified SSAs −" }, { "code": null, "e": 4840, "s": 4791, "text": "The key points of command codes are as follows −" }, { "code": null, "e": 4942, "s": 4840, "text": "To use command codes, specify an asterisk in the 9th position of the SSA as shown in the above image." }, { "code": null, "e": 5044, "s": 4942, "text": "To use command codes, specify an asterisk in the 9th position of the SSA as shown in the above image." }, { "code": null, "e": 5089, "s": 5044, "text": "Command code is coded at the tenth position." }, { "code": null, "e": 5134, "s": 5089, "text": "Command code is coded at the tenth position." }, { "code": null, "e": 5307, "s": 5134, "text": "From 10th position onwards, DL/I considers all characters to be command codes until it encounters a space for an unqualified SSA and a left parenthesis for a qualified SSA." }, { "code": null, "e": 5480, "s": 5307, "text": "From 10th position onwards, DL/I considers all characters to be command codes until it encounters a space for an unqualified SSA and a left parenthesis for a qualified SSA." }, { "code": null, "e": 5546, "s": 5480, "text": "The following table shows the list of command codes used in SSA −" }, { "code": null, "e": 5613, "s": 5546, "text": "The fundamental points of multiple qualifications are as follows −" }, { "code": null, "e": 5723, "s": 5613, "text": "Multiple qualifications are required when we need to use two or more qualifications or fields for comparison." }, { "code": null, "e": 5833, "s": 5723, "text": "Multiple qualifications are required when we need to use two or more qualifications or fields for comparison." }, { "code": null, "e": 5913, "s": 5833, "text": "We use Boolean operators like AND and OR to connect two or more qualifications." }, { "code": null, "e": 5993, "s": 5913, "text": "We use Boolean operators like AND and OR to connect two or more qualifications." }, { "code": null, "e": 6119, "s": 5993, "text": "Multiple qualifications can be used when we want to process a segment based on a range of possible values for a single field." }, { "code": null, "e": 6245, "s": 6119, "text": "Multiple qualifications can be used when we want to process a segment based on a range of possible values for a single field." }, { "code": null, "e": 6300, "s": 6245, "text": "Given below is the syntax of Multiple Qualifications −" }, { "code": null, "e": 6668, "s": 6300, "text": "01 QUALIFIED-SSA.\n 05 SEGMENT-NAME PIC X(8).\n 05 FILLER PIC X(01) VALUE '('.\n 05 FIELD-NAME1 PIC X(8).\n 05 REL-OPR PIC X(2).\n 05 SEARCH-VALUE1 PIC X(m).\n 05 MUL-QUAL PIC X VALUE '&'.\n 05 FIELD-NAME2 PIC X(8).\n 05 REL-OPR PIC X(2).\n 05 SEARCH-VALUE2 PIC X(n).\n 05 FILLER PIC X(n+1) VALUE ')'.\n" }, { "code": null, "e": 6779, "s": 6668, "text": "MUL-QUAL is a short term for MULtiple QUALIification in which we can provide boolean operators like AND or OR." }, { "code": null, "e": 6786, "s": 6779, "text": " Print" }, { "code": null, "e": 6797, "s": 6786, "text": " Add Notes" } ]
How to clear Python shell?
Python provides a python shell which is used to execute a single Python command and display the result. It is also called REPL. REPL stands for Read, Evaluate, Print and Loop. The command is read, then evaluated, afterwards the result is printed and looped back to read the next command. Sometimes after executing so many commands and getting haphazard output or having executed some unnecessary commands, we may need to clear the python shell. If the shell is not cleared, we will need to scroll the screen too many times which is inefficient. Thus, it is required to clear the python shell. The commands used to clear the terminal or Python shell are cls and clear. In Windows import os os.system(‘CLS’) In Linux import os os.system(‘clear’) Let us suppose, we need to show some output for few seconds and then we want to clear the shell. The following code serves the purpose. Import os and sleep Import os and sleep Define a function where the commands to clear the shell are specified, cls for windows and clear for linux. Define a function where the commands to clear the shell are specified, cls for windows and clear for linux. Print some output Print some output Let the screen sleep for few seconds Let the screen sleep for few seconds Call the function to clear the screen Call the function to clear the screen from os import system, name from time import sleep def clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux else: _ = system('clear') print(“Hi Learner!!”) sleep(5) clear()
[ { "code": null, "e": 1350, "s": 1062, "text": "Python provides a python shell which is used to execute a single Python command and display the result. It is also called REPL. REPL stands for Read, Evaluate, Print and Loop. The command is read, then evaluated, afterwards the result is printed and looped back to read the next command." }, { "code": null, "e": 1655, "s": 1350, "text": "Sometimes after executing so many commands and getting haphazard output or having executed some unnecessary commands, we may need to clear the python shell. If the shell is not cleared, we will need to scroll the screen too many times which is inefficient. Thus, it is required to clear the python shell." }, { "code": null, "e": 1730, "s": 1655, "text": "The commands used to clear the terminal or Python shell are cls and clear." }, { "code": null, "e": 1741, "s": 1730, "text": "In Windows" }, { "code": null, "e": 1768, "s": 1741, "text": "import os\nos.system(‘CLS’)" }, { "code": null, "e": 1777, "s": 1768, "text": "In Linux" }, { "code": null, "e": 1806, "s": 1777, "text": "import os\nos.system(‘clear’)" }, { "code": null, "e": 1942, "s": 1806, "text": "Let us suppose, we need to show some output for few seconds and then we want to clear the shell. The following code serves the purpose." }, { "code": null, "e": 1962, "s": 1942, "text": "Import os and sleep" }, { "code": null, "e": 1982, "s": 1962, "text": "Import os and sleep" }, { "code": null, "e": 2090, "s": 1982, "text": "Define a function where the commands to clear the shell are specified, cls for windows and clear for linux." }, { "code": null, "e": 2198, "s": 2090, "text": "Define a function where the commands to clear the shell are specified, cls for windows and clear for linux." }, { "code": null, "e": 2216, "s": 2198, "text": "Print some output" }, { "code": null, "e": 2234, "s": 2216, "text": "Print some output" }, { "code": null, "e": 2271, "s": 2234, "text": "Let the screen sleep for few seconds" }, { "code": null, "e": 2308, "s": 2271, "text": "Let the screen sleep for few seconds" }, { "code": null, "e": 2346, "s": 2308, "text": "Call the function to clear the screen" }, { "code": null, "e": 2384, "s": 2346, "text": "Call the function to clear the screen" }, { "code": null, "e": 2605, "s": 2384, "text": "from os import system, name\nfrom time import sleep\ndef clear():\n # for windows\n if name == 'nt':\n _ = system('cls')\n\n # for mac and linux\n else:\n _ = system('clear')\n\nprint(“Hi Learner!!”)\nsleep(5)\nclear()" } ]
How to delete one or more rows in excel using Openpyxl? - GeeksforGeeks
24 Jan, 2021 Openpyxl is a Python library to manipulate xlsx/xlsm/xltx/xltm files. With Openpyxl you can create a new Excel file or a sheet and can also be used on an existing Excel file or sheet. This module does not come built-in with Python. To install this type the below command in the terminal. pip3 install openpyxl In this article, we will discuss how to delete rows in an Excel sheet with openpyxl. You can find the Excel file used for this article here. Method 1: This method removes empty rows but not continues empty rows, because when you delete the first empty row the next row gets its position. So it is not validated. Hence, this problem can be solved by recursive function calls. Approach: Import openpyxl library. Load Excel file with openpyxl. Then load the sheet from the file. Iterate the rows from the sheet that is loaded. Pass the row to remove the function. Then check for each cell if it is empty if any of the cells non-empty return the function, so only empty rows will exit the for loop without returning. Only if all rows are empty, remove statement is executed. Finally, save the file to the path. Python3 # import openpyxl libraryimport openpyxl # function to remove empty rows def remove(sheet, row): # iterate the row object for cell in row: # check the value of each cell in # the row, if any of the value is not # None return without removing the row if cell.value != None: return # get the row number from the first cell # and remove the row sheet.delete_rows(row[0].row, 1) if __name__ == '__main__': # enter your file path path = './delete_empty_rows.xlsx' # load excel file book = openpyxl.load_workbook(path) # select the sheet sheet = book['daily sales'] print("Maximum rows before removing:", sheet.max_row) # iterate the sheet object for row in sheet: remove(sheet,row) print("Maximum rows after removing:",sheet.max_row) # save the file to the path path = './openpy.xlsx' book.save(path) Output: Maximum rows before removing: 15 Maximum rows after removing: 14 File after deletion: The first method deleted only the first empty row and the second continuous empty row is not deleted. Method 2: This method removes empty rows, including continuous empty rows by using the recursive approach. The key point is to pass the modified sheet object as an argument to the recursive function. If there is no empty row function is returned immediately. Approach: Import openpyxl library. Load Excel file with openpyxl. Then load the sheet from the file. Pass the sheet that is loaded to the remove function. Iterate the rows with iter_rows(). If any of the cells in a row is non-empty, any() return false, so it is returned immediately. If all cells in a row are empty, then remove the row with delete_rows(). Then pass the modified sheet object to the remove function, this repeats until the end of the sheet is reached. Finally, save the file to the path. Python3 # import openpyxl libraryimport openpyxl # function to remove empty rows def remove(sheet): # iterate the sheet by rows for row in sheet.iter_rows(): # all() return False if all of the row value is None if not all(cell.value for cell in row): # detele the empty row sheet.delete_rows(row[0].row, 1) # recursively call the remove() with modified sheet data remove(sheet) return if __name__ == '__main__': # enter your file path path = './delete_empty_rows.xlsx' # load excel file book = openpyxl.load_workbook(path) # select the sheet sheet = book['daily sales'] print("Maximum rows before removing:", sheet.max_row) # iterate the sheet for row in sheet: remove(sheet) print("Maximum rows after removing:",sheet.max_row) # save the file to the path path = './openpy.xlsx' book.save(path) Output: Maximum rows before removing: 15 Maximum rows after removing: 13 File after deletion: This method deleted both continuous empty rows as expected. Method 1: In this method, we delete the second row repeatedly until a single row is left(column names). Approach: Import openpyxl library. Load the Excel file and the sheet to work with. Pass the sheet object to delete function. Delete the second row, until there is a single row left. Finally, return the function. Python3 import openpyxl def delete(sheet): # continuously delete row 2 untill there # is only a single row left over # that contains column names while(sheet.max_row > 1): # this method removes the row 2 sheet.delete_rows(2) # return to main function return if __name__ == '__main__': # enter your file path path = './delete_every_rows.xlsx' # load excel file book = openpyxl.load_workbook(path) # select the sheet sheet = book['sheet1'] print("Maximum rows before removing:", sheet.max_row) delete(sheet) print("Maximum rows after removing:", sheet.max_row) # save the file to the path path = './openpy.xlsx' book.save(path) Output: Maximum rows before removing: 15 Maximum rows after removing: 1 File after deletion: Method 2: In this method, we use openpyxl sheet method to delete entire rows with a single command. Approach: Import openpyxl library. Load the Excel file and the sheet to work with. Use delete_rows function to delete all rows except the column names. So a single empty row is left over. Python3 import openpyxl if __name__ == '__main__': # enter your file path path = './delete_every_rows.xlsx' # load excel file book = openpyxl.load_workbook(path) # select the sheet sheet = book['sheet1'] print("Maximum rows before removing:", sheet.max_row) # sheet.max_row is the maximum number # of rows that the sheet have # delete_row() method removes rows, first parameter represents row # number and sencond parameter represents number of rows # to delete from the row number sheet.delete_rows(2, sheet.max_row-1) print("Maximum rows after removing:", sheet.max_row) # save the file to the path path = './openpy.xlsx' book.save(path) Output: Maximum rows before removing: 15 Maximum rows after removing: 1 File after deletion: Picked Python-excel Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n24 Jan, 2021" }, { "code": null, "e": 24085, "s": 23901, "text": "Openpyxl is a Python library to manipulate xlsx/xlsm/xltx/xltm files. With Openpyxl you can create a new Excel file or a sheet and can also be used on an existing Excel file or sheet." }, { "code": null, "e": 24189, "s": 24085, "text": "This module does not come built-in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 24211, "s": 24189, "text": "pip3 install openpyxl" }, { "code": null, "e": 24352, "s": 24211, "text": "In this article, we will discuss how to delete rows in an Excel sheet with openpyxl. You can find the Excel file used for this article here." }, { "code": null, "e": 24362, "s": 24352, "text": "Method 1:" }, { "code": null, "e": 24587, "s": 24362, "text": "This method removes empty rows but not continues empty rows, because when you delete the first empty row the next row gets its position. So it is not validated. Hence, this problem can be solved by recursive function calls. " }, { "code": null, "e": 24597, "s": 24587, "text": "Approach:" }, { "code": null, "e": 24622, "s": 24597, "text": "Import openpyxl library." }, { "code": null, "e": 24653, "s": 24622, "text": "Load Excel file with openpyxl." }, { "code": null, "e": 24688, "s": 24653, "text": "Then load the sheet from the file." }, { "code": null, "e": 24736, "s": 24688, "text": "Iterate the rows from the sheet that is loaded." }, { "code": null, "e": 24773, "s": 24736, "text": "Pass the row to remove the function." }, { "code": null, "e": 24925, "s": 24773, "text": "Then check for each cell if it is empty if any of the cells non-empty return the function, so only empty rows will exit the for loop without returning." }, { "code": null, "e": 24983, "s": 24925, "text": "Only if all rows are empty, remove statement is executed." }, { "code": null, "e": 25019, "s": 24983, "text": "Finally, save the file to the path." }, { "code": null, "e": 25027, "s": 25019, "text": "Python3" }, { "code": "# import openpyxl libraryimport openpyxl # function to remove empty rows def remove(sheet, row): # iterate the row object for cell in row: # check the value of each cell in # the row, if any of the value is not # None return without removing the row if cell.value != None: return # get the row number from the first cell # and remove the row sheet.delete_rows(row[0].row, 1) if __name__ == '__main__': # enter your file path path = './delete_empty_rows.xlsx' # load excel file book = openpyxl.load_workbook(path) # select the sheet sheet = book['daily sales'] print(\"Maximum rows before removing:\", sheet.max_row) # iterate the sheet object for row in sheet: remove(sheet,row) print(\"Maximum rows after removing:\",sheet.max_row) # save the file to the path path = './openpy.xlsx' book.save(path)", "e": 25957, "s": 25027, "text": null }, { "code": null, "e": 25965, "s": 25957, "text": "Output:" }, { "code": null, "e": 26030, "s": 25965, "text": "Maximum rows before removing: 15\nMaximum rows after removing: 14" }, { "code": null, "e": 26051, "s": 26030, "text": "File after deletion:" }, { "code": null, "e": 26153, "s": 26051, "text": "The first method deleted only the first empty row and the second continuous empty row is not deleted." }, { "code": null, "e": 26163, "s": 26153, "text": "Method 2:" }, { "code": null, "e": 26412, "s": 26163, "text": "This method removes empty rows, including continuous empty rows by using the recursive approach. The key point is to pass the modified sheet object as an argument to the recursive function. If there is no empty row function is returned immediately." }, { "code": null, "e": 26422, "s": 26412, "text": "Approach:" }, { "code": null, "e": 26447, "s": 26422, "text": "Import openpyxl library." }, { "code": null, "e": 26478, "s": 26447, "text": "Load Excel file with openpyxl." }, { "code": null, "e": 26513, "s": 26478, "text": "Then load the sheet from the file." }, { "code": null, "e": 26567, "s": 26513, "text": "Pass the sheet that is loaded to the remove function." }, { "code": null, "e": 26602, "s": 26567, "text": "Iterate the rows with iter_rows()." }, { "code": null, "e": 26696, "s": 26602, "text": "If any of the cells in a row is non-empty, any() return false, so it is returned immediately." }, { "code": null, "e": 26769, "s": 26696, "text": "If all cells in a row are empty, then remove the row with delete_rows()." }, { "code": null, "e": 26881, "s": 26769, "text": "Then pass the modified sheet object to the remove function, this repeats until the end of the sheet is reached." }, { "code": null, "e": 26917, "s": 26881, "text": "Finally, save the file to the path." }, { "code": null, "e": 26925, "s": 26917, "text": "Python3" }, { "code": "# import openpyxl libraryimport openpyxl # function to remove empty rows def remove(sheet): # iterate the sheet by rows for row in sheet.iter_rows(): # all() return False if all of the row value is None if not all(cell.value for cell in row): # detele the empty row sheet.delete_rows(row[0].row, 1) # recursively call the remove() with modified sheet data remove(sheet) return if __name__ == '__main__': # enter your file path path = './delete_empty_rows.xlsx' # load excel file book = openpyxl.load_workbook(path) # select the sheet sheet = book['daily sales'] print(\"Maximum rows before removing:\", sheet.max_row) # iterate the sheet for row in sheet: remove(sheet) print(\"Maximum rows after removing:\",sheet.max_row) # save the file to the path path = './openpy.xlsx' book.save(path)", "e": 27831, "s": 26925, "text": null }, { "code": null, "e": 27839, "s": 27831, "text": "Output:" }, { "code": null, "e": 27904, "s": 27839, "text": "Maximum rows before removing: 15\nMaximum rows after removing: 13" }, { "code": null, "e": 27925, "s": 27904, "text": "File after deletion:" }, { "code": null, "e": 27985, "s": 27925, "text": "This method deleted both continuous empty rows as expected." }, { "code": null, "e": 27995, "s": 27985, "text": "Method 1:" }, { "code": null, "e": 28090, "s": 27995, "text": " In this method, we delete the second row repeatedly until a single row is left(column names)." }, { "code": null, "e": 28100, "s": 28090, "text": "Approach:" }, { "code": null, "e": 28125, "s": 28100, "text": "Import openpyxl library." }, { "code": null, "e": 28173, "s": 28125, "text": "Load the Excel file and the sheet to work with." }, { "code": null, "e": 28215, "s": 28173, "text": "Pass the sheet object to delete function." }, { "code": null, "e": 28272, "s": 28215, "text": "Delete the second row, until there is a single row left." }, { "code": null, "e": 28302, "s": 28272, "text": "Finally, return the function." }, { "code": null, "e": 28310, "s": 28302, "text": "Python3" }, { "code": "import openpyxl def delete(sheet): # continuously delete row 2 untill there # is only a single row left over # that contains column names while(sheet.max_row > 1): # this method removes the row 2 sheet.delete_rows(2) # return to main function return if __name__ == '__main__': # enter your file path path = './delete_every_rows.xlsx' # load excel file book = openpyxl.load_workbook(path) # select the sheet sheet = book['sheet1'] print(\"Maximum rows before removing:\", sheet.max_row) delete(sheet) print(\"Maximum rows after removing:\", sheet.max_row) # save the file to the path path = './openpy.xlsx' book.save(path)", "e": 29024, "s": 28310, "text": null }, { "code": null, "e": 29032, "s": 29024, "text": "Output:" }, { "code": null, "e": 29096, "s": 29032, "text": "Maximum rows before removing: 15\nMaximum rows after removing: 1" }, { "code": null, "e": 29117, "s": 29096, "text": "File after deletion:" }, { "code": null, "e": 29127, "s": 29117, "text": "Method 2:" }, { "code": null, "e": 29217, "s": 29127, "text": "In this method, we use openpyxl sheet method to delete entire rows with a single command." }, { "code": null, "e": 29227, "s": 29217, "text": "Approach:" }, { "code": null, "e": 29252, "s": 29227, "text": "Import openpyxl library." }, { "code": null, "e": 29300, "s": 29252, "text": "Load the Excel file and the sheet to work with." }, { "code": null, "e": 29369, "s": 29300, "text": "Use delete_rows function to delete all rows except the column names." }, { "code": null, "e": 29405, "s": 29369, "text": "So a single empty row is left over." }, { "code": null, "e": 29413, "s": 29405, "text": "Python3" }, { "code": "import openpyxl if __name__ == '__main__': # enter your file path path = './delete_every_rows.xlsx' # load excel file book = openpyxl.load_workbook(path) # select the sheet sheet = book['sheet1'] print(\"Maximum rows before removing:\", sheet.max_row) # sheet.max_row is the maximum number # of rows that the sheet have # delete_row() method removes rows, first parameter represents row # number and sencond parameter represents number of rows # to delete from the row number sheet.delete_rows(2, sheet.max_row-1) print(\"Maximum rows after removing:\", sheet.max_row) # save the file to the path path = './openpy.xlsx' book.save(path)", "e": 30111, "s": 29413, "text": null }, { "code": null, "e": 30119, "s": 30111, "text": "Output:" }, { "code": null, "e": 30183, "s": 30119, "text": "Maximum rows before removing: 15\nMaximum rows after removing: 1" }, { "code": null, "e": 30204, "s": 30183, "text": "File after deletion:" }, { "code": null, "e": 30211, "s": 30204, "text": "Picked" }, { "code": null, "e": 30224, "s": 30211, "text": "Python-excel" }, { "code": null, "e": 30231, "s": 30224, "text": "Python" }, { "code": null, "e": 30329, "s": 30231, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30338, "s": 30329, "text": "Comments" }, { "code": null, "e": 30351, "s": 30338, "text": "Old Comments" }, { "code": null, "e": 30383, "s": 30351, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30439, "s": 30383, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30481, "s": 30439, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30523, "s": 30481, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30559, "s": 30523, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 30581, "s": 30559, "text": "Defaultdict in Python" }, { "code": null, "e": 30620, "s": 30581, "text": "Python | Get unique values from a list" }, { "code": null, "e": 30647, "s": 30620, "text": "Python Classes and Objects" }, { "code": null, "e": 30678, "s": 30647, "text": "Python | os.path.join() method" } ]
Core arguments in serializer fields - Django REST Framework - GeeksforGeeks
03 Dec, 2021 Serializer fields in Django are same as Django Form fields and Django model fields and thus require certain arguments to manipulate the behaviour of those Fields. In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. This article revolves around various arguments that serializer fields can use for efficiently manipulating data in and out of serializer. .math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any ‘read_only’ fields that are incorrectly included in the serializer input will be ignored. Set this to True to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization. Defaults to False Syntax – read_only = True/False Example – field_name = serializers.CharField(read_only = True) Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation. Defaults to False Syntax – write_only = True/False Example – field_name = serializers.CharField(write_only = True) Normally an error will be raised if a field is not supplied during deserialization. Set to false if this field is not required to be present during deserialization. Setting this to False also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation. Defaults to True. Syntax – write_only = True/False Example – field_name = serializers.CharField(write_only = True) If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all. The default is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned. May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a requires_context = True attribute, then the serializer field will be passed as an argument. For example: class CurrentUserDefault: """ May be applied as a `default=...` value on a serializer field. Returns the current user. """ requires_context = True def __call__(self, serializer_field): return serializer_field.context['request'].user When serializing the instance, default will be used if the o object attribute or dictionary key is not present in the instance. Note that setting a default value implies that the field is not required. Including both the default and required keyword arguments is invalid and will raise an error. Syntax – default = value Example – field_name = serializers.CharField(default = "Naveen") Normally an error will be raised if None is passed to a serializer field. Set this keyword argument to True if None should be considered a valid value. Note that, without an explicit default, setting this argument to True will imply a default value of null for serialization output, but does not imply a default for input deserialization. Defaults to False Syntax – allow_null = True/False Example – field_name = serializers.CharField(allow_null = True) The name of the attribute that will be used to populate the field. May be a method that only takes a self argument, such as URLField(source=’get_absolute_url’), or may use dotted notation to traverse attributes, such as EmailField(source=’user.email’). When serializing fields with dotted notation, it may be necessary to provide a default value if any object is not present or is empty during attribute traversal. The value source=’*’ has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation. Defaults to the name of the field. Syntax – source = value Example – field_name = serializers.CharField(source = "user.name") A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise serializers.ValidationError, but Django’s built-in ValidationError is also supported for compatibility with validators defined in the Django codebase or third party Django packages. Syntax – validators = [function_1, function_2] Example – field_name = serializers.CharField(validations = [validate_name, validate_username]) A dictionary of error codes to error messages. It works the same way as error_messages – Django Built-in Field Validation Syntax – error_messages = {'argument':'message'} Example – field_name = serializers.CharField(error_messages = {"unique":"Data should be unique"}) A short text string that may be used as the name of the field in HTML form fields or other descriptive elements. It is same as label – Django Form Field Validation Syntax – label = value Example – field_name = serializers.CharField(label = "Name") A text string that may be used as a description of the field in HTML form fields or other descriptive elements. It is same as help_text – Django Built-in Field Validation. Syntax – help_text = value Example – field_name = serializers.CharField(help_text = "Enter only 10 characters") A value that should be used for pre-populating the value of HTML form fields. It is same as initial – Django Form Field Validation. You may pass a callable to it, just as you may do with any regular Django Field: Syntax – initial = value Example – import datetime from rest_framework import serializers class ExampleSerializer(serializers.Serializer): day = serializers.DateField(initial=datetime.date.today) ruhelaa48 kalrap615 Django-REST rest-framework Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n03 Dec, 2021" }, { "code": null, "e": 24328, "s": 23901, "text": "Serializer fields in Django are same as Django Form fields and Django model fields and thus require certain arguments to manipulate the behaviour of those Fields. In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. This article revolves around various arguments that serializer fields can use for efficiently manipulating data in and out of serializer. " }, { "code": null, "e": 24668, "s": 24328, "text": ".math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } " }, { "code": null, "e": 24888, "s": 24668, "text": "Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any ‘read_only’ fields that are incorrectly included in the serializer input will be ignored. " }, { "code": null, "e": 25052, "s": 24888, "text": "Set this to True to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization. " }, { "code": null, "e": 25081, "s": 25052, "text": "Defaults to False Syntax – " }, { "code": null, "e": 25104, "s": 25081, "text": "read_only = True/False" }, { "code": null, "e": 25115, "s": 25104, "text": "Example – " }, { "code": null, "e": 25169, "s": 25115, "text": "field_name = serializers.CharField(read_only = True) " }, { "code": null, "e": 25320, "s": 25169, "text": "Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation. " }, { "code": null, "e": 25349, "s": 25320, "text": "Defaults to False Syntax – " }, { "code": null, "e": 25373, "s": 25349, "text": "write_only = True/False" }, { "code": null, "e": 25384, "s": 25373, "text": "Example – " }, { "code": null, "e": 25439, "s": 25384, "text": "field_name = serializers.CharField(write_only = True) " }, { "code": null, "e": 25605, "s": 25439, "text": "Normally an error will be raised if a field is not supplied during deserialization. Set to false if this field is not required to be present during deserialization. " }, { "code": null, "e": 25823, "s": 25605, "text": "Setting this to False also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation. " }, { "code": null, "e": 25842, "s": 25823, "text": "Defaults to True. " }, { "code": null, "e": 25853, "s": 25842, "text": "Syntax – " }, { "code": null, "e": 25877, "s": 25853, "text": "write_only = True/False" }, { "code": null, "e": 25888, "s": 25877, "text": "Example – " }, { "code": null, "e": 25943, "s": 25888, "text": "field_name = serializers.CharField(write_only = True) " }, { "code": null, "e": 26118, "s": 25943, "text": "If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all. " }, { "code": null, "e": 26296, "s": 26118, "text": "The default is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned. " }, { "code": null, "e": 26562, "s": 26296, "text": "May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a requires_context = True attribute, then the serializer field will be passed as an argument. " }, { "code": null, "e": 26576, "s": 26562, "text": "For example: " }, { "code": null, "e": 26903, "s": 26576, "text": "class CurrentUserDefault:\n \"\"\"\n May be applied as a `default=...` value on a serializer field.\n Returns the current user.\n \"\"\"\n requires_context = True\n\n def __call__(self, serializer_field):\n return serializer_field.context['request'].user\nWhen serializing the instance, default will be used if the o" }, { "code": null, "e": 26971, "s": 26903, "text": "object attribute or dictionary key is not present in the instance. " }, { "code": null, "e": 27140, "s": 26971, "text": "Note that setting a default value implies that the field is not required. Including both the default and required keyword arguments is invalid and will raise an error. " }, { "code": null, "e": 27151, "s": 27140, "text": "Syntax – " }, { "code": null, "e": 27167, "s": 27151, "text": "default = value" }, { "code": null, "e": 27178, "s": 27167, "text": "Example – " }, { "code": null, "e": 27234, "s": 27178, "text": "field_name = serializers.CharField(default = \"Naveen\") " }, { "code": null, "e": 27387, "s": 27234, "text": "Normally an error will be raised if None is passed to a serializer field. Set this keyword argument to True if None should be considered a valid value. " }, { "code": null, "e": 27575, "s": 27387, "text": "Note that, without an explicit default, setting this argument to True will imply a default value of null for serialization output, but does not imply a default for input deserialization. " }, { "code": null, "e": 27594, "s": 27575, "text": "Defaults to False " }, { "code": null, "e": 27605, "s": 27594, "text": "Syntax – " }, { "code": null, "e": 27629, "s": 27605, "text": "allow_null = True/False" }, { "code": null, "e": 27640, "s": 27629, "text": "Example – " }, { "code": null, "e": 27695, "s": 27640, "text": "field_name = serializers.CharField(allow_null = True) " }, { "code": null, "e": 28111, "s": 27695, "text": "The name of the attribute that will be used to populate the field. May be a method that only takes a self argument, such as URLField(source=’get_absolute_url’), or may use dotted notation to traverse attributes, such as EmailField(source=’user.email’). When serializing fields with dotted notation, it may be necessary to provide a default value if any object is not present or is empty during attribute traversal. " }, { "code": null, "e": 28405, "s": 28111, "text": "The value source=’*’ has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation. " }, { "code": null, "e": 28441, "s": 28405, "text": "Defaults to the name of the field. " }, { "code": null, "e": 28452, "s": 28441, "text": "Syntax – " }, { "code": null, "e": 28467, "s": 28452, "text": "source = value" }, { "code": null, "e": 28478, "s": 28467, "text": "Example – " }, { "code": null, "e": 28536, "s": 28478, "text": "field_name = serializers.CharField(source = \"user.name\") " }, { "code": null, "e": 28905, "s": 28536, "text": "A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise serializers.ValidationError, but Django’s built-in ValidationError is also supported for compatibility with validators defined in the Django codebase or third party Django packages. " }, { "code": null, "e": 28916, "s": 28905, "text": "Syntax – " }, { "code": null, "e": 28954, "s": 28916, "text": "validators = [function_1, function_2]" }, { "code": null, "e": 28965, "s": 28954, "text": "Example – " }, { "code": null, "e": 29051, "s": 28965, "text": "field_name = serializers.CharField(validations = [validate_name, validate_username]) " }, { "code": null, "e": 29184, "s": 29051, "text": "A dictionary of error codes to error messages. It works the same way as error_messages – Django Built-in Field Validation Syntax – " }, { "code": null, "e": 29224, "s": 29184, "text": "error_messages = {'argument':'message'}" }, { "code": null, "e": 29235, "s": 29224, "text": "Example – " }, { "code": null, "e": 29324, "s": 29235, "text": "field_name = serializers.CharField(error_messages = {\"unique\":\"Data should be unique\"}) " }, { "code": null, "e": 29489, "s": 29324, "text": "A short text string that may be used as the name of the field in HTML form fields or other descriptive elements. It is same as label – Django Form Field Validation " }, { "code": null, "e": 29500, "s": 29489, "text": "Syntax – " }, { "code": null, "e": 29514, "s": 29500, "text": "label = value" }, { "code": null, "e": 29525, "s": 29514, "text": "Example – " }, { "code": null, "e": 29577, "s": 29525, "text": "field_name = serializers.CharField(label = \"Name\") " }, { "code": null, "e": 29760, "s": 29577, "text": "A text string that may be used as a description of the field in HTML form fields or other descriptive elements. It is same as help_text – Django Built-in Field Validation. Syntax – " }, { "code": null, "e": 29778, "s": 29760, "text": "help_text = value" }, { "code": null, "e": 29789, "s": 29778, "text": "Example – " }, { "code": null, "e": 29865, "s": 29789, "text": "field_name = serializers.CharField(help_text = \"Enter only 10 characters\") " }, { "code": null, "e": 30089, "s": 29865, "text": "A value that should be used for pre-populating the value of HTML form fields. It is same as initial – Django Form Field Validation. You may pass a callable to it, just as you may do with any regular Django Field: Syntax – " }, { "code": null, "e": 30105, "s": 30089, "text": "initial = value" }, { "code": null, "e": 30116, "s": 30105, "text": "Example – " }, { "code": null, "e": 30281, "s": 30116, "text": "import datetime\nfrom rest_framework import serializers\nclass ExampleSerializer(serializers.Serializer):\n day = serializers.DateField(initial=datetime.date.today)" }, { "code": null, "e": 30291, "s": 30281, "text": "ruhelaa48" }, { "code": null, "e": 30301, "s": 30291, "text": "kalrap615" }, { "code": null, "e": 30313, "s": 30301, "text": "Django-REST" }, { "code": null, "e": 30328, "s": 30313, "text": "rest-framework" }, { "code": null, "e": 30335, "s": 30328, "text": "Python" }, { "code": null, "e": 30433, "s": 30335, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30442, "s": 30433, "text": "Comments" }, { "code": null, "e": 30455, "s": 30442, "text": "Old Comments" }, { "code": null, "e": 30487, "s": 30455, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30543, "s": 30487, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30585, "s": 30543, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30627, "s": 30585, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30663, "s": 30627, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 30685, "s": 30663, "text": "Defaultdict in Python" }, { "code": null, "e": 30724, "s": 30685, "text": "Python | Get unique values from a list" }, { "code": null, "e": 30751, "s": 30724, "text": "Python Classes and Objects" }, { "code": null, "e": 30782, "s": 30751, "text": "Python | os.path.join() method" } ]
D3.js curveCardinal() Method - GeeksforGeeks
09 Sep, 2020 The curveCardinal() method produces a cubic cardinal spline. The curve is also based on these cubic cardinal splines. Syntax: d3.curveCardinal() Parameters: This method does not accept any parameters. Return Value: This method does not return any value. Example 1: HTML <!DOCTYPE html><html><meta charset="utf-8"> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"> </script></head> <body> <h1 style="text-align:center;color:green;"> GeeksforGeeks </h1> <center> <svg id="gfg" width="200" height="200"></svg> </center> <script> var data = [ { x: 0, y: 0 }, { x: 1, y: 3 }, { x: 2, y: 15 }, { x: 5, y: 15 }, { x: 6, y: 1 }, { x: 7, y: 5 }, { x: 8, y: 1 }]; var xScale = d3.scaleLinear() .domain([0, 8]).range([25, 175]); var yScale = d3.scaleLinear() .domain([0, 20]).range([175, 25]); var line = d3.line() .x((d) => xScale(d.x)) .y((d) => yScale(d.y)) .curve(d3.curveCardinal); d3.select("#gfg") .append("path") .attr("d", line(data)) .attr("fill", "none") .attr("stroke", "green"); </script></body> </html> Output: Example 2: HTML <!DOCTYPE html><html><meta charset="utf-8"> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"> </script></head> <body> <h1 style="text-align:center; color:green;"> GeeksforGeeks </h1> <center> <svg id="gfg" width="200" height="200"></svg> </center> <script> var points = [ { xpoint: 25, ypoint: 150 }, { xpoint: 75, ypoint: 85 }, { xpoint: 100, ypoint: 115 }, { xpoint: 175, ypoint: 25 }, { xpoint: 200, ypoint: 150 }]; var Gen = d3.line() .x((p) => p.xpoint) .y((p) => p.ypoint) .curve(d3.curveCardinal); d3.select("#gfg") .append("path") .attr("d", Gen(points)) .attr("fill", "none") .attr("stroke", "green"); </script></body> </html> Output: D3.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request Remove elements from a JavaScript Array How to get character array from string in JavaScript? How to filter object array based on attributes? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 25300, "s": 25272, "text": "\n09 Sep, 2020" }, { "code": null, "e": 25418, "s": 25300, "text": "The curveCardinal() method produces a cubic cardinal spline. The curve is also based on these cubic cardinal splines." }, { "code": null, "e": 25426, "s": 25418, "text": "Syntax:" }, { "code": null, "e": 25445, "s": 25426, "text": "d3.curveCardinal()" }, { "code": null, "e": 25501, "s": 25445, "text": "Parameters: This method does not accept any parameters." }, { "code": null, "e": 25554, "s": 25501, "text": "Return Value: This method does not return any value." }, { "code": null, "e": 25566, "s": 25554, "text": "Example 1: " }, { "code": null, "e": 25571, "s": 25566, "text": "HTML" }, { "code": "<!DOCTYPE html><html><meta charset=\"utf-8\"> <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js\"> </script></head> <body> <h1 style=\"text-align:center;color:green;\"> GeeksforGeeks </h1> <center> <svg id=\"gfg\" width=\"200\" height=\"200\"></svg> </center> <script> var data = [ { x: 0, y: 0 }, { x: 1, y: 3 }, { x: 2, y: 15 }, { x: 5, y: 15 }, { x: 6, y: 1 }, { x: 7, y: 5 }, { x: 8, y: 1 }]; var xScale = d3.scaleLinear() .domain([0, 8]).range([25, 175]); var yScale = d3.scaleLinear() .domain([0, 20]).range([175, 25]); var line = d3.line() .x((d) => xScale(d.x)) .y((d) => yScale(d.y)) .curve(d3.curveCardinal); d3.select(\"#gfg\") .append(\"path\") .attr(\"d\", line(data)) .attr(\"fill\", \"none\") .attr(\"stroke\", \"green\"); </script></body> </html>", "e": 26601, "s": 25571, "text": null }, { "code": null, "e": 26609, "s": 26601, "text": "Output:" }, { "code": null, "e": 26620, "s": 26609, "text": "Example 2:" }, { "code": null, "e": 26625, "s": 26620, "text": "HTML" }, { "code": "<!DOCTYPE html><html><meta charset=\"utf-8\"> <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js\"> </script></head> <body> <h1 style=\"text-align:center; color:green;\"> GeeksforGeeks </h1> <center> <svg id=\"gfg\" width=\"200\" height=\"200\"></svg> </center> <script> var points = [ { xpoint: 25, ypoint: 150 }, { xpoint: 75, ypoint: 85 }, { xpoint: 100, ypoint: 115 }, { xpoint: 175, ypoint: 25 }, { xpoint: 200, ypoint: 150 }]; var Gen = d3.line() .x((p) => p.xpoint) .y((p) => p.ypoint) .curve(d3.curveCardinal); d3.select(\"#gfg\") .append(\"path\") .attr(\"d\", Gen(points)) .attr(\"fill\", \"none\") .attr(\"stroke\", \"green\"); </script></body> </html>", "e": 27491, "s": 26625, "text": null }, { "code": null, "e": 27499, "s": 27491, "text": "Output:" }, { "code": null, "e": 27505, "s": 27499, "text": "D3.js" }, { "code": null, "e": 27516, "s": 27505, "text": "JavaScript" }, { "code": null, "e": 27533, "s": 27516, "text": "Web Technologies" }, { "code": null, "e": 27631, "s": 27533, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27692, "s": 27631, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27733, "s": 27692, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27773, "s": 27733, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27827, "s": 27773, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 27875, "s": 27827, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 27917, "s": 27875, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27950, "s": 27917, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27993, "s": 27950, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28043, "s": 27993, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python | Check whether two lists are circularly identical - GeeksforGeeks
11 May, 2020 Given two lists, check if they are circularly identical or not. Examples: Input : list1 = [10, 10, 0, 0, 10] list2 = [10, 10, 10, 0, 0] Output : Yes Explanation: yes they are circularly identical as when we write the list1 last index to second last index, then we find it is circularly same with list1 Input : list1 = [10, 10, 10, 0, 0] list2 = [1, 10, 10, 0, 0] Output :No Method 1 : Using List Traversal Using traversal, we have to double the given list. Check for any x(0<=n) to any x+n and compare with list2 to see if the list1 and list2 are same, if both are same then the list2 is circularly identical. Using two loops, check this property. The first loop will run from 0 to len(list1) and then check if the index (x to x+n) is same as list2, if yes then return true, else return false. Below is the Python implementation of the above approach: # python program to check if two # lists are circularly identical# using traversal # function to check circularly identical or notdef circularly_identical(list1, list2): # doubling list list3 = list1 * 2 # traversal in twice of list1 for x in range(0, len(list1)): z = 0 # check if list2 == list1 curcularly for y in range(x, x + len(list1)): if list2[z]== list3[y]: z+= 1 else: break # if all n elements are same circularly if z == len(list1): return True return False # driver codelist1 = [10, 10, 0, 0, 10]list2 = [10, 10, 10, 0, 0]list3 = [1, 10, 10, 0, 0] # check for list 1 and list 2 if(circularly_identical(list1, list2)): print("Yes")else: print("No") # check for list 2 and list 3 if(circularly_identical(list2, list3)): print ("Yes") else: print ("No") Yes No Method 2 : Using List Slicing # python program to check if two # lists are circularly identical# using traversal # function to check circularly identical or notdef circularly_identical(list1, list2): # doubling list list1.extend(list1) # traversal in twice of list1 for i in range(len(list1)): # check if sliced list1 is equal to list2 if list2 == list1[i: i + len(list2)]: return True return False # driver codelist1 = [10, 10, 0, 0, 10]list2 = [10, 10, 10, 0, 0]list3 = [1, 10, 10, 0, 0] # check for list 1 and list 2 if(circularly_identical(list1, list2)): print("Yes")else: print("No") # check for list 2 and list 3 if(circularly_identical(list2, list3)): print ("Yes") else: print ("No") Yes No Method 3 : Using map() function Using Python’s inbuilt function map() we can do this in one single step, where we have to map list2 in a string and then see if it exists in the mapping of twice of list1 (2*list1) in another string. Below is the Python implementation of the above approach: # python program to check if two # lists are circularly identical# using map function # function to check circularly identical or notdef circularly_identical(list1, list2): return(' '.join(map(str, list2)) in ' '.join(map(str, list1 * 2))) # driver codelist1 = [10, 10, 0, 0, 10]list2 = [10, 10, 10, 0, 0]list3 = [1, 10, 10, 0, 0] # check for list 1 and list 2 if (circularly_identical(list1, list2)): print("Yes")else: print("No") # check for list 2 and list 3 if(circularly_identical(list2, list3)): print ("Yes") else: print ("No") Yes No nikhilk26 circular-array Python list-programs python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Box Plot in Python using Matplotlib Bar Plot in Matplotlib Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Python - Call function from another file loops in python Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method Python Lambda Functions
[ { "code": null, "e": 23925, "s": 23897, "text": "\n11 May, 2020" }, { "code": null, "e": 23989, "s": 23925, "text": "Given two lists, check if they are circularly identical or not." }, { "code": null, "e": 23999, "s": 23989, "text": "Examples:" }, { "code": null, "e": 24343, "s": 23999, "text": "Input : list1 = [10, 10, 0, 0, 10]\n list2 = [10, 10, 10, 0, 0]\nOutput : Yes\nExplanation: yes they are circularly identical as when we write the list1\n last index to second last index, then we find it is circularly\n same with list1 \nInput : list1 = [10, 10, 10, 0, 0]\n list2 = [1, 10, 10, 0, 0]\nOutput :No\n" }, { "code": null, "e": 24375, "s": 24343, "text": "Method 1 : Using List Traversal" }, { "code": null, "e": 24763, "s": 24375, "text": "Using traversal, we have to double the given list. Check for any x(0<=n) to any x+n and compare with list2 to see if the list1 and list2 are same, if both are same then the list2 is circularly identical. Using two loops, check this property. The first loop will run from 0 to len(list1) and then check if the index (x to x+n) is same as list2, if yes then return true, else return false." }, { "code": null, "e": 24821, "s": 24763, "text": "Below is the Python implementation of the above approach:" }, { "code": "# python program to check if two # lists are circularly identical# using traversal # function to check circularly identical or notdef circularly_identical(list1, list2): # doubling list list3 = list1 * 2 # traversal in twice of list1 for x in range(0, len(list1)): z = 0 # check if list2 == list1 curcularly for y in range(x, x + len(list1)): if list2[z]== list3[y]: z+= 1 else: break # if all n elements are same circularly if z == len(list1): return True return False # driver codelist1 = [10, 10, 0, 0, 10]list2 = [10, 10, 10, 0, 0]list3 = [1, 10, 10, 0, 0] # check for list 1 and list 2 if(circularly_identical(list1, list2)): print(\"Yes\")else: print(\"No\") # check for list 2 and list 3 if(circularly_identical(list2, list3)): print (\"Yes\") else: print (\"No\") ", "e": 25775, "s": 24821, "text": null }, { "code": null, "e": 25783, "s": 25775, "text": "Yes\nNo\n" }, { "code": null, "e": 25813, "s": 25783, "text": "Method 2 : Using List Slicing" }, { "code": "# python program to check if two # lists are circularly identical# using traversal # function to check circularly identical or notdef circularly_identical(list1, list2): # doubling list list1.extend(list1) # traversal in twice of list1 for i in range(len(list1)): # check if sliced list1 is equal to list2 if list2 == list1[i: i + len(list2)]: return True return False # driver codelist1 = [10, 10, 0, 0, 10]list2 = [10, 10, 10, 0, 0]list3 = [1, 10, 10, 0, 0] # check for list 1 and list 2 if(circularly_identical(list1, list2)): print(\"Yes\")else: print(\"No\") # check for list 2 and list 3 if(circularly_identical(list2, list3)): print (\"Yes\") else: print (\"No\") ", "e": 26526, "s": 25813, "text": null }, { "code": null, "e": 26534, "s": 26526, "text": "Yes\nNo\n" }, { "code": null, "e": 26566, "s": 26534, "text": "Method 3 : Using map() function" }, { "code": null, "e": 26766, "s": 26566, "text": "Using Python’s inbuilt function map() we can do this in one single step, where we have to map list2 in a string and then see if it exists in the mapping of twice of list1 (2*list1) in another string." }, { "code": null, "e": 26824, "s": 26766, "text": "Below is the Python implementation of the above approach:" }, { "code": "# python program to check if two # lists are circularly identical# using map function # function to check circularly identical or notdef circularly_identical(list1, list2): return(' '.join(map(str, list2)) in ' '.join(map(str, list1 * 2))) # driver codelist1 = [10, 10, 0, 0, 10]list2 = [10, 10, 10, 0, 0]list3 = [1, 10, 10, 0, 0] # check for list 1 and list 2 if (circularly_identical(list1, list2)): print(\"Yes\")else: print(\"No\") # check for list 2 and list 3 if(circularly_identical(list2, list3)): print (\"Yes\") else: print (\"No\") ", "e": 27393, "s": 26824, "text": null }, { "code": null, "e": 27401, "s": 27393, "text": "Yes\nNo\n" }, { "code": null, "e": 27411, "s": 27401, "text": "nikhilk26" }, { "code": null, "e": 27426, "s": 27411, "text": "circular-array" }, { "code": null, "e": 27447, "s": 27426, "text": "Python list-programs" }, { "code": null, "e": 27459, "s": 27447, "text": "python-list" }, { "code": null, "e": 27466, "s": 27459, "text": "Python" }, { "code": null, "e": 27478, "s": 27466, "text": "python-list" }, { "code": null, "e": 27576, "s": 27478, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27585, "s": 27576, "text": "Comments" }, { "code": null, "e": 27598, "s": 27585, "text": "Old Comments" }, { "code": null, "e": 27634, "s": 27598, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 27657, "s": 27634, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 27696, "s": 27657, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27729, "s": 27696, "text": "Python | Convert set into a list" }, { "code": null, "e": 27778, "s": 27729, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 27819, "s": 27778, "text": "Python - Call function from another file" }, { "code": null, "e": 27835, "s": 27819, "text": "loops in python" }, { "code": null, "e": 27886, "s": 27835, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 27918, "s": 27886, "text": "Python Dictionary keys() method" } ]