title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Mapping the letter of a string to an object of arrays - JavaScript
|
Given a string, we are required to write a function that creates an object that stores the indexes of each letter in an array. The letters (elements) of the string must be the keys of object
The indexes should be stored in an array and those arrays are values.
For example −
If the input string is −
const str = 'cannot';
Then the output should be −
const output = {
'c': [0],
'a': [1],
'n': [2, 3],
'o': [4],
't': [5]
};
Following is the code −
const str = 'cannot';
const mapString = str => {
const map = {};
for(let i = 0; i < str.length; i++){
if(map.hasOwnProperty(str[i])){
map[str[i]] = map[str[i]].concat(i);
}else{
map[str[i]] = [i];
};
};
return map;
};
console.log(mapString(str));
Following is the output in the console −
{ c: [ 0 ], a: [ 1 ], n: [ 2, 3 ], o: [ 4 ], t: [ 5 ] }
|
[
{
"code": null,
"e": 1253,
"s": 1062,
"text": "Given a string, we are required to write a function that creates an object that stores the indexes of each letter in an array. The letters (elements) of the string must be the keys of object"
},
{
"code": null,
"e": 1323,
"s": 1253,
"text": "The indexes should be stored in an array and those arrays are values."
},
{
"code": null,
"e": 1337,
"s": 1323,
"text": "For example −"
},
{
"code": null,
"e": 1362,
"s": 1337,
"text": "If the input string is −"
},
{
"code": null,
"e": 1384,
"s": 1362,
"text": "const str = 'cannot';"
},
{
"code": null,
"e": 1412,
"s": 1384,
"text": "Then the output should be −"
},
{
"code": null,
"e": 1499,
"s": 1412,
"text": "const output = {\n 'c': [0],\n 'a': [1],\n 'n': [2, 3],\n 'o': [4],\n 't': [5]\n};"
},
{
"code": null,
"e": 1523,
"s": 1499,
"text": "Following is the code −"
},
{
"code": null,
"e": 1818,
"s": 1523,
"text": "const str = 'cannot';\nconst mapString = str => {\n const map = {};\n for(let i = 0; i < str.length; i++){\n if(map.hasOwnProperty(str[i])){\n map[str[i]] = map[str[i]].concat(i);\n }else{\n map[str[i]] = [i];\n };\n };\n return map;\n};\nconsole.log(mapString(str));"
},
{
"code": null,
"e": 1859,
"s": 1818,
"text": "Following is the output in the console −"
},
{
"code": null,
"e": 1915,
"s": 1859,
"text": "{ c: [ 0 ], a: [ 1 ], n: [ 2, 3 ], o: [ 4 ], t: [ 5 ] }"
}
] |
Python program to sort a list of tuples alphabetically - GeeksforGeeks
|
11 May, 2020
Given a list of tuples, write a Python program to sort the tuples alphabetically by the first item of each tuple.
Examples:
Input: [("Amana", 28), ("Zenat", 30), ("Abhishek", 29), ("Nikhil", 21), ("B", "C")]
Output: [('Amana', 28), ('Abhishek', 29), ('B', 'C'), ('Nikhil', 21), ('Zenat', 30)]
Input: [("aaaa", 28), ("aa", 30), ("bab", 29), ("bb", 21), ("csa", "C")]
Output: [('aa', 30), ('aaaa', 28), ('bab', 29), ('bb', 21), ('csa', 'C')]
Method 1: Using Bubble sortUsing the technique of Bubble Sort to we can perform the sorting. Note that each tuple is an element in the given list. Access the first element of each tuple using the nested loops. This performs the in-place method of sorting. The time complexity is similar to the Bubble Sort i.e. O(n^2).
# Python program to sort a# list of tuples alphabetically # Function to sort the list of# tuples def SortTuple(tup): # Getting the length of list # of tuples n = len(tup) for i in range(n): for j in range(n-i-1): if tup[j][0] > tup[j + 1][0]: tup[j], tup[j + 1] = tup[j + 1], tup[j] return tup # Driver's code tup = [("Amana", 28), ("Zenat", 30), ("Abhishek", 29), ("Nikhil", 21), ("B", "C")] print(SortTuple(tup))
Output:
[('Abhishek', 29), ('Amana', 28), ('B', 'C'), ('Nikhil', 21), ('Zenat', 30)]
Method 2: Using sort() methodWhile sorting via this method the actual content of the tuple is changed, and just like the previous method, the in-place method of the sort is performed.
# Python program to sort a list of # tuples using sort() # Function to sort the listdef SortTuple(tup): # reverse = None (Sorts in Ascending order) # key is set to sort using first element of # sublist lambda has been used tup.sort(key = lambda x: x[0]) return tup # Driver's code tup = [("Amana", 28), ("Zenat", 30), ("Abhishek", 29), ("Nikhil", 21), ("B", "C")] print(SortTuple(tup))
Output:
[('Abhishek', 29), ('Amana', 28), ('B', 'C'), ('Nikhil', 21), ('Zenat', 30)]
Method 3: Using sorted() method
sorted() method is a method of list class that returns the sorted list without making any changes to the original list.
# Python program to sort a list of # tuples using sorted() # Function to sort the listdef Sort_Tuple(tup): # reverse = None (Sorts in Ascending order) # key is set to sort using first element of # sublist lambda has been used return(sorted(tup, key = lambda x: x[0])) # Driver Code tup = [("Amana", 28), ("Zenat", 30), ("Abhishek", 29), ("Nikhil", 21), ("B", "C")] # printing the sorted list of tuples print(Sort_Tuple(tup))
Output:
[('Abhishek', 29), ('Amana', 28), ('B', 'C'), ('Nikhil', 21), ('Zenat', 30)]
Python tuple-programs
Python-sort
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": 26191,
"s": 26163,
"text": "\n11 May, 2020"
},
{
"code": null,
"e": 26305,
"s": 26191,
"text": "Given a list of tuples, write a Python program to sort the tuples alphabetically by the first item of each tuple."
},
{
"code": null,
"e": 26315,
"s": 26305,
"text": "Examples:"
},
{
"code": null,
"e": 26633,
"s": 26315,
"text": "Input: [(\"Amana\", 28), (\"Zenat\", 30), (\"Abhishek\", 29), (\"Nikhil\", 21), (\"B\", \"C\")]\nOutput: [('Amana', 28), ('Abhishek', 29), ('B', 'C'), ('Nikhil', 21), ('Zenat', 30)]\n\nInput: [(\"aaaa\", 28), (\"aa\", 30), (\"bab\", 29), (\"bb\", 21), (\"csa\", \"C\")]\nOutput: [('aa', 30), ('aaaa', 28), ('bab', 29), ('bb', 21), ('csa', 'C')]\n"
},
{
"code": null,
"e": 26952,
"s": 26633,
"text": "Method 1: Using Bubble sortUsing the technique of Bubble Sort to we can perform the sorting. Note that each tuple is an element in the given list. Access the first element of each tuple using the nested loops. This performs the in-place method of sorting. The time complexity is similar to the Bubble Sort i.e. O(n^2)."
},
{
"code": "# Python program to sort a# list of tuples alphabetically # Function to sort the list of# tuples def SortTuple(tup): # Getting the length of list # of tuples n = len(tup) for i in range(n): for j in range(n-i-1): if tup[j][0] > tup[j + 1][0]: tup[j], tup[j + 1] = tup[j + 1], tup[j] return tup # Driver's code tup = [(\"Amana\", 28), (\"Zenat\", 30), (\"Abhishek\", 29), (\"Nikhil\", 21), (\"B\", \"C\")] print(SortTuple(tup))",
"e": 27486,
"s": 26952,
"text": null
},
{
"code": null,
"e": 27494,
"s": 27486,
"text": "Output:"
},
{
"code": null,
"e": 27572,
"s": 27494,
"text": "[('Abhishek', 29), ('Amana', 28), ('B', 'C'), ('Nikhil', 21), ('Zenat', 30)]\n"
},
{
"code": null,
"e": 27756,
"s": 27572,
"text": "Method 2: Using sort() methodWhile sorting via this method the actual content of the tuple is changed, and just like the previous method, the in-place method of the sort is performed."
},
{
"code": "# Python program to sort a list of # tuples using sort() # Function to sort the listdef SortTuple(tup): # reverse = None (Sorts in Ascending order) # key is set to sort using first element of # sublist lambda has been used tup.sort(key = lambda x: x[0]) return tup # Driver's code tup = [(\"Amana\", 28), (\"Zenat\", 30), (\"Abhishek\", 29), (\"Nikhil\", 21), (\"B\", \"C\")] print(SortTuple(tup))",
"e": 28200,
"s": 27756,
"text": null
},
{
"code": null,
"e": 28208,
"s": 28200,
"text": "Output:"
},
{
"code": null,
"e": 28286,
"s": 28208,
"text": "[('Abhishek', 29), ('Amana', 28), ('B', 'C'), ('Nikhil', 21), ('Zenat', 30)]\n"
},
{
"code": null,
"e": 28318,
"s": 28286,
"text": "Method 3: Using sorted() method"
},
{
"code": null,
"e": 28438,
"s": 28318,
"text": "sorted() method is a method of list class that returns the sorted list without making any changes to the original list."
},
{
"code": "# Python program to sort a list of # tuples using sorted() # Function to sort the listdef Sort_Tuple(tup): # reverse = None (Sorts in Ascending order) # key is set to sort using first element of # sublist lambda has been used return(sorted(tup, key = lambda x: x[0])) # Driver Code tup = [(\"Amana\", 28), (\"Zenat\", 30), (\"Abhishek\", 29), (\"Nikhil\", 21), (\"B\", \"C\")] # printing the sorted list of tuples print(Sort_Tuple(tup)) ",
"e": 28910,
"s": 28438,
"text": null
},
{
"code": null,
"e": 28918,
"s": 28910,
"text": "Output:"
},
{
"code": null,
"e": 28996,
"s": 28918,
"text": "[('Abhishek', 29), ('Amana', 28), ('B', 'C'), ('Nikhil', 21), ('Zenat', 30)]\n"
},
{
"code": null,
"e": 29018,
"s": 28996,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 29030,
"s": 29018,
"text": "Python-sort"
},
{
"code": null,
"e": 29037,
"s": 29030,
"text": "Python"
},
{
"code": null,
"e": 29053,
"s": 29037,
"text": "Python Programs"
},
{
"code": null,
"e": 29151,
"s": 29053,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29169,
"s": 29151,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29204,
"s": 29169,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29236,
"s": 29204,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29258,
"s": 29236,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29300,
"s": 29258,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29343,
"s": 29300,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 29365,
"s": 29343,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29404,
"s": 29365,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 29450,
"s": 29404,
"text": "Python | Split string into list of characters"
}
] |
Ordinary Least Squares (OLS) using statsmodels - GeeksforGeeks
|
10 Mar, 2022
In this article, we will use Python’s statsmodels module to implement Ordinary Least Squares(OLS) method of linear regression.Introduction : A linear regression model establishes the relation between a dependent variable(y) and at least one independent variable(x) as : In OLS method, we have to choose the values of and such that, the total sum of squares of the difference between the calculated and observed values of y, is minimised. Formula for OLS:Where, = predicted value for the ith observation = actual value for the ith observation = error/residual for the ith observation n = total number of observationsTo get the values of and which minimise S, we can take a partial derivative for each coefficient and equate it to zero.Modules used :
statsmodels : provides classes and functions for the estimation of many different statistical models.
pip install statsmodels
pandas : library used for data manipulation and analysis.
NumPy : core library for array computing.
Matplotlib : a comprehensive library used for creating static and interactive graphs and visualisations.
Approach :
First we define the variables x and y. In the example below, the variables are read from a csv file using pandas. The file used in the example can be downloaded here.
Next, We need to add the constant to the equation using the add_constant() method.
The OLS() function of the statsmodels.api module is used to perform OLS regression. It returns an OLS object. Then fit() method is called on this object for fitting the regression line to the data.
The summary() method is used to obtain a table which gives an extensive description about the regression results
Syntax : statsmodels.api.OLS(y, x) Parameters :
y : the variable which is dependent on x
x : the independent variable
Code:
Python3
import statsmodels.api as smimport pandas as pd # reading data from the csvdata = pd.read_csv('train.csv') # defining the variablesx = data['x'].tolist()y = data['y'].tolist() # adding the constant termx = sm.add_constant(x) # performing the regression# and fitting the modelresult = sm.OLS(y, x).fit() # printing the summary tableprint(result.summary())
Output :
OLS Regression Results
==============================================================================
Dep. Variable: y R-squared: 0.989
Model: OLS Adj. R-squared: 0.989
Method: Least Squares F-statistic: 2.709e+04
Date: Fri, 26 Jun 2020 Prob (F-statistic): 1.33e-294
Time: 15:55:38 Log-Likelihood: -757.98
No. Observations: 300 AIC: 1520.
Df Residuals: 298 BIC: 1527.
Df Model: 1
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
const -0.4618 0.360 -1.284 0.200 -1.169 0.246
x1 1.0143 0.006 164.598 0.000 1.002 1.026
==============================================================================
Omnibus: 1.034 Durbin-Watson: 2.006
Prob(Omnibus): 0.596 Jarque-Bera (JB): 0.825
Skew: 0.117 Prob(JB): 0.662
Kurtosis: 3.104 Cond. No. 120.
==============================================================================
Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
Description of some of the terms in the table :
R-squared : the coefficient of determination. It is the proportion of the variance in the dependent variable that is predictable/explained
Adj. R-squared : Adjusted R-squared is the modified form of R-squared adjusted for the number of independent variables in the model. Value of adj. R-squared increases, when we include extra variables which actually improve the model.
F-statistic : the ratio of mean squared error of the model to the mean squared error of residuals. It determines the overall significance of the model.
coef : the coefficients of the independent variables and the constant term in the equation.
t : the value of t-statistic. It is the ratio of the difference between the estimated and hypothesized value of a parameter, to the standard error
Predicting values: From the results table, we note the coefficient of x and the constant term. These values are substituted in the original equation and the regression line is plotted using matplotlib. Code:
Python3
import pandas as pdimport matplotlib.pyplot as pltimport numpy as np # reading data from the csvdata = pd.read_csv('train.csv') # plotting the original valuesx = data['x'].tolist()y = data['y'].tolist()plt.scatter(x, y) # finding the maximum and minimum# values of x, to get the# range of datamax_x = data['x'].max()min_x = data['x'].min() # range of values for plotting# the regression linex = np.arange(min_x, max_x, 1) # the substituted equationy = 1.0143 * x - 0.4618 # plotting the regression lineplt.plot(y, 'r')plt.show()
Output:
rkbhola5
data-science
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
Convert integer to string in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
sum() function in Python
|
[
{
"code": null,
"e": 26024,
"s": 25996,
"text": "\n10 Mar, 2022"
},
{
"code": null,
"e": 26775,
"s": 26024,
"text": "In this article, we will use Python’s statsmodels module to implement Ordinary Least Squares(OLS) method of linear regression.Introduction : A linear regression model establishes the relation between a dependent variable(y) and at least one independent variable(x) as : In OLS method, we have to choose the values of and such that, the total sum of squares of the difference between the calculated and observed values of y, is minimised. Formula for OLS:Where, = predicted value for the ith observation = actual value for the ith observation = error/residual for the ith observation n = total number of observationsTo get the values of and which minimise S, we can take a partial derivative for each coefficient and equate it to zero.Modules used : "
},
{
"code": null,
"e": 26879,
"s": 26775,
"text": "statsmodels : provides classes and functions for the estimation of many different statistical models. "
},
{
"code": null,
"e": 26903,
"s": 26879,
"text": "pip install statsmodels"
},
{
"code": null,
"e": 26965,
"s": 26905,
"text": "pandas : library used for data manipulation and analysis. "
},
{
"code": null,
"e": 27013,
"s": 26969,
"text": "NumPy : core library for array computing. "
},
{
"code": null,
"e": 27124,
"s": 27017,
"text": "Matplotlib : a comprehensive library used for creating static and interactive graphs and visualisations. "
},
{
"code": null,
"e": 27140,
"s": 27128,
"text": "Approach : "
},
{
"code": null,
"e": 27309,
"s": 27140,
"text": "First we define the variables x and y. In the example below, the variables are read from a csv file using pandas. The file used in the example can be downloaded here. "
},
{
"code": null,
"e": 27392,
"s": 27309,
"text": "Next, We need to add the constant to the equation using the add_constant() method."
},
{
"code": null,
"e": 27590,
"s": 27392,
"text": "The OLS() function of the statsmodels.api module is used to perform OLS regression. It returns an OLS object. Then fit() method is called on this object for fitting the regression line to the data."
},
{
"code": null,
"e": 27703,
"s": 27590,
"text": "The summary() method is used to obtain a table which gives an extensive description about the regression results"
},
{
"code": null,
"e": 27755,
"s": 27705,
"text": "Syntax : statsmodels.api.OLS(y, x) Parameters : "
},
{
"code": null,
"e": 27796,
"s": 27755,
"text": "y : the variable which is dependent on x"
},
{
"code": null,
"e": 27825,
"s": 27796,
"text": "x : the independent variable"
},
{
"code": null,
"e": 27835,
"s": 27827,
"text": "Code: "
},
{
"code": null,
"e": 27843,
"s": 27835,
"text": "Python3"
},
{
"code": "import statsmodels.api as smimport pandas as pd # reading data from the csvdata = pd.read_csv('train.csv') # defining the variablesx = data['x'].tolist()y = data['y'].tolist() # adding the constant termx = sm.add_constant(x) # performing the regression# and fitting the modelresult = sm.OLS(y, x).fit() # printing the summary tableprint(result.summary())",
"e": 28198,
"s": 27843,
"text": null
},
{
"code": null,
"e": 28209,
"s": 28198,
"text": "Output : "
},
{
"code": null,
"e": 30050,
"s": 28209,
"text": " OLS Regression Results \n==============================================================================\nDep. Variable: y R-squared: 0.989\nModel: OLS Adj. R-squared: 0.989\nMethod: Least Squares F-statistic: 2.709e+04\nDate: Fri, 26 Jun 2020 Prob (F-statistic): 1.33e-294\nTime: 15:55:38 Log-Likelihood: -757.98\nNo. Observations: 300 AIC: 1520.\nDf Residuals: 298 BIC: 1527.\nDf Model: 1 \nCovariance Type: nonrobust \n==============================================================================\n coef std err t P>|t| [0.025 0.975]\n------------------------------------------------------------------------------\nconst -0.4618 0.360 -1.284 0.200 -1.169 0.246\nx1 1.0143 0.006 164.598 0.000 1.002 1.026\n==============================================================================\nOmnibus: 1.034 Durbin-Watson: 2.006\nProb(Omnibus): 0.596 Jarque-Bera (JB): 0.825\nSkew: 0.117 Prob(JB): 0.662\nKurtosis: 3.104 Cond. No. 120.\n==============================================================================\n\nWarnings:\n[1] Standard Errors assume that the covariance matrix of the errors is correctly specified."
},
{
"code": null,
"e": 30100,
"s": 30050,
"text": "Description of some of the terms in the table : "
},
{
"code": null,
"e": 30239,
"s": 30100,
"text": "R-squared : the coefficient of determination. It is the proportion of the variance in the dependent variable that is predictable/explained"
},
{
"code": null,
"e": 30473,
"s": 30239,
"text": "Adj. R-squared : Adjusted R-squared is the modified form of R-squared adjusted for the number of independent variables in the model. Value of adj. R-squared increases, when we include extra variables which actually improve the model."
},
{
"code": null,
"e": 30625,
"s": 30473,
"text": "F-statistic : the ratio of mean squared error of the model to the mean squared error of residuals. It determines the overall significance of the model."
},
{
"code": null,
"e": 30717,
"s": 30625,
"text": "coef : the coefficients of the independent variables and the constant term in the equation."
},
{
"code": null,
"e": 30864,
"s": 30717,
"text": "t : the value of t-statistic. It is the ratio of the difference between the estimated and hypothesized value of a parameter, to the standard error"
},
{
"code": null,
"e": 31074,
"s": 30864,
"text": "Predicting values: From the results table, we note the coefficient of x and the constant term. These values are substituted in the original equation and the regression line is plotted using matplotlib. Code: "
},
{
"code": null,
"e": 31082,
"s": 31074,
"text": "Python3"
},
{
"code": "import pandas as pdimport matplotlib.pyplot as pltimport numpy as np # reading data from the csvdata = pd.read_csv('train.csv') # plotting the original valuesx = data['x'].tolist()y = data['y'].tolist()plt.scatter(x, y) # finding the maximum and minimum# values of x, to get the# range of datamax_x = data['x'].max()min_x = data['x'].min() # range of values for plotting# the regression linex = np.arange(min_x, max_x, 1) # the substituted equationy = 1.0143 * x - 0.4618 # plotting the regression lineplt.plot(y, 'r')plt.show()",
"e": 31611,
"s": 31082,
"text": null
},
{
"code": null,
"e": 31621,
"s": 31611,
"text": "Output: "
},
{
"code": null,
"e": 31632,
"s": 31623,
"text": "rkbhola5"
},
{
"code": null,
"e": 31645,
"s": 31632,
"text": "data-science"
},
{
"code": null,
"e": 31652,
"s": 31645,
"text": "Python"
},
{
"code": null,
"e": 31750,
"s": 31652,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31768,
"s": 31750,
"text": "Python Dictionary"
},
{
"code": null,
"e": 31800,
"s": 31768,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31822,
"s": 31800,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 31864,
"s": 31822,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 31890,
"s": 31864,
"text": "Python String | replace()"
},
{
"code": null,
"e": 31919,
"s": 31890,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 31955,
"s": 31919,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 31992,
"s": 31955,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 32034,
"s": 31992,
"text": "Check if element exists in list in Python"
}
] |
One Hot Encoding using Tensorflow - GeeksforGeeks
|
02 Sep, 2020
In this post, we will be seeing how to initialize a vector in TensorFlow with all zeros or ones. The function you will be calling is tf.ones(). To initialize with zeros you could use tf.zeros() instead. These functions take in a shape and return an array full of zeros and ones accordingly.
Code:
import tensorflow as tf ones_matrix = tf.ones([2, 3])sess = tf.Session()ones = sess.run(ones_matrix)sess.close() print(ones)
Output:
[[1. 1. 1.] [1. 1. 1.]]
Using One Hot Encoding:Many times in deep learning and general vector computations you will have a y vector with numbers ranging from 0 to C-1 and you want to do the following conversion. If C is for example 5, then you might have the following y vector which you will need to convert as follows:
One Hot Encoding Example
This can be done as follows:
Parameters passed to the function:
indices: A Tensor of indices.depth: A scalar defining the depth of the one hot dimension.on_value: A scalar defining the value to fill in output when indices[j] = i. (default : 1)off_value: A scalar defining the value to fill in output when indices[j] != i. (default : 0)axis: The axis to fill (default : -1, a new inner-most axis).dtype: The data type of the output tensor.name: A name for the operation (optional).
Code:
indices = [1, 4, 2, 0, 3]C = tf.constant(5, name = "C") one_hot_matrix = tf.one_hot( indices, C, on_value = 1.0, off_value = 0.0, axis =-1) sess = tf.Session() one_hot = sess.run(one_hot_matrix) sess.close() # output is of dimension 5 x 5print(one_hot)
Output:
[[0.0, 1.0, 0.0, 0.0, 0.0 ]
[0.0, 0.0, 0.0, 0.0, 1.0]
[0.0, 0.0, 1.0, 0.0, 0.0]
[1.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 1.0, 0.0]]
Feel free to change values and see the result.
Code:
indices = [[0, 2], [1, -1]]C = tf.constant(5, name = "C") one_hot_matrix = tf.one_hot( indices, C, on_value = 1.0, off_value = 0.0, axis =-1) sess = tf.Session() one_hot = sess.run(one_hot_matrix) sess.close() # output is of dimension 2 x 2 x 3print(one_hot)
Output :
[[[1.0, 0.0, 0.0],
[0.0, 0.0, 1.0]],
[[0.0, 1.0, 0.0],
[0.0, 0.0, 0.0]]]
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Reinforcement learning
Activation functions in Neural Networks
Introduction to Recurrent Neural Network
Decision Tree Introduction with example
Support Vector Machine Algorithm
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 26011,
"s": 25983,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 26302,
"s": 26011,
"text": "In this post, we will be seeing how to initialize a vector in TensorFlow with all zeros or ones. The function you will be calling is tf.ones(). To initialize with zeros you could use tf.zeros() instead. These functions take in a shape and return an array full of zeros and ones accordingly."
},
{
"code": null,
"e": 26308,
"s": 26302,
"text": "Code:"
},
{
"code": "import tensorflow as tf ones_matrix = tf.ones([2, 3])sess = tf.Session()ones = sess.run(ones_matrix)sess.close() print(ones)",
"e": 26435,
"s": 26308,
"text": null
},
{
"code": null,
"e": 26443,
"s": 26435,
"text": "Output:"
},
{
"code": null,
"e": 26468,
"s": 26443,
"text": "[[1. 1. 1.] [1. 1. 1.]]"
},
{
"code": null,
"e": 26765,
"s": 26468,
"text": "Using One Hot Encoding:Many times in deep learning and general vector computations you will have a y vector with numbers ranging from 0 to C-1 and you want to do the following conversion. If C is for example 5, then you might have the following y vector which you will need to convert as follows:"
},
{
"code": null,
"e": 26790,
"s": 26765,
"text": "One Hot Encoding Example"
},
{
"code": null,
"e": 26819,
"s": 26790,
"text": "This can be done as follows:"
},
{
"code": null,
"e": 26854,
"s": 26819,
"text": "Parameters passed to the function:"
},
{
"code": null,
"e": 27271,
"s": 26854,
"text": "indices: A Tensor of indices.depth: A scalar defining the depth of the one hot dimension.on_value: A scalar defining the value to fill in output when indices[j] = i. (default : 1)off_value: A scalar defining the value to fill in output when indices[j] != i. (default : 0)axis: The axis to fill (default : -1, a new inner-most axis).dtype: The data type of the output tensor.name: A name for the operation (optional)."
},
{
"code": null,
"e": 27277,
"s": 27271,
"text": "Code:"
},
{
"code": "indices = [1, 4, 2, 0, 3]C = tf.constant(5, name = \"C\") one_hot_matrix = tf.one_hot( indices, C, on_value = 1.0, off_value = 0.0, axis =-1) sess = tf.Session() one_hot = sess.run(one_hot_matrix) sess.close() # output is of dimension 5 x 5print(one_hot)",
"e": 27542,
"s": 27277,
"text": null
},
{
"code": null,
"e": 27550,
"s": 27542,
"text": "Output:"
},
{
"code": null,
"e": 27687,
"s": 27550,
"text": "[[0.0, 1.0, 0.0, 0.0, 0.0 ]\n\n[0.0, 0.0, 0.0, 0.0, 1.0]\n\n[0.0, 0.0, 1.0, 0.0, 0.0]\n\n[1.0, 0.0, 0.0, 0.0, 0.0]\n\n[0.0, 0.0, 0.0, 1.0, 0.0]]"
},
{
"code": null,
"e": 27734,
"s": 27687,
"text": "Feel free to change values and see the result."
},
{
"code": null,
"e": 27740,
"s": 27734,
"text": "Code:"
},
{
"code": "indices = [[0, 2], [1, -1]]C = tf.constant(5, name = \"C\") one_hot_matrix = tf.one_hot( indices, C, on_value = 1.0, off_value = 0.0, axis =-1) sess = tf.Session() one_hot = sess.run(one_hot_matrix) sess.close() # output is of dimension 2 x 2 x 3print(one_hot) ",
"e": 28016,
"s": 27740,
"text": null
},
{
"code": null,
"e": 28025,
"s": 28016,
"text": "Output :"
},
{
"code": null,
"e": 28112,
"s": 28025,
"text": "[[[1.0, 0.0, 0.0], \n\n [0.0, 0.0, 1.0]], \n\n [[0.0, 1.0, 0.0], \n\n [0.0, 0.0, 0.0]]] "
},
{
"code": null,
"e": 28129,
"s": 28112,
"text": "Machine Learning"
},
{
"code": null,
"e": 28136,
"s": 28129,
"text": "Python"
},
{
"code": null,
"e": 28153,
"s": 28136,
"text": "Machine Learning"
},
{
"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": 28274,
"s": 28251,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 28314,
"s": 28274,
"text": "Activation functions in Neural Networks"
},
{
"code": null,
"e": 28355,
"s": 28314,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 28395,
"s": 28355,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 28428,
"s": 28395,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 28456,
"s": 28428,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 28506,
"s": 28456,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 28528,
"s": 28506,
"text": "Python map() function"
}
] |
Sets difference() function | Guava | Java - GeeksforGeeks
|
15 Nov, 2018
Guava’s Sets.difference() returns an unmodifiable view of the difference of two sets.
Syntax:
public static <E>
Sets.SetView<E>
difference(Set<E> set1,
Set<?> set2)
Return Value: This method returns a set containing all elements that are contained by set1 and not contained by set2.
Note: Set2 may also contain elements not present in set1, these are simply ignored. The iteration order of the returned set matches that of set1.
Example 1:
// Java code to show implementation of// Guava's Sets.difference() method import com.google.common.collect.Sets;import java.util.Set; class GFG { // Driver's code public static void main(String[] args) { // Creating first set named set1 Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5, 6); // Creating second set named set2 Set<Integer> set2 = Sets.newHashSet(1, 3, 5, 7); // Using Guava's Sets.difference() method Set<Integer> diff = Sets.difference(set1, set2); // Displaying the unmodifiable view of // the difference of two sets. System.out.println("Set 1: " + set1); System.out.println("Set 2: " + set2); System.out.println("Difference between " + "Set 1 and Set 2: " + diff); }}
Set 1: [1, 2, 3, 4, 5, 6]
Set 2: [1, 3, 5, 7]
Difference between Set 1 and Set 2: [2, 4, 6]
Example 2 :
// Java code to show implementation of// Guava's Sets.difference() method import com.google.common.collect.Sets;import java.util.Set; class GFG { // Driver's code public static void main(String[] args) { // Creating first set named set1 Set<String> set1 = Sets .newHashSet("H", "E", "L", "L", "O", "G"); // Creating second set named set2 Set<String> set2 = Sets .newHashSet("L", "I", "K", "E", "G"); // Using Guava's Sets.difference() method Set<String> diff = Sets.difference(set1, set2); // Displaying the unmodifiable view of // the difference of two sets. System.out.println("Set 1: " + set1); System.out.println("Set 2: " + set2); System.out.println("Difference between " + "Set 1 and Set 2: " + diff); }}
Set 1: [E, G, H, L, O]
Set 2: [I, K, L, E, G]
Difference between Set 1 and Set 2: [H, O]
java-guava
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Internal Working of HashMap in Java
Comparator Interface in Java with Examples
Strings in Java
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n15 Nov, 2018"
},
{
"code": null,
"e": 25311,
"s": 25225,
"text": "Guava’s Sets.difference() returns an unmodifiable view of the difference of two sets."
},
{
"code": null,
"e": 25319,
"s": 25311,
"text": "Syntax:"
},
{
"code": null,
"e": 25414,
"s": 25319,
"text": "public static <E> \n Sets.SetView<E> \n difference(Set<E> set1,\n Set<?> set2)\n"
},
{
"code": null,
"e": 25532,
"s": 25414,
"text": "Return Value: This method returns a set containing all elements that are contained by set1 and not contained by set2."
},
{
"code": null,
"e": 25678,
"s": 25532,
"text": "Note: Set2 may also contain elements not present in set1, these are simply ignored. The iteration order of the returned set matches that of set1."
},
{
"code": null,
"e": 25689,
"s": 25678,
"text": "Example 1:"
},
{
"code": "// Java code to show implementation of// Guava's Sets.difference() method import com.google.common.collect.Sets;import java.util.Set; class GFG { // Driver's code public static void main(String[] args) { // Creating first set named set1 Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5, 6); // Creating second set named set2 Set<Integer> set2 = Sets.newHashSet(1, 3, 5, 7); // Using Guava's Sets.difference() method Set<Integer> diff = Sets.difference(set1, set2); // Displaying the unmodifiable view of // the difference of two sets. System.out.println(\"Set 1: \" + set1); System.out.println(\"Set 2: \" + set2); System.out.println(\"Difference between \" + \"Set 1 and Set 2: \" + diff); }}",
"e": 26610,
"s": 25689,
"text": null
},
{
"code": null,
"e": 26703,
"s": 26610,
"text": "Set 1: [1, 2, 3, 4, 5, 6]\nSet 2: [1, 3, 5, 7]\nDifference between Set 1 and Set 2: [2, 4, 6]\n"
},
{
"code": null,
"e": 26715,
"s": 26703,
"text": "Example 2 :"
},
{
"code": "// Java code to show implementation of// Guava's Sets.difference() method import com.google.common.collect.Sets;import java.util.Set; class GFG { // Driver's code public static void main(String[] args) { // Creating first set named set1 Set<String> set1 = Sets .newHashSet(\"H\", \"E\", \"L\", \"L\", \"O\", \"G\"); // Creating second set named set2 Set<String> set2 = Sets .newHashSet(\"L\", \"I\", \"K\", \"E\", \"G\"); // Using Guava's Sets.difference() method Set<String> diff = Sets.difference(set1, set2); // Displaying the unmodifiable view of // the difference of two sets. System.out.println(\"Set 1: \" + set1); System.out.println(\"Set 2: \" + set2); System.out.println(\"Difference between \" + \"Set 1 and Set 2: \" + diff); }}",
"e": 27708,
"s": 26715,
"text": null
},
{
"code": null,
"e": 27798,
"s": 27708,
"text": "Set 1: [E, G, H, L, O]\nSet 2: [I, K, L, E, G]\nDifference between Set 1 and Set 2: [H, O]\n"
},
{
"code": null,
"e": 27809,
"s": 27798,
"text": "java-guava"
},
{
"code": null,
"e": 27814,
"s": 27809,
"text": "Java"
},
{
"code": null,
"e": 27819,
"s": 27814,
"text": "Java"
},
{
"code": null,
"e": 27917,
"s": 27819,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27932,
"s": 27917,
"text": "Stream In Java"
},
{
"code": null,
"e": 27953,
"s": 27932,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27972,
"s": 27953,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28002,
"s": 27972,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28048,
"s": 28002,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28065,
"s": 28048,
"text": "Generics in Java"
},
{
"code": null,
"e": 28086,
"s": 28065,
"text": "Introduction to Java"
},
{
"code": null,
"e": 28122,
"s": 28086,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 28165,
"s": 28122,
"text": "Comparator Interface in Java with Examples"
}
] |
Largest interval in an Array that contains the given element X for Q queries - GeeksforGeeks
|
20 May, 2021
Given an array arr[] of N elements and Q queries of the form [X]. For each query, the task is to find the largest interval [L, R] of the array such that the greatest element in the interval is arr[X], such that 1 ≤ L ≤ X ≤ R. Note: The array has 1-based indexing.
Examples:
Input: N = 5, arr[] = {2, 1, 2, 3, 2}, Q = 3, query[] = {1, 2, 4} Output: [1, 3] [2, 2] [1, 5] Explanation : In 1st query, x = 1, so arr[x] = 2 and answer is L = 1 and R = 3. here, we can see that max(arr[1], arr[2], arr[3]) = arr[x], which is the maximum intervals. In 2nd query, x = 2, so arr[x] = 1 and since it is the smallest element of the array, so the interval contains only one element, thus the range is [2, 2]. In 3rd query, x = 4, so arr[x] = 4, which is maximum element of the arr[], so the answer is whole array, L = 1 and R = N.
Input: N = 4, arr[] = { 1, 2, 2, 4}, Q = 2, query[] = {1, 2} Output: [1, 1] [1, 3] Explanation: In 1st query, x = 1, so arr[x] = 1 and since it is the smallest element of the array, so the interval contains only one element, thus the range is [1, 1]. In 2nd query, x = 2, so arr[x] = 2 and answer is L = 1 and R = 3. here, we can see that max(arr[1], arr[2], arr[3]) = arr[x] = arr[2] = 2, which is the maximum intervals.
Approach: The idea is to precompute the largest interval for every value K in arr[] from 1 to N. Below are the steps:
For each element K in arr[], fix the index of the element K, then find how much we can extend the interval to it’s left and right.Decrement left iterator till arr[left] ≤ K and similarly increment right iterator till arr[right] ≤ K.The final value of left and right represents the starting and the ending index of the interval, which is stored in arrL[] and arrR[] respectively.After we have precomputed interval range for each value. Then, for each query, we need to print the interval range for arr[x] i.e., arrL[arr[x]] and arrR[arr[x]].
For each element K in arr[], fix the index of the element K, then find how much we can extend the interval to it’s left and right.
Decrement left iterator till arr[left] ≤ K and similarly increment right iterator till arr[right] ≤ K.
The final value of left and right represents the starting and the ending index of the interval, which is stored in arrL[] and arrR[] respectively.
After we have precomputed interval range for each value. Then, for each query, we need to print the interval range for arr[x] i.e., arrL[arr[x]] and arrR[arr[x]].
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 precompute the interval// for each queryvoid utilLargestInterval(int arr[], int arrL[], int arrR[], int N){ // For every values [1, N] find // the longest intervals for (int maxValue = 1; maxValue <= N; maxValue++) { int lastIndex = 0; // Iterate the array arr[] for (int i = 1; i <= N; i++) { if (lastIndex >= i || arr[i] != maxValue) continue; int left = i, right = i; // Shift the left pointers while (left > 0 && arr[left] <= maxValue) left--; // Shift the right pointers while (right <= N && arr[right] <= maxValue) right++; left++, right--; lastIndex = right; // Store the range of interval // in arrL[] and arrR[]. for (int j = left; j <= right; j++) { if (arr[j] == maxValue) { arrL[j] = left; arrR[j] = right; } } } }} // Function to find the largest interval// for each query in Q[]void largestInterval( int arr[], int query[], int N, int Q){ // To store the L and R of X int arrL[N + 1], arrR[N + 1]; // Function Call utilLargestInterval(arr, arrL, arrR, N); // Iterate to find ranges for each query for (int i = 0; i < Q; i++) { cout << "[" << arrL[query[i]] << ", " << arrR[query[i]] << "]\n"; }} // Driver Codeint main(){ int N = 5, Q = 3; // Given array arr[] int arr[N + 1] = { 0, 2, 1, 2, 3, 2 }; // Given Queries int query[Q] = { 1, 2, 4 }; // Function Call largestInterval(arr, query, N, Q); return 0;}
// Java program for the above approachclass GFG{ // Function to precompute the interval// for each querystatic void utilLargestInterval(int arr[], int arrL[], int arrR[], int N){ // For every values [1, N] find // the longest intervals for(int maxValue = 1; maxValue <= N; maxValue++) { int lastIndex = 0; // Iterate the array arr[] for(int i = 1; i <= N; i++) { if (lastIndex >= i || arr[i] != maxValue) continue; int left = i, right = i; // Shift the left pointers while (left > 0 && arr[left] <= maxValue) left--; // Shift the right pointers while (right <= N && arr[right] <= maxValue) right++; left++; right--; lastIndex = right; // Store the range of interval // in arrL[] and arrR[]. for(int j = left; j <= right; j++) { if (arr[j] == maxValue) { arrL[j] = left; arrR[j] = right; } } } }} // Function to find the largest interval// for each query in Q[]static void largestInterval(int arr[], int query[], int N, int Q){ // To store the L and R of X int []arrL = new int[N + 1]; int []arrR = new int[N + 1]; // Function Call utilLargestInterval(arr, arrL, arrR, N); // Iterate to find ranges for // each query for(int i = 0; i < Q; i++) { System.out.print("[" + arrL[query[i]] + ", " + arrR[query[i]] + "]\n"); }} // Driver Codepublic static void main(String[] args){ int N = 5, Q = 3; // Given array arr[] int arr[] = { 0, 2, 1, 2, 3, 2 }; // Given queries int query[] = { 1, 2, 4 }; // Function call largestInterval(arr, query, N, Q);}} // This code is contributed by Amit Katiyar
# Python3 program for the above approach # Function to precompute the interval# for each querydef utilLargestInterval(arr, arrL, arrR, N): # For every values [1, N] find # the longest intervals for maxValue in range(1, N + 1): lastIndex = 0 # Iterate the array arr[] for i in range(N + 1): if (lastIndex >= i or arr[i] != maxValue): continue left = i right = i # Shift the left pointers while (left > 0 and arr[left] <= maxValue): left -= 1 # Shift the right pointers while (right <= N and arr[right] <= maxValue): right += 1 left += 1 right -= 1 lastIndex = right # Store the range of interval # in arrL[] and arrR[]. for j in range(left, right + 1): if (arr[j] == maxValue): arrL[j] = left arrR[j] = right # Function to find the largest interval# for each query in Q[]def largestInterval(arr, query, N, Q): # To store the L and R of X arrL = [0 for i in range(N + 1)] arrR = [0 for i in range(N + 1)] # Function call utilLargestInterval(arr, arrL, arrR, N); # Iterate to find ranges for each query for i in range(Q): print('[' + str(arrL[query[i]]) + ', ' + str(arrR[query[i]]) + ']') # Driver codeif __name__=="__main__": N = 5 Q = 3 # Given array arr[] arr = [ 0, 2, 1, 2, 3, 2 ] # Given Queries query = [ 1, 2, 4 ] # Function call largestInterval(arr, query, N, Q) # This code is contributed by rutvik_56
// C# program for the above approachusing System; class GFG{ // Function to precompute the interval// for each querystatic void utilLargestInterval(int []arr, int []arrL, int []arrR, int N){ // For every values [1, N] find // the longest intervals for(int maxValue = 1; maxValue <= N; maxValue++) { int lastIndex = 0; // Iterate the array []arr for(int i = 1; i <= N; i++) { if (lastIndex >= i || arr[i] != maxValue) continue; int left = i, right = i; // Shift the left pointers while (left > 0 && arr[left] <= maxValue) left--; // Shift the right pointers while (right <= N && arr[right] <= maxValue) right++; left++; right--; lastIndex = right; // Store the range of interval // in arrL[] and arrR[]. for(int j = left; j <= right; j++) { if (arr[j] == maxValue) { arrL[j] = left; arrR[j] = right; } } } }} // Function to find the largest interval// for each query in Q[]static void largestInterval(int []arr, int []query, int N, int Q){ // To store the L and R of X int []arrL = new int[N + 1]; int []arrR = new int[N + 1]; // Function Call utilLargestInterval(arr, arrL, arrR, N); // Iterate to find ranges for // each query for(int i = 0; i < Q; i++) { Console.Write("[" + arrL[query[i]] + ", " + arrR[query[i]] + "]\n"); }} // Driver Codepublic static void Main(String[] args){ int N = 5, Q = 3; // Given array []arr int []arr = { 0, 2, 1, 2, 3, 2 }; // Given queries int []query = { 1, 2, 4 }; // Function call largestInterval(arr, query, N, Q);}} // This code is contributed by Princi Singh
<script> // Javascript program for the above approach // Function to precompute the interval// for each queryfunction utilLargestInterval(arr, arrL, arrR, N){ // For every values [1, N] find // the longest intervals for (var maxValue = 1; maxValue <= N; maxValue++) { var lastIndex = 0; // Iterate the array arr[] for (var i = 1; i <= N; i++) { if (lastIndex >= i || arr[i] != maxValue) continue; var left = i, right = i; // Shift the left pointers while (left > 0 && arr[left] <= maxValue) left--; // Shift the right pointers while (right <= N && arr[right] <= maxValue) right++; left++, right--; lastIndex = right; // Store the range of interval // in arrL[] and arrR[]. for (var j = left; j <= right; j++) { if (arr[j] == maxValue) { arrL[j] = left; arrR[j] = right; } } } }} // Function to find the largest interval// for each query in Q[]function largestInterval( arr, query, N, Q){ // To store the L and R of X var arrL = Array(N+1).fill(0),arrR = Array(N+1).fill(0); // Function Call utilLargestInterval(arr, arrL, arrR, N); // Iterate to find ranges for each query for (var i = 0; i < Q; i++) { document.write( "[" + arrL[query[i]] + ", " + arrR[query[i]] + "]<br>"); }} // Driver Codevar N = 5, Q = 3; // Given array arr[]var arr = [0, 2, 1, 2, 3, 2]; // Given Queriesvar query = [1, 2, 4]; // Function CalllargestInterval(arr, query, N, Q); // This code is contributed by itsok.</script>
[1, 3]
[2, 2]
[1, 5]
Time Complexity: O(Q + N2) Auxiliary Space: O(N)
amit143katiyar
princi singh
nidhi_biet
rutvik_56
itsok
array-range-queries
Algorithms
Arrays
Competitive Programming
Arrays
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 write a Pseudo Code?
Understanding Time Complexity with Simple Examples
Introduction to Algorithms
Arrays in Java
Arrays in C/C++
Maximum and minimum of an array using minimum number of comparisons
Write a program to reverse an array or string
Program for array rotation
|
[
{
"code": null,
"e": 26007,
"s": 25979,
"text": "\n20 May, 2021"
},
{
"code": null,
"e": 26271,
"s": 26007,
"text": "Given an array arr[] of N elements and Q queries of the form [X]. For each query, the task is to find the largest interval [L, R] of the array such that the greatest element in the interval is arr[X], such that 1 ≤ L ≤ X ≤ R. Note: The array has 1-based indexing."
},
{
"code": null,
"e": 26282,
"s": 26271,
"text": "Examples: "
},
{
"code": null,
"e": 26826,
"s": 26282,
"text": "Input: N = 5, arr[] = {2, 1, 2, 3, 2}, Q = 3, query[] = {1, 2, 4} Output: [1, 3] [2, 2] [1, 5] Explanation : In 1st query, x = 1, so arr[x] = 2 and answer is L = 1 and R = 3. here, we can see that max(arr[1], arr[2], arr[3]) = arr[x], which is the maximum intervals. In 2nd query, x = 2, so arr[x] = 1 and since it is the smallest element of the array, so the interval contains only one element, thus the range is [2, 2]. In 3rd query, x = 4, so arr[x] = 4, which is maximum element of the arr[], so the answer is whole array, L = 1 and R = N."
},
{
"code": null,
"e": 27249,
"s": 26826,
"text": "Input: N = 4, arr[] = { 1, 2, 2, 4}, Q = 2, query[] = {1, 2} Output: [1, 1] [1, 3] Explanation: In 1st query, x = 1, so arr[x] = 1 and since it is the smallest element of the array, so the interval contains only one element, thus the range is [1, 1]. In 2nd query, x = 2, so arr[x] = 2 and answer is L = 1 and R = 3. here, we can see that max(arr[1], arr[2], arr[3]) = arr[x] = arr[2] = 2, which is the maximum intervals. "
},
{
"code": null,
"e": 27367,
"s": 27249,
"text": "Approach: The idea is to precompute the largest interval for every value K in arr[] from 1 to N. Below are the steps:"
},
{
"code": null,
"e": 27908,
"s": 27367,
"text": "For each element K in arr[], fix the index of the element K, then find how much we can extend the interval to it’s left and right.Decrement left iterator till arr[left] ≤ K and similarly increment right iterator till arr[right] ≤ K.The final value of left and right represents the starting and the ending index of the interval, which is stored in arrL[] and arrR[] respectively.After we have precomputed interval range for each value. Then, for each query, we need to print the interval range for arr[x] i.e., arrL[arr[x]] and arrR[arr[x]]."
},
{
"code": null,
"e": 28039,
"s": 27908,
"text": "For each element K in arr[], fix the index of the element K, then find how much we can extend the interval to it’s left and right."
},
{
"code": null,
"e": 28142,
"s": 28039,
"text": "Decrement left iterator till arr[left] ≤ K and similarly increment right iterator till arr[right] ≤ K."
},
{
"code": null,
"e": 28289,
"s": 28142,
"text": "The final value of left and right represents the starting and the ending index of the interval, which is stored in arrL[] and arrR[] respectively."
},
{
"code": null,
"e": 28452,
"s": 28289,
"text": "After we have precomputed interval range for each value. Then, for each query, we need to print the interval range for arr[x] i.e., arrL[arr[x]] and arrR[arr[x]]."
},
{
"code": null,
"e": 28503,
"s": 28452,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28507,
"s": 28503,
"text": "C++"
},
{
"code": null,
"e": 28512,
"s": 28507,
"text": "Java"
},
{
"code": null,
"e": 28520,
"s": 28512,
"text": "Python3"
},
{
"code": null,
"e": 28523,
"s": 28520,
"text": "C#"
},
{
"code": null,
"e": 28534,
"s": 28523,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to precompute the interval// for each queryvoid utilLargestInterval(int arr[], int arrL[], int arrR[], int N){ // For every values [1, N] find // the longest intervals for (int maxValue = 1; maxValue <= N; maxValue++) { int lastIndex = 0; // Iterate the array arr[] for (int i = 1; i <= N; i++) { if (lastIndex >= i || arr[i] != maxValue) continue; int left = i, right = i; // Shift the left pointers while (left > 0 && arr[left] <= maxValue) left--; // Shift the right pointers while (right <= N && arr[right] <= maxValue) right++; left++, right--; lastIndex = right; // Store the range of interval // in arrL[] and arrR[]. for (int j = left; j <= right; j++) { if (arr[j] == maxValue) { arrL[j] = left; arrR[j] = right; } } } }} // Function to find the largest interval// for each query in Q[]void largestInterval( int arr[], int query[], int N, int Q){ // To store the L and R of X int arrL[N + 1], arrR[N + 1]; // Function Call utilLargestInterval(arr, arrL, arrR, N); // Iterate to find ranges for each query for (int i = 0; i < Q; i++) { cout << \"[\" << arrL[query[i]] << \", \" << arrR[query[i]] << \"]\\n\"; }} // Driver Codeint main(){ int N = 5, Q = 3; // Given array arr[] int arr[N + 1] = { 0, 2, 1, 2, 3, 2 }; // Given Queries int query[Q] = { 1, 2, 4 }; // Function Call largestInterval(arr, query, N, Q); return 0;}",
"e": 30487,
"s": 28534,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Function to precompute the interval// for each querystatic void utilLargestInterval(int arr[], int arrL[], int arrR[], int N){ // For every values [1, N] find // the longest intervals for(int maxValue = 1; maxValue <= N; maxValue++) { int lastIndex = 0; // Iterate the array arr[] for(int i = 1; i <= N; i++) { if (lastIndex >= i || arr[i] != maxValue) continue; int left = i, right = i; // Shift the left pointers while (left > 0 && arr[left] <= maxValue) left--; // Shift the right pointers while (right <= N && arr[right] <= maxValue) right++; left++; right--; lastIndex = right; // Store the range of interval // in arrL[] and arrR[]. for(int j = left; j <= right; j++) { if (arr[j] == maxValue) { arrL[j] = left; arrR[j] = right; } } } }} // Function to find the largest interval// for each query in Q[]static void largestInterval(int arr[], int query[], int N, int Q){ // To store the L and R of X int []arrL = new int[N + 1]; int []arrR = new int[N + 1]; // Function Call utilLargestInterval(arr, arrL, arrR, N); // Iterate to find ranges for // each query for(int i = 0; i < Q; i++) { System.out.print(\"[\" + arrL[query[i]] + \", \" + arrR[query[i]] + \"]\\n\"); }} // Driver Codepublic static void main(String[] args){ int N = 5, Q = 3; // Given array arr[] int arr[] = { 0, 2, 1, 2, 3, 2 }; // Given queries int query[] = { 1, 2, 4 }; // Function call largestInterval(arr, query, N, Q);}} // This code is contributed by Amit Katiyar",
"e": 32625,
"s": 30487,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to precompute the interval# for each querydef utilLargestInterval(arr, arrL, arrR, N): # For every values [1, N] find # the longest intervals for maxValue in range(1, N + 1): lastIndex = 0 # Iterate the array arr[] for i in range(N + 1): if (lastIndex >= i or arr[i] != maxValue): continue left = i right = i # Shift the left pointers while (left > 0 and arr[left] <= maxValue): left -= 1 # Shift the right pointers while (right <= N and arr[right] <= maxValue): right += 1 left += 1 right -= 1 lastIndex = right # Store the range of interval # in arrL[] and arrR[]. for j in range(left, right + 1): if (arr[j] == maxValue): arrL[j] = left arrR[j] = right # Function to find the largest interval# for each query in Q[]def largestInterval(arr, query, N, Q): # To store the L and R of X arrL = [0 for i in range(N + 1)] arrR = [0 for i in range(N + 1)] # Function call utilLargestInterval(arr, arrL, arrR, N); # Iterate to find ranges for each query for i in range(Q): print('[' + str(arrL[query[i]]) + ', ' + str(arrR[query[i]]) + ']') # Driver codeif __name__==\"__main__\": N = 5 Q = 3 # Given array arr[] arr = [ 0, 2, 1, 2, 3, 2 ] # Given Queries query = [ 1, 2, 4 ] # Function call largestInterval(arr, query, N, Q) # This code is contributed by rutvik_56",
"e": 34371,
"s": 32625,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to precompute the interval// for each querystatic void utilLargestInterval(int []arr, int []arrL, int []arrR, int N){ // For every values [1, N] find // the longest intervals for(int maxValue = 1; maxValue <= N; maxValue++) { int lastIndex = 0; // Iterate the array []arr for(int i = 1; i <= N; i++) { if (lastIndex >= i || arr[i] != maxValue) continue; int left = i, right = i; // Shift the left pointers while (left > 0 && arr[left] <= maxValue) left--; // Shift the right pointers while (right <= N && arr[right] <= maxValue) right++; left++; right--; lastIndex = right; // Store the range of interval // in arrL[] and arrR[]. for(int j = left; j <= right; j++) { if (arr[j] == maxValue) { arrL[j] = left; arrR[j] = right; } } } }} // Function to find the largest interval// for each query in Q[]static void largestInterval(int []arr, int []query, int N, int Q){ // To store the L and R of X int []arrL = new int[N + 1]; int []arrR = new int[N + 1]; // Function Call utilLargestInterval(arr, arrL, arrR, N); // Iterate to find ranges for // each query for(int i = 0; i < Q; i++) { Console.Write(\"[\" + arrL[query[i]] + \", \" + arrR[query[i]] + \"]\\n\"); }} // Driver Codepublic static void Main(String[] args){ int N = 5, Q = 3; // Given array []arr int []arr = { 0, 2, 1, 2, 3, 2 }; // Given queries int []query = { 1, 2, 4 }; // Function call largestInterval(arr, query, N, Q);}} // This code is contributed by Princi Singh",
"e": 36534,
"s": 34371,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to precompute the interval// for each queryfunction utilLargestInterval(arr, arrL, arrR, N){ // For every values [1, N] find // the longest intervals for (var maxValue = 1; maxValue <= N; maxValue++) { var lastIndex = 0; // Iterate the array arr[] for (var i = 1; i <= N; i++) { if (lastIndex >= i || arr[i] != maxValue) continue; var left = i, right = i; // Shift the left pointers while (left > 0 && arr[left] <= maxValue) left--; // Shift the right pointers while (right <= N && arr[right] <= maxValue) right++; left++, right--; lastIndex = right; // Store the range of interval // in arrL[] and arrR[]. for (var j = left; j <= right; j++) { if (arr[j] == maxValue) { arrL[j] = left; arrR[j] = right; } } } }} // Function to find the largest interval// for each query in Q[]function largestInterval( arr, query, N, Q){ // To store the L and R of X var arrL = Array(N+1).fill(0),arrR = Array(N+1).fill(0); // Function Call utilLargestInterval(arr, arrL, arrR, N); // Iterate to find ranges for each query for (var i = 0; i < Q; i++) { document.write( \"[\" + arrL[query[i]] + \", \" + arrR[query[i]] + \"]<br>\"); }} // Driver Codevar N = 5, Q = 3; // Given array arr[]var arr = [0, 2, 1, 2, 3, 2]; // Given Queriesvar query = [1, 2, 4]; // Function CalllargestInterval(arr, query, N, Q); // This code is contributed by itsok.</script>",
"e": 38364,
"s": 36534,
"text": null
},
{
"code": null,
"e": 38385,
"s": 38364,
"text": "[1, 3]\n[2, 2]\n[1, 5]"
},
{
"code": null,
"e": 38437,
"s": 38387,
"text": "Time Complexity: O(Q + N2) Auxiliary Space: O(N) "
},
{
"code": null,
"e": 38452,
"s": 38437,
"text": "amit143katiyar"
},
{
"code": null,
"e": 38465,
"s": 38452,
"text": "princi singh"
},
{
"code": null,
"e": 38476,
"s": 38465,
"text": "nidhi_biet"
},
{
"code": null,
"e": 38486,
"s": 38476,
"text": "rutvik_56"
},
{
"code": null,
"e": 38492,
"s": 38486,
"text": "itsok"
},
{
"code": null,
"e": 38512,
"s": 38492,
"text": "array-range-queries"
},
{
"code": null,
"e": 38523,
"s": 38512,
"text": "Algorithms"
},
{
"code": null,
"e": 38530,
"s": 38523,
"text": "Arrays"
},
{
"code": null,
"e": 38554,
"s": 38530,
"text": "Competitive Programming"
},
{
"code": null,
"e": 38561,
"s": 38554,
"text": "Arrays"
},
{
"code": null,
"e": 38572,
"s": 38561,
"text": "Algorithms"
},
{
"code": null,
"e": 38670,
"s": 38572,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38719,
"s": 38670,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 38744,
"s": 38719,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 38772,
"s": 38744,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 38823,
"s": 38772,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 38850,
"s": 38823,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 38865,
"s": 38850,
"text": "Arrays in Java"
},
{
"code": null,
"e": 38881,
"s": 38865,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 38949,
"s": 38881,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 38995,
"s": 38949,
"text": "Write a program to reverse an array or string"
}
] |
Find maximum possible stolen value from houses - GeeksforGeeks
|
05 May, 2022
There are n houses build in a line, each of which contains some value in it. A thief is going to steal the maximal value of these houses, but he can’t steal in two adjacent houses because the owner of the stolen houses will tell his two neighbors left and right side. What is the maximum stolen value?Examples:
Input: hval[] = {6, 7, 1, 3, 8, 2, 4}
Output: 19
Explanation: The thief will steal 6, 1, 8 and 4 from the house.
Input: hval[] = {5, 3, 4, 11, 2}
Output: 16
Explanation: Thief will steal 5 and 11
Naive Approach: Given an array, the solution is to find the maximum sum subsequence where no two selected elements are adjacent. So the approach to the problem is a recursive solution. So there are two cases.
If an element is selected then the next element cannot be selected.if an element is not selected then the next element can be selected.
If an element is selected then the next element cannot be selected.
if an element is not selected then the next element can be selected.
Implementation of recursion approach:
C++
C
// CPP program to find the maximum stolen value#include <iostream>using namespace std; // calculate the maximum stolen valueint maxLoot(int* hval, int n){ // base case if (n < 0) { return 0; } if (n == 0) { return hval[0]; } // if current element is pick then previous cannot be // picked int pick = hval[n] + maxLoot(hval, n - 2); // if current element is not picked then previous // element is picked int notPick = maxLoot(hval, n - 1); // return max of picked and not picked return max(pick, notPick);} // Driver to test above codeint main(){ int hval[] = { 6, 7, 1, 3, 8, 2, 4 }; int n = sizeof(hval) / sizeof(hval[0]); cout << "Maximum loot possible : " << maxLoot(hval, n - 1); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C program to find the maximum stolen value#include <stdio.h> // Find maximum between two numbers.int max(int num1, int num2){ return (num1 > num2) ? num1 : num2;} // calculate the maximum stolen valueint maxLoot(int* hval, int n){ // base case if (n < 0) return 0; if (n == 0) return hval[0]; // if current element is pick then previous cannot be // picked int pick = hval[n] + maxLoot(hval, n - 2); // if current element is not picked then previous // element is picked int notPick = maxLoot(hval, n - 1); // return max of picked and not picked return max(pick, notPick);} // Driver to test above codeint main(){ int hval[] = { 6, 7, 1, 3, 8, 2, 4 }; int n = sizeof(hval) / sizeof(hval[0]); printf("Maximum loot possible : %d ", maxLoot(hval, n - 1)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
Maximum loot possible : 19
Complexity Analysis
Time Complexity: O(2N). Every element has 2 choices to pick and not pick
Space Complexity: O(2N). A recursion stack space is required of size 2n, so space complexity is O(2N).
Method 2: Dynamic Programming : Top Down Approach
So the recursive solution can easily be deviced. The sub-problems can be stored thus reducing the complexity and converting the recursive solution to a Dynamic programming problem.
C++
// CPP program to find the maximum stolen value#include <bits/stdc++.h>using namespace std; // calculate the maximum stolen valueint maxLoot(int *hval, int n, vector<int> &dp){ // base case if(n < 0){ return 0 ; } if(n == 0){ return hval[0] ; } // If the subproblem is already solved // then return its value if(dp[n] != -1 ){ return dp[n] ; } //if current element is pick then previous cannot be picked int pick = hval[n] + maxLoot(hval, n-2, dp) ; //if current element is not picked then previous element is picked int notPick = maxLoot(hval, n-1, dp) ; // return max of picked and not picked return dp[n] = max(pick, notPick) ; } // Driver to test above codeint main(){ int hval[] = {6, 7, 1, 3, 8, 2, 4}; int n = sizeof(hval)/sizeof(hval[0]); // Initialize a dp vector vector<int> dp(n+1, -1) ; cout << "Maximum loot possible : " << maxLoot(hval, n-1, dp); return 0;}
Maximum loot possible : 19
Complexity Analysis:
Time Complexity: O(n) . Only one traversal of original array is needed. So the time complexity is O(n)
Space Complexity: O(n). Recursive stack space is required of size n, so space complexity is O(n).
Method 3: Dynamic Programming : Bottom Up Approach
So the recursive solution can easily be deviced. The sub-problems can be stored thus reducing the complexity and converting the recursive solution to a Dynamic programming problem.
Algorithm:
Create an extra space dp, DP array to store the sub-problems.Tackle some basic cases, if the length of the array is 0, print 0, if the length of the array is 1, print the first element, if the length of the array is 2, print maximum of two elements.Update dp[0] as array[0] and dp[1] as maximum of array[0] and array[1]Traverse the array from the second element (2nd index) to the end of array.For every index, update dp[i] as maximum of dp[i-2] + array[i] and dp[i-1], this step defines the two cases, if an element is selected then the previous element cannot be selected and if an element is not selected then the previous element can be selected.Print the value dp[n-1]
Create an extra space dp, DP array to store the sub-problems.
Tackle some basic cases, if the length of the array is 0, print 0, if the length of the array is 1, print the first element, if the length of the array is 2, print maximum of two elements.
Update dp[0] as array[0] and dp[1] as maximum of array[0] and array[1]
Traverse the array from the second element (2nd index) to the end of array.
For every index, update dp[i] as maximum of dp[i-2] + array[i] and dp[i-1], this step defines the two cases, if an element is selected then the previous element cannot be selected and if an element is not selected then the previous element can be selected.
Print the value dp[n-1]
Implementation:
C++
C
Java
Python3
C#
PHP
Javascript
// CPP program to find the maximum stolen value#include <iostream>using namespace std; // calculate the maximum stolen valueint maxLoot(int* hval, int n){ if (n == 0) return 0; if (n == 1) return hval[0]; if (n == 2) return max(hval[0], hval[1]); // dp[i] represent the maximum value stolen // so far after reaching house i. int dp[n]; // Initialize the dp[0] and dp[1] dp[0] = hval[0]; dp[1] = max(hval[0], hval[1]); // Fill remaining positions for (int i = 2; i < n; i++) dp[i] = max(hval[i] + dp[i - 2], dp[i - 1]); return dp[n - 1];} // Driver to test above codeint main(){ int hval[] = { 6, 7, 1, 3, 8, 2, 4 }; int n = sizeof(hval) / sizeof(hval[0]); cout << "Maximum loot possible : " << maxLoot(hval, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C program to find the maximum stolen value#include <stdio.h> // Find maximum between two numbers.int max(int num1, int num2){ return (num1 > num2) ? num1 : num2;} // calculate the maximum stolen valueint maxLoot(int* hval, int n){ if (n == 0) return 0; if (n == 1) return hval[0]; if (n == 2) return max(hval[0], hval[1]); // dp[i] represent the maximum value stolen // so far after reaching house i. int dp[n]; // Initialize the dp[0] and dp[1] dp[0] = hval[0]; dp[1] = max(hval[0], hval[1]); // Fill remaining positions for (int i = 2; i < n; i++) dp[i] = max(hval[i] + dp[i - 2], dp[i - 1]); return dp[n - 1];} // Driver to test above codeint main(){ int hval[] = { 6, 7, 1, 3, 8, 2, 4 }; int n = sizeof(hval) / sizeof(hval[0]); printf("Maximum loot possible : %d", maxLoot(hval, n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program to find the maximum stolen valueimport java.io.*; class GFG { // Function to calculate the maximum stolen value static int maxLoot(int hval[], int n) { if (n == 0) return 0; if (n == 1) return hval[0]; if (n == 2) return Math.max(hval[0], hval[1]); // dp[i] represent the maximum value stolen // so far after reaching house i. int[] dp = new int[n]; // Initialize the dp[0] and dp[1] dp[0] = hval[0]; dp[1] = Math.max(hval[0], hval[1]); // Fill remaining positions for (int i = 2; i < n; i++) dp[i] = Math.max(hval[i] + dp[i - 2], dp[i - 1]); return dp[n - 1]; } // Driver program public static void main(String[] args) { int hval[] = { 6, 7, 1, 3, 8, 2, 4 }; int n = hval.length; System.out.println("Maximum loot value : " + maxLoot(hval, n)); }} // This code is contributed by Aditya Kumar (adityakumar129)
# Python3 program to find the maximum stolen value # calculate the maximum stolen valuedef maximize_loot(hval, n): if n == 0: return 0 if n == 1: return hval[0] if n == 2: return max(hval[0], hval[1]) # dp[i] represent the maximum value stolen so # for after reaching house i. dp = [0]*n # Initialize the dp[0] and dp[1] dp[0] = hval[0] dp[1] = max(hval[0], hval[1]) # Fill remaining positions for i in range(2, n): dp[i] = max(hval[i]+dp[i-2], dp[i-1]) return dp[-1] # Driver to test above codedef main(): # Value of houses hval = [6, 7, 1, 3, 8, 2, 4] # number of houses n = len(hval) print("Maximum loot value : {}". format(maximize_loot(hval, n))) if __name__ == '__main__': main()
// C# program to find the// maximum stolen valueusing System; class GFG{ // Function to calculate the // maximum stolen value static int maxLoot(int []hval, int n) { if (n == 0) return 0; if (n == 1) return hval[0]; if (n == 2) return Math.Max(hval[0], hval[1]); // dp[i] represent the maximum value stolen // so far after reaching house i. int[] dp = new int[n]; // Initialize the dp[0] and dp[1] dp[0] = hval[0]; dp[1] = Math.Max(hval[0], hval[1]); // Fill remaining positions for (int i = 2; i<n; i++) dp[i] = Math.Max(hval[i]+dp[i-2], dp[i-1]); return dp[n-1]; } // Driver program public static void Main () { int []hval = {6, 7, 1, 3, 8, 2, 4}; int n = hval.Length; Console.WriteLine("Maximum loot value : " + maxLoot(hval, n)); }} // This code is contributed by Sam007
<?php// PHP program to find// the maximum stolen value // calculate the maximum// stolen valuefunction maxLoot($hval, $n){ if ($n == 0) return 0; if ($n == 1) return $hval[0]; if ($n == 2) return max($hval[0], $hval[1]); // dp[i] represent the maximum // value stolen so far after // reaching house i. $dp = array(); // Initialize the // dp[0] and dp[1] $dp[0] = $hval[0]; $dp[1] = max($hval[0], $hval[1]); // Fill remaining positions for ($i = 2; $i < $n; $i++) $dp[$i] = max($hval[$i] + $dp[$i - 2], $dp[$i - 1]); return $dp[$n - 1];} // Driver Code$hval = array(6, 7, 1, 3, 8, 2, 4);$n = sizeof($hval);echo "Maximum loot possible : ", maxLoot($hval, $n); // This code is contributed by aj_36?>
<script> // Javascript program to find // the maximum stolen value // Function to calculate the // maximum stolen value function maxLoot(hval, n) { if (n == 0) return 0; if (n == 1) return hval[0]; if (n == 2) return Math.max(hval[0], hval[1]); // dp[i] represent the maximum value stolen // so far after reaching house i. let dp = new Array(n); // Initialize the dp[0] and dp[1] dp[0] = hval[0]; dp[1] = Math.max(hval[0], hval[1]); // Fill remaining positions for (let i = 2; i<n; i++) dp[i] = Math.max(hval[i]+dp[i-2], dp[i-1]); return dp[n-1]; } let hval = [6, 7, 1, 3, 8, 2, 4]; let n = hval.length; document.write( "Maximum loot value : " + maxLoot(hval, n) ); </script>
Maximum loot possible : 19
Complexity Analysis:
Time Complexity: . Only one traversal of original array is needed. So the time complexity is O(n)
Space Complexity: . An array is required of size n, so space complexity is O(n).
Efficient Approach: By carefully observing the DP array, it can be seen that the values of previous two indices matter while calculating the value for an index. To replace the total DP array by two variables.
Algorithm:
Tackle some basic cases, if the length of the array is 0, print 0, if the length of the array is 1, print the first element, if the length of the array is 2, print maximum of two elements.Create two variables value1 and value2 value1 as array[0] and value2 as maximum of array[0] and array[1] and a variable max_val to store the answerTraverse the array from the second element (2nd index) to the end of array.For every index, update max_val as maximum of value1 + array[i] and value2, this step defines the two cases, if an element is selected then the previous element cannot be selected and if an element is not selected then the previous element can be selected.For every index, Update value1 = value2 and value2 = max_valPrint the value of max_val
Tackle some basic cases, if the length of the array is 0, print 0, if the length of the array is 1, print the first element, if the length of the array is 2, print maximum of two elements.
Create two variables value1 and value2 value1 as array[0] and value2 as maximum of array[0] and array[1] and a variable max_val to store the answer
Traverse the array from the second element (2nd index) to the end of array.
For every index, update max_val as maximum of value1 + array[i] and value2, this step defines the two cases, if an element is selected then the previous element cannot be selected and if an element is not selected then the previous element can be selected.
For every index, Update value1 = value2 and value2 = max_val
Print the value of max_val
Implementation:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find the maximum stolen value#include <iostream>using namespace std; // calculate the maximum stolen valueint maxLoot(int* hval, int n){ if (n == 0) return 0; int value1 = hval[0]; if (n == 1) return value1; int value2 = max(hval[0], hval[1]); if (n == 2) return value2; // contains maximum stolen value at the end int max_val; // Fill remaining positions for (int i = 2; i < n; i++) { max_val = max(hval[i] + value1, value2); value1 = value2; value2 = max_val; } return max_val;} // Driver to test above codeint main(){ // Value of houses int hval[] = { 6, 7, 1, 3, 8, 2, 4 }; int n = sizeof(hval) / sizeof(hval[0]); cout << "Maximum loot possible : " << maxLoot(hval, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C program to find the maximum stolen value#include <stdio.h> //Find maximum between two numbers.int max(int num1, int num2){ return (num1 > num2) ? num1 : num2;} // calculate the maximum stolen valueint maxLoot(int* hval, int n){ if (n == 0) return 0; int value1 = hval[0]; if (n == 1) return value1; int value2 = max(hval[0], hval[1]); if (n == 2) return value2; // contains maximum stolen value at the end int max_val; // Fill remaining positions for (int i = 2; i < n; i++) { max_val = max(hval[i] + value1, value2); value1 = value2; value2 = max_val; } return max_val;} // Driver to test above codeint main(){ // Value of houses int hval[] = { 6, 7, 1, 3, 8, 2, 4 }; int n = sizeof(hval) / sizeof(hval[0]); printf("Maximum loot possible : %d", maxLoot(hval, n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program to find the maximum stolen valueimport java.io.*; class GFG { // Function to calculate the maximum stolen value static int maxLoot(int hval[], int n) { if (n == 0) return 0; int value1 = hval[0]; if (n == 1) return value1; int value2 = Math.max(hval[0], hval[1]); if (n == 2) return value2; // contains maximum stolen value at the end int max_val = 0; // Fill remaining positions for (int i = 2; i < n; i++) { max_val = Math.max(hval[i] + value1, value2); value1 = value2; value2 = max_val; } return max_val; } // driver program public static void main(String[] args) { int hval[] = { 6, 7, 1, 3, 8, 2, 4 }; int n = hval.length; System.out.println("Maximum loot value : " + maxLoot(hval, n)); }} // This code is contributed by Aditya Kumar (adityakumar129)
# Python3 program to find the maximum stolen value # calculate the maximum stolen valuedef maximize_loot(hval, n): if n == 0: return 0 value1 = hval[0] if n == 1: return value1 value2 = max(hval[0], hval[1]) if n == 2: return value2 # contains maximum stolen value at the end max_val = None # Fill remaining positions for i in range(2, n): max_val = max(hval[i]+value1, value2) value1 = value2 value2 = max_val return max_val # Driver to test above codedef main(): # Value of houses hval = [6, 7, 1, 3, 8, 2, 4] # number of houses n = len(hval) print("Maximum loot value : {}".format(maximize_loot(hval, n))) if __name__ == '__main__': main()
// C# program to find the// maximum stolen valueusing System; public class GFG{ // Function to calculate the // maximum stolen value static int maxLoot(int []hval, int n) { if (n == 0) return 0; int value1 = hval[0]; if (n == 1) return value1; int value2 = Math.Max(hval[0], hval[1]); if (n == 2) return value2; // contains maximum stolen value at the end int max_val = 0; // Fill remaining positions for (int i = 2; i < n; i++) { max_val = Math.Max(hval[i] + value1, value2); value1 = value2; value2 = max_val; } return max_val; } // Driver program public static void Main () { int []hval = {6, 7, 1, 3, 8, 2, 4}; int n = hval.Length; Console.WriteLine("Maximum loot value : " + maxLoot(hval, n)); }} // This code is contributed by Sam007
<?php// PHP program to find// the maximum stolen value // calculate the// maximum stolen valuefunction maxLoot($hval, $n){ if ($n == 0) return 0; $value1 = $hval[0]; if ($n == 1) return $value1; $value2 = max($hval[0], $hval[1]); if ($n == 2) return $value2; // contains maximum // stolen value at the end $max_val; // Fill remaining positions for ($i = 2; $i < $n; $i++) { $max_val = max($hval[$i] + $value1, $value2); $value1 = $value2; $value2 = $max_val; } return $max_val;} // Driver code$hval = array(6, 7, 1, 3, 8, 2, 4);$n = sizeof($hval);echo "Maximum loot value : ", maxLoot($hval, $n); // This code is contributed by ajit?>
<script> // Javascript program to find the // maximum stolen value // Function to calculate the // maximum stolen value function maxLoot(hval, n) { if (n == 0) return 0; let value1 = hval[0]; if (n == 1) return value1; let value2 = Math.max(hval[0], hval[1]); if (n == 2) return value2; // contains maximum stolen value at the end let max_val = 0; // Fill remaining positions for (let i = 2; i < n; i++) { max_val = Math.max(hval[i] + value1, value2); value1 = value2; value2 = max_val; } return max_val; } let hval = [6, 7, 1, 3, 8, 2, 4]; let n = hval.length; document.write("Maximum loot value : " + maxLoot(hval, n)); </script>
Maximum loot possible : 19
Complexity Analysis:
Time Complexity: , Only one traversal of original array is needed. So the time complexity is O(n).
Auxiliary Space: , No extra space is required so the space complexity is constant.
This article is contributed by Atul Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sam007
jit_t
andrew1234
suresh07
divyesh072019
raghvendraprasad5678
amartyaghoshgfg
prasanna1995
arorakashish0911
adityakumar129
Amazon
FactSet
Oxigen Wallet
OYO Rooms
Paytm
Walmart
Yahoo
Arrays
Dynamic Programming
Paytm
Amazon
OYO Rooms
FactSet
Walmart
Oxigen Wallet
Yahoo
Arrays
Dynamic Programming
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
0-1 Knapsack Problem | DP-10
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Longest Increasing Subsequence | DP-3
|
[
{
"code": null,
"e": 26131,
"s": 26103,
"text": "\n05 May, 2022"
},
{
"code": null,
"e": 26444,
"s": 26131,
"text": "There are n houses build in a line, each of which contains some value in it. A thief is going to steal the maximal value of these houses, but he can’t steal in two adjacent houses because the owner of the stolen houses will tell his two neighbors left and right side. What is the maximum stolen value?Examples: "
},
{
"code": null,
"e": 26643,
"s": 26444,
"text": "Input: hval[] = {6, 7, 1, 3, 8, 2, 4}\nOutput: 19\n\nExplanation: The thief will steal 6, 1, 8 and 4 from the house.\n\nInput: hval[] = {5, 3, 4, 11, 2}\nOutput: 16\n\nExplanation: Thief will steal 5 and 11"
},
{
"code": null,
"e": 26856,
"s": 26645,
"text": "Naive Approach: Given an array, the solution is to find the maximum sum subsequence where no two selected elements are adjacent. So the approach to the problem is a recursive solution. So there are two cases. "
},
{
"code": null,
"e": 26992,
"s": 26856,
"text": "If an element is selected then the next element cannot be selected.if an element is not selected then the next element can be selected."
},
{
"code": null,
"e": 27060,
"s": 26992,
"text": "If an element is selected then the next element cannot be selected."
},
{
"code": null,
"e": 27129,
"s": 27060,
"text": "if an element is not selected then the next element can be selected."
},
{
"code": null,
"e": 27167,
"s": 27129,
"text": "Implementation of recursion approach:"
},
{
"code": null,
"e": 27171,
"s": 27167,
"text": "C++"
},
{
"code": null,
"e": 27173,
"s": 27171,
"text": "C"
},
{
"code": "// CPP program to find the maximum stolen value#include <iostream>using namespace std; // calculate the maximum stolen valueint maxLoot(int* hval, int n){ // base case if (n < 0) { return 0; } if (n == 0) { return hval[0]; } // if current element is pick then previous cannot be // picked int pick = hval[n] + maxLoot(hval, n - 2); // if current element is not picked then previous // element is picked int notPick = maxLoot(hval, n - 1); // return max of picked and not picked return max(pick, notPick);} // Driver to test above codeint main(){ int hval[] = { 6, 7, 1, 3, 8, 2, 4 }; int n = sizeof(hval) / sizeof(hval[0]); cout << \"Maximum loot possible : \" << maxLoot(hval, n - 1); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 28004,
"s": 27173,
"text": null
},
{
"code": "// C program to find the maximum stolen value#include <stdio.h> // Find maximum between two numbers.int max(int num1, int num2){ return (num1 > num2) ? num1 : num2;} // calculate the maximum stolen valueint maxLoot(int* hval, int n){ // base case if (n < 0) return 0; if (n == 0) return hval[0]; // if current element is pick then previous cannot be // picked int pick = hval[n] + maxLoot(hval, n - 2); // if current element is not picked then previous // element is picked int notPick = maxLoot(hval, n - 1); // return max of picked and not picked return max(pick, notPick);} // Driver to test above codeint main(){ int hval[] = { 6, 7, 1, 3, 8, 2, 4 }; int n = sizeof(hval) / sizeof(hval[0]); printf(\"Maximum loot possible : %d \", maxLoot(hval, n - 1)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 28906,
"s": 28004,
"text": null
},
{
"code": null,
"e": 28933,
"s": 28906,
"text": "Maximum loot possible : 19"
},
{
"code": null,
"e": 28953,
"s": 28933,
"text": "Complexity Analysis"
},
{
"code": null,
"e": 29027,
"s": 28953,
"text": "Time Complexity: O(2N). Every element has 2 choices to pick and not pick"
},
{
"code": null,
"e": 29130,
"s": 29027,
"text": "Space Complexity: O(2N). A recursion stack space is required of size 2n, so space complexity is O(2N)."
},
{
"code": null,
"e": 29180,
"s": 29130,
"text": "Method 2: Dynamic Programming : Top Down Approach"
},
{
"code": null,
"e": 29361,
"s": 29180,
"text": "So the recursive solution can easily be deviced. The sub-problems can be stored thus reducing the complexity and converting the recursive solution to a Dynamic programming problem."
},
{
"code": null,
"e": 29365,
"s": 29361,
"text": "C++"
},
{
"code": "// CPP program to find the maximum stolen value#include <bits/stdc++.h>using namespace std; // calculate the maximum stolen valueint maxLoot(int *hval, int n, vector<int> &dp){ // base case if(n < 0){ return 0 ; } if(n == 0){ return hval[0] ; } // If the subproblem is already solved // then return its value if(dp[n] != -1 ){ return dp[n] ; } //if current element is pick then previous cannot be picked int pick = hval[n] + maxLoot(hval, n-2, dp) ; //if current element is not picked then previous element is picked int notPick = maxLoot(hval, n-1, dp) ; // return max of picked and not picked return dp[n] = max(pick, notPick) ; } // Driver to test above codeint main(){ int hval[] = {6, 7, 1, 3, 8, 2, 4}; int n = sizeof(hval)/sizeof(hval[0]); // Initialize a dp vector vector<int> dp(n+1, -1) ; cout << \"Maximum loot possible : \" << maxLoot(hval, n-1, dp); return 0;}",
"e": 30338,
"s": 29365,
"text": null
},
{
"code": null,
"e": 30365,
"s": 30338,
"text": "Maximum loot possible : 19"
},
{
"code": null,
"e": 30388,
"s": 30365,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 30491,
"s": 30388,
"text": "Time Complexity: O(n) . Only one traversal of original array is needed. So the time complexity is O(n)"
},
{
"code": null,
"e": 30590,
"s": 30491,
"text": "Space Complexity: O(n). Recursive stack space is required of size n, so space complexity is O(n)."
},
{
"code": null,
"e": 30641,
"s": 30590,
"text": "Method 3: Dynamic Programming : Bottom Up Approach"
},
{
"code": null,
"e": 30823,
"s": 30641,
"text": "So the recursive solution can easily be deviced. The sub-problems can be stored thus reducing the complexity and converting the recursive solution to a Dynamic programming problem. "
},
{
"code": null,
"e": 30836,
"s": 30823,
"text": "Algorithm: "
},
{
"code": null,
"e": 31510,
"s": 30836,
"text": "Create an extra space dp, DP array to store the sub-problems.Tackle some basic cases, if the length of the array is 0, print 0, if the length of the array is 1, print the first element, if the length of the array is 2, print maximum of two elements.Update dp[0] as array[0] and dp[1] as maximum of array[0] and array[1]Traverse the array from the second element (2nd index) to the end of array.For every index, update dp[i] as maximum of dp[i-2] + array[i] and dp[i-1], this step defines the two cases, if an element is selected then the previous element cannot be selected and if an element is not selected then the previous element can be selected.Print the value dp[n-1]"
},
{
"code": null,
"e": 31572,
"s": 31510,
"text": "Create an extra space dp, DP array to store the sub-problems."
},
{
"code": null,
"e": 31761,
"s": 31572,
"text": "Tackle some basic cases, if the length of the array is 0, print 0, if the length of the array is 1, print the first element, if the length of the array is 2, print maximum of two elements."
},
{
"code": null,
"e": 31832,
"s": 31761,
"text": "Update dp[0] as array[0] and dp[1] as maximum of array[0] and array[1]"
},
{
"code": null,
"e": 31908,
"s": 31832,
"text": "Traverse the array from the second element (2nd index) to the end of array."
},
{
"code": null,
"e": 32165,
"s": 31908,
"text": "For every index, update dp[i] as maximum of dp[i-2] + array[i] and dp[i-1], this step defines the two cases, if an element is selected then the previous element cannot be selected and if an element is not selected then the previous element can be selected."
},
{
"code": null,
"e": 32189,
"s": 32165,
"text": "Print the value dp[n-1]"
},
{
"code": null,
"e": 32207,
"s": 32189,
"text": "Implementation: "
},
{
"code": null,
"e": 32211,
"s": 32207,
"text": "C++"
},
{
"code": null,
"e": 32213,
"s": 32211,
"text": "C"
},
{
"code": null,
"e": 32218,
"s": 32213,
"text": "Java"
},
{
"code": null,
"e": 32226,
"s": 32218,
"text": "Python3"
},
{
"code": null,
"e": 32229,
"s": 32226,
"text": "C#"
},
{
"code": null,
"e": 32233,
"s": 32229,
"text": "PHP"
},
{
"code": null,
"e": 32244,
"s": 32233,
"text": "Javascript"
},
{
"code": "// CPP program to find the maximum stolen value#include <iostream>using namespace std; // calculate the maximum stolen valueint maxLoot(int* hval, int n){ if (n == 0) return 0; if (n == 1) return hval[0]; if (n == 2) return max(hval[0], hval[1]); // dp[i] represent the maximum value stolen // so far after reaching house i. int dp[n]; // Initialize the dp[0] and dp[1] dp[0] = hval[0]; dp[1] = max(hval[0], hval[1]); // Fill remaining positions for (int i = 2; i < n; i++) dp[i] = max(hval[i] + dp[i - 2], dp[i - 1]); return dp[n - 1];} // Driver to test above codeint main(){ int hval[] = { 6, 7, 1, 3, 8, 2, 4 }; int n = sizeof(hval) / sizeof(hval[0]); cout << \"Maximum loot possible : \" << maxLoot(hval, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 33108,
"s": 32244,
"text": null
},
{
"code": "// C program to find the maximum stolen value#include <stdio.h> // Find maximum between two numbers.int max(int num1, int num2){ return (num1 > num2) ? num1 : num2;} // calculate the maximum stolen valueint maxLoot(int* hval, int n){ if (n == 0) return 0; if (n == 1) return hval[0]; if (n == 2) return max(hval[0], hval[1]); // dp[i] represent the maximum value stolen // so far after reaching house i. int dp[n]; // Initialize the dp[0] and dp[1] dp[0] = hval[0]; dp[1] = max(hval[0], hval[1]); // Fill remaining positions for (int i = 2; i < n; i++) dp[i] = max(hval[i] + dp[i - 2], dp[i - 1]); return dp[n - 1];} // Driver to test above codeint main(){ int hval[] = { 6, 7, 1, 3, 8, 2, 4 }; int n = sizeof(hval) / sizeof(hval[0]); printf(\"Maximum loot possible : %d\", maxLoot(hval, n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 34054,
"s": 33108,
"text": null
},
{
"code": "// Java program to find the maximum stolen valueimport java.io.*; class GFG { // Function to calculate the maximum stolen value static int maxLoot(int hval[], int n) { if (n == 0) return 0; if (n == 1) return hval[0]; if (n == 2) return Math.max(hval[0], hval[1]); // dp[i] represent the maximum value stolen // so far after reaching house i. int[] dp = new int[n]; // Initialize the dp[0] and dp[1] dp[0] = hval[0]; dp[1] = Math.max(hval[0], hval[1]); // Fill remaining positions for (int i = 2; i < n; i++) dp[i] = Math.max(hval[i] + dp[i - 2], dp[i - 1]); return dp[n - 1]; } // Driver program public static void main(String[] args) { int hval[] = { 6, 7, 1, 3, 8, 2, 4 }; int n = hval.length; System.out.println(\"Maximum loot value : \" + maxLoot(hval, n)); }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 35072,
"s": 34054,
"text": null
},
{
"code": "# Python3 program to find the maximum stolen value # calculate the maximum stolen valuedef maximize_loot(hval, n): if n == 0: return 0 if n == 1: return hval[0] if n == 2: return max(hval[0], hval[1]) # dp[i] represent the maximum value stolen so # for after reaching house i. dp = [0]*n # Initialize the dp[0] and dp[1] dp[0] = hval[0] dp[1] = max(hval[0], hval[1]) # Fill remaining positions for i in range(2, n): dp[i] = max(hval[i]+dp[i-2], dp[i-1]) return dp[-1] # Driver to test above codedef main(): # Value of houses hval = [6, 7, 1, 3, 8, 2, 4] # number of houses n = len(hval) print(\"Maximum loot value : {}\". format(maximize_loot(hval, n))) if __name__ == '__main__': main()",
"e": 35857,
"s": 35072,
"text": null
},
{
"code": "// C# program to find the// maximum stolen valueusing System; class GFG{ // Function to calculate the // maximum stolen value static int maxLoot(int []hval, int n) { if (n == 0) return 0; if (n == 1) return hval[0]; if (n == 2) return Math.Max(hval[0], hval[1]); // dp[i] represent the maximum value stolen // so far after reaching house i. int[] dp = new int[n]; // Initialize the dp[0] and dp[1] dp[0] = hval[0]; dp[1] = Math.Max(hval[0], hval[1]); // Fill remaining positions for (int i = 2; i<n; i++) dp[i] = Math.Max(hval[i]+dp[i-2], dp[i-1]); return dp[n-1]; } // Driver program public static void Main () { int []hval = {6, 7, 1, 3, 8, 2, 4}; int n = hval.Length; Console.WriteLine(\"Maximum loot value : \" + maxLoot(hval, n)); }} // This code is contributed by Sam007",
"e": 36851,
"s": 35857,
"text": null
},
{
"code": "<?php// PHP program to find// the maximum stolen value // calculate the maximum// stolen valuefunction maxLoot($hval, $n){ if ($n == 0) return 0; if ($n == 1) return $hval[0]; if ($n == 2) return max($hval[0], $hval[1]); // dp[i] represent the maximum // value stolen so far after // reaching house i. $dp = array(); // Initialize the // dp[0] and dp[1] $dp[0] = $hval[0]; $dp[1] = max($hval[0], $hval[1]); // Fill remaining positions for ($i = 2; $i < $n; $i++) $dp[$i] = max($hval[$i] + $dp[$i - 2], $dp[$i - 1]); return $dp[$n - 1];} // Driver Code$hval = array(6, 7, 1, 3, 8, 2, 4);$n = sizeof($hval);echo \"Maximum loot possible : \", maxLoot($hval, $n); // This code is contributed by aj_36?>",
"e": 37727,
"s": 36851,
"text": null
},
{
"code": "<script> // Javascript program to find // the maximum stolen value // Function to calculate the // maximum stolen value function maxLoot(hval, n) { if (n == 0) return 0; if (n == 1) return hval[0]; if (n == 2) return Math.max(hval[0], hval[1]); // dp[i] represent the maximum value stolen // so far after reaching house i. let dp = new Array(n); // Initialize the dp[0] and dp[1] dp[0] = hval[0]; dp[1] = Math.max(hval[0], hval[1]); // Fill remaining positions for (let i = 2; i<n; i++) dp[i] = Math.max(hval[i]+dp[i-2], dp[i-1]); return dp[n-1]; } let hval = [6, 7, 1, 3, 8, 2, 4]; let n = hval.length; document.write( \"Maximum loot value : \" + maxLoot(hval, n) ); </script>",
"e": 38597,
"s": 37727,
"text": null
},
{
"code": null,
"e": 38624,
"s": 38597,
"text": "Maximum loot possible : 19"
},
{
"code": null,
"e": 38649,
"s": 38626,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 38747,
"s": 38649,
"text": "Time Complexity: . Only one traversal of original array is needed. So the time complexity is O(n)"
},
{
"code": null,
"e": 38828,
"s": 38747,
"text": "Space Complexity: . An array is required of size n, so space complexity is O(n)."
},
{
"code": null,
"e": 39037,
"s": 38828,
"text": "Efficient Approach: By carefully observing the DP array, it can be seen that the values of previous two indices matter while calculating the value for an index. To replace the total DP array by two variables."
},
{
"code": null,
"e": 39050,
"s": 39037,
"text": "Algorithm: "
},
{
"code": null,
"e": 39804,
"s": 39050,
"text": "Tackle some basic cases, if the length of the array is 0, print 0, if the length of the array is 1, print the first element, if the length of the array is 2, print maximum of two elements.Create two variables value1 and value2 value1 as array[0] and value2 as maximum of array[0] and array[1] and a variable max_val to store the answerTraverse the array from the second element (2nd index) to the end of array.For every index, update max_val as maximum of value1 + array[i] and value2, this step defines the two cases, if an element is selected then the previous element cannot be selected and if an element is not selected then the previous element can be selected.For every index, Update value1 = value2 and value2 = max_valPrint the value of max_val"
},
{
"code": null,
"e": 39993,
"s": 39804,
"text": "Tackle some basic cases, if the length of the array is 0, print 0, if the length of the array is 1, print the first element, if the length of the array is 2, print maximum of two elements."
},
{
"code": null,
"e": 40141,
"s": 39993,
"text": "Create two variables value1 and value2 value1 as array[0] and value2 as maximum of array[0] and array[1] and a variable max_val to store the answer"
},
{
"code": null,
"e": 40218,
"s": 40141,
"text": "Traverse the array from the second element (2nd index) to the end of array."
},
{
"code": null,
"e": 40475,
"s": 40218,
"text": "For every index, update max_val as maximum of value1 + array[i] and value2, this step defines the two cases, if an element is selected then the previous element cannot be selected and if an element is not selected then the previous element can be selected."
},
{
"code": null,
"e": 40536,
"s": 40475,
"text": "For every index, Update value1 = value2 and value2 = max_val"
},
{
"code": null,
"e": 40563,
"s": 40536,
"text": "Print the value of max_val"
},
{
"code": null,
"e": 40581,
"s": 40563,
"text": "Implementation: "
},
{
"code": null,
"e": 40585,
"s": 40581,
"text": "C++"
},
{
"code": null,
"e": 40587,
"s": 40585,
"text": "C"
},
{
"code": null,
"e": 40592,
"s": 40587,
"text": "Java"
},
{
"code": null,
"e": 40600,
"s": 40592,
"text": "Python3"
},
{
"code": null,
"e": 40603,
"s": 40600,
"text": "C#"
},
{
"code": null,
"e": 40607,
"s": 40603,
"text": "PHP"
},
{
"code": null,
"e": 40618,
"s": 40607,
"text": "Javascript"
},
{
"code": "// C++ program to find the maximum stolen value#include <iostream>using namespace std; // calculate the maximum stolen valueint maxLoot(int* hval, int n){ if (n == 0) return 0; int value1 = hval[0]; if (n == 1) return value1; int value2 = max(hval[0], hval[1]); if (n == 2) return value2; // contains maximum stolen value at the end int max_val; // Fill remaining positions for (int i = 2; i < n; i++) { max_val = max(hval[i] + value1, value2); value1 = value2; value2 = max_val; } return max_val;} // Driver to test above codeint main(){ // Value of houses int hval[] = { 6, 7, 1, 3, 8, 2, 4 }; int n = sizeof(hval) / sizeof(hval[0]); cout << \"Maximum loot possible : \" << maxLoot(hval, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 41477,
"s": 40618,
"text": null
},
{
"code": "// C program to find the maximum stolen value#include <stdio.h> //Find maximum between two numbers.int max(int num1, int num2){ return (num1 > num2) ? num1 : num2;} // calculate the maximum stolen valueint maxLoot(int* hval, int n){ if (n == 0) return 0; int value1 = hval[0]; if (n == 1) return value1; int value2 = max(hval[0], hval[1]); if (n == 2) return value2; // contains maximum stolen value at the end int max_val; // Fill remaining positions for (int i = 2; i < n; i++) { max_val = max(hval[i] + value1, value2); value1 = value2; value2 = max_val; } return max_val;} // Driver to test above codeint main(){ // Value of houses int hval[] = { 6, 7, 1, 3, 8, 2, 4 }; int n = sizeof(hval) / sizeof(hval[0]); printf(\"Maximum loot possible : %d\", maxLoot(hval, n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 42415,
"s": 41477,
"text": null
},
{
"code": "// Java program to find the maximum stolen valueimport java.io.*; class GFG { // Function to calculate the maximum stolen value static int maxLoot(int hval[], int n) { if (n == 0) return 0; int value1 = hval[0]; if (n == 1) return value1; int value2 = Math.max(hval[0], hval[1]); if (n == 2) return value2; // contains maximum stolen value at the end int max_val = 0; // Fill remaining positions for (int i = 2; i < n; i++) { max_val = Math.max(hval[i] + value1, value2); value1 = value2; value2 = max_val; } return max_val; } // driver program public static void main(String[] args) { int hval[] = { 6, 7, 1, 3, 8, 2, 4 }; int n = hval.length; System.out.println(\"Maximum loot value : \" + maxLoot(hval, n)); }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 43408,
"s": 42415,
"text": null
},
{
"code": "# Python3 program to find the maximum stolen value # calculate the maximum stolen valuedef maximize_loot(hval, n): if n == 0: return 0 value1 = hval[0] if n == 1: return value1 value2 = max(hval[0], hval[1]) if n == 2: return value2 # contains maximum stolen value at the end max_val = None # Fill remaining positions for i in range(2, n): max_val = max(hval[i]+value1, value2) value1 = value2 value2 = max_val return max_val # Driver to test above codedef main(): # Value of houses hval = [6, 7, 1, 3, 8, 2, 4] # number of houses n = len(hval) print(\"Maximum loot value : {}\".format(maximize_loot(hval, n))) if __name__ == '__main__': main()",
"e": 44148,
"s": 43408,
"text": null
},
{
"code": "// C# program to find the// maximum stolen valueusing System; public class GFG{ // Function to calculate the // maximum stolen value static int maxLoot(int []hval, int n) { if (n == 0) return 0; int value1 = hval[0]; if (n == 1) return value1; int value2 = Math.Max(hval[0], hval[1]); if (n == 2) return value2; // contains maximum stolen value at the end int max_val = 0; // Fill remaining positions for (int i = 2; i < n; i++) { max_val = Math.Max(hval[i] + value1, value2); value1 = value2; value2 = max_val; } return max_val; } // Driver program public static void Main () { int []hval = {6, 7, 1, 3, 8, 2, 4}; int n = hval.Length; Console.WriteLine(\"Maximum loot value : \" + maxLoot(hval, n)); }} // This code is contributed by Sam007",
"e": 45136,
"s": 44148,
"text": null
},
{
"code": "<?php// PHP program to find// the maximum stolen value // calculate the// maximum stolen valuefunction maxLoot($hval, $n){ if ($n == 0) return 0; $value1 = $hval[0]; if ($n == 1) return $value1; $value2 = max($hval[0], $hval[1]); if ($n == 2) return $value2; // contains maximum // stolen value at the end $max_val; // Fill remaining positions for ($i = 2; $i < $n; $i++) { $max_val = max($hval[$i] + $value1, $value2); $value1 = $value2; $value2 = $max_val; } return $max_val;} // Driver code$hval = array(6, 7, 1, 3, 8, 2, 4);$n = sizeof($hval);echo \"Maximum loot value : \", maxLoot($hval, $n); // This code is contributed by ajit?>",
"e": 45909,
"s": 45136,
"text": null
},
{
"code": "<script> // Javascript program to find the // maximum stolen value // Function to calculate the // maximum stolen value function maxLoot(hval, n) { if (n == 0) return 0; let value1 = hval[0]; if (n == 1) return value1; let value2 = Math.max(hval[0], hval[1]); if (n == 2) return value2; // contains maximum stolen value at the end let max_val = 0; // Fill remaining positions for (let i = 2; i < n; i++) { max_val = Math.max(hval[i] + value1, value2); value1 = value2; value2 = max_val; } return max_val; } let hval = [6, 7, 1, 3, 8, 2, 4]; let n = hval.length; document.write(\"Maximum loot value : \" + maxLoot(hval, n)); </script>",
"e": 46783,
"s": 45909,
"text": null
},
{
"code": null,
"e": 46810,
"s": 46783,
"text": "Maximum loot possible : 19"
},
{
"code": null,
"e": 46832,
"s": 46810,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 46931,
"s": 46832,
"text": "Time Complexity: , Only one traversal of original array is needed. So the time complexity is O(n)."
},
{
"code": null,
"e": 47014,
"s": 46931,
"text": "Auxiliary Space: , No extra space is required so the space complexity is constant."
},
{
"code": null,
"e": 47438,
"s": 47014,
"text": "This article is contributed by Atul Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 47445,
"s": 47438,
"text": "Sam007"
},
{
"code": null,
"e": 47451,
"s": 47445,
"text": "jit_t"
},
{
"code": null,
"e": 47462,
"s": 47451,
"text": "andrew1234"
},
{
"code": null,
"e": 47471,
"s": 47462,
"text": "suresh07"
},
{
"code": null,
"e": 47485,
"s": 47471,
"text": "divyesh072019"
},
{
"code": null,
"e": 47506,
"s": 47485,
"text": "raghvendraprasad5678"
},
{
"code": null,
"e": 47522,
"s": 47506,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 47535,
"s": 47522,
"text": "prasanna1995"
},
{
"code": null,
"e": 47552,
"s": 47535,
"text": "arorakashish0911"
},
{
"code": null,
"e": 47567,
"s": 47552,
"text": "adityakumar129"
},
{
"code": null,
"e": 47574,
"s": 47567,
"text": "Amazon"
},
{
"code": null,
"e": 47582,
"s": 47574,
"text": "FactSet"
},
{
"code": null,
"e": 47596,
"s": 47582,
"text": "Oxigen Wallet"
},
{
"code": null,
"e": 47606,
"s": 47596,
"text": "OYO Rooms"
},
{
"code": null,
"e": 47612,
"s": 47606,
"text": "Paytm"
},
{
"code": null,
"e": 47620,
"s": 47612,
"text": "Walmart"
},
{
"code": null,
"e": 47626,
"s": 47620,
"text": "Yahoo"
},
{
"code": null,
"e": 47633,
"s": 47626,
"text": "Arrays"
},
{
"code": null,
"e": 47653,
"s": 47633,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 47659,
"s": 47653,
"text": "Paytm"
},
{
"code": null,
"e": 47666,
"s": 47659,
"text": "Amazon"
},
{
"code": null,
"e": 47676,
"s": 47666,
"text": "OYO Rooms"
},
{
"code": null,
"e": 47684,
"s": 47676,
"text": "FactSet"
},
{
"code": null,
"e": 47692,
"s": 47684,
"text": "Walmart"
},
{
"code": null,
"e": 47706,
"s": 47692,
"text": "Oxigen Wallet"
},
{
"code": null,
"e": 47712,
"s": 47706,
"text": "Yahoo"
},
{
"code": null,
"e": 47719,
"s": 47712,
"text": "Arrays"
},
{
"code": null,
"e": 47739,
"s": 47719,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 47837,
"s": 47739,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 47905,
"s": 47837,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 47949,
"s": 47905,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 47997,
"s": 47949,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 48020,
"s": 47997,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 48052,
"s": 48020,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 48081,
"s": 48052,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 48115,
"s": 48081,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 48146,
"s": 48115,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 48179,
"s": 48146,
"text": "Floyd Warshall Algorithm | DP-16"
}
] |
How Java 8 Helps in Improving Performance of HashMap? - GeeksforGeeks
|
17 Jun, 2021
Here we will be discussing out how we can, we improve the performance while using HashMap in Java, the Importance of the hashCode() contract and why is it very important to have an efficient hashcode, and what happens when we use an in-efficient hashcode. Let us directly roll over to implementing the same over the same set size of keys in our HashMap. It is as follows:
Implementation: Here no such concept is introduced, so a naive approach is being applied over our HashMap.
Example 1:
Java
// Java Program to Illustrate In-efficient Technique// While using HashMap // Importing Map and HashMap utility classes// from java.util packageimport java.util.HashMap;import java.util.Map; // Main classclass HashMapEx2 { // main driver method public static void main(String[] args) { // Creating a Map object // Declaring object of user-defined class and string // type Map<Student, String> studentMap = new HashMap<>(); long startTime = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { studentMap.put(new Student("saty" + i), "satyy" + i); } studentMap.forEach( (k, v) -> System.out.println(k + " : " + v)); long endTime = System.currentTimeMillis(); long timeElapsed = endTime - startTime; System.out.println( "\n Execution time in milliseconds for In-Efficient hashcode : " + timeElapsed + " milliseconds."); }} /*Student class.*/class Student { String name; public Student(String name) { super(); this.name = name; } @Override public String toString() { return "Student [name=" + name + "]"; } /* Very in-efficient hashcode override */ @Override public int hashCode() { return 12; /* Very inefficient hashcode, returns 12 for every key, that means all the keys will end up in the same bucket */ } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Student other = (Student)obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }}
Output: It contains humongous lines as the output to illustrate milliseconds taken hence, the last snapshot off the output roll is appended below in order to figure out the time taken for all the operations. It is as follows:
Output Explanation: In the above program, we use Student as a HashMap key and the hashCode() override in the Student class is written very inefficiently which returns the same hashcode for every Student object.
Why an efficient hashcode is so darn important?
When you run the above program, what actually happens behind the scene is that when the HashMap is created it stores all the 10000 keys of student objects into the same bucket. As a result, all the keys get stored on a single bucket which results in a huge performance hit, and you can see that the time taken for the execution of the first program is approx 1700 milliseconds.
Now, in the program below, our hashcode override in the Student class is efficient and returns unique hashcode for every Student Object. As a result, each hashmap key is stored in a separate bucket, which improves the performance by ‘n’ times for storing the keys, and you can see that the time taken for the execution of the second program is only about 300 milliseconds
Example 2:
Java
// Java Program to Illustrate In-efficient Technique// While using HashMap // Importing Map and HashMap utility classes// from java.util packageimport java.util.HashMap;import java.util.Map; // Main classclass HashMapEx3 { // main driver method public static void main(String[] args) { Map<Student, String> studentMap = new HashMap<>(); long startTime = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { studentMap.put(new Student("saty" + i), "satyy" + i); } studentMap.forEach( (k, v) -> System.out.println(k + " : " + v)); long endTime = System.currentTimeMillis(); long timeElapsed = endTime - startTime; System.out.println( "\n Execution time in milliseconds for Efficient hashCode: " + timeElapsed + " milliseconds"); }} /*Student class.*/class Student { String name; public Student(String name) { super(); this.name = name; } @Override public String toString() { return "Student [name=" + name + "]"; } /* Efficient hashcode override */ @Override public int hashCode() { return name.hashCode() * 12; /* Efficient hashcode, returns unique hashcode for every key, that means the keys will be distributed into unique buckets */ } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Student other = (Student)obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }}
Output: It contains humongous lines as the output to illustrate milliseconds taken hence, last snapshot off the output roll is appended below in order to figure out the time taken for all the operations. It is as follows:
We can figure out a significant change wherein example 1 takes close to 1700 milliseconds and here as depicted from the output, it takes close to 180 seconds only. Hence, the multiplier of 10X is justified when we compare the above-demonstrated examples.
Java 8
Java-Collections
Java-HashMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 25597,
"s": 25225,
"text": "Here we will be discussing out how we can, we improve the performance while using HashMap in Java, the Importance of the hashCode() contract and why is it very important to have an efficient hashcode, and what happens when we use an in-efficient hashcode. Let us directly roll over to implementing the same over the same set size of keys in our HashMap. It is as follows:"
},
{
"code": null,
"e": 25704,
"s": 25597,
"text": "Implementation: Here no such concept is introduced, so a naive approach is being applied over our HashMap."
},
{
"code": null,
"e": 25715,
"s": 25704,
"text": "Example 1:"
},
{
"code": null,
"e": 25720,
"s": 25715,
"text": "Java"
},
{
"code": "// Java Program to Illustrate In-efficient Technique// While using HashMap // Importing Map and HashMap utility classes// from java.util packageimport java.util.HashMap;import java.util.Map; // Main classclass HashMapEx2 { // main driver method public static void main(String[] args) { // Creating a Map object // Declaring object of user-defined class and string // type Map<Student, String> studentMap = new HashMap<>(); long startTime = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { studentMap.put(new Student(\"saty\" + i), \"satyy\" + i); } studentMap.forEach( (k, v) -> System.out.println(k + \" : \" + v)); long endTime = System.currentTimeMillis(); long timeElapsed = endTime - startTime; System.out.println( \"\\n Execution time in milliseconds for In-Efficient hashcode : \" + timeElapsed + \" milliseconds.\"); }} /*Student class.*/class Student { String name; public Student(String name) { super(); this.name = name; } @Override public String toString() { return \"Student [name=\" + name + \"]\"; } /* Very in-efficient hashcode override */ @Override public int hashCode() { return 12; /* Very inefficient hashcode, returns 12 for every key, that means all the keys will end up in the same bucket */ } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Student other = (Student)obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }}",
"e": 27658,
"s": 25720,
"text": null
},
{
"code": null,
"e": 27884,
"s": 27658,
"text": "Output: It contains humongous lines as the output to illustrate milliseconds taken hence, the last snapshot off the output roll is appended below in order to figure out the time taken for all the operations. It is as follows:"
},
{
"code": null,
"e": 28096,
"s": 27884,
"text": "Output Explanation: In the above program, we use Student as a HashMap key and the hashCode() override in the Student class is written very inefficiently which returns the same hashcode for every Student object. "
},
{
"code": null,
"e": 28144,
"s": 28096,
"text": "Why an efficient hashcode is so darn important?"
},
{
"code": null,
"e": 28522,
"s": 28144,
"text": "When you run the above program, what actually happens behind the scene is that when the HashMap is created it stores all the 10000 keys of student objects into the same bucket. As a result, all the keys get stored on a single bucket which results in a huge performance hit, and you can see that the time taken for the execution of the first program is approx 1700 milliseconds."
},
{
"code": null,
"e": 28894,
"s": 28522,
"text": "Now, in the program below, our hashcode override in the Student class is efficient and returns unique hashcode for every Student Object. As a result, each hashmap key is stored in a separate bucket, which improves the performance by ‘n’ times for storing the keys, and you can see that the time taken for the execution of the second program is only about 300 milliseconds"
},
{
"code": null,
"e": 28905,
"s": 28894,
"text": "Example 2:"
},
{
"code": null,
"e": 28910,
"s": 28905,
"text": "Java"
},
{
"code": "// Java Program to Illustrate In-efficient Technique// While using HashMap // Importing Map and HashMap utility classes// from java.util packageimport java.util.HashMap;import java.util.Map; // Main classclass HashMapEx3 { // main driver method public static void main(String[] args) { Map<Student, String> studentMap = new HashMap<>(); long startTime = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { studentMap.put(new Student(\"saty\" + i), \"satyy\" + i); } studentMap.forEach( (k, v) -> System.out.println(k + \" : \" + v)); long endTime = System.currentTimeMillis(); long timeElapsed = endTime - startTime; System.out.println( \"\\n Execution time in milliseconds for Efficient hashCode: \" + timeElapsed + \" milliseconds\"); }} /*Student class.*/class Student { String name; public Student(String name) { super(); this.name = name; } @Override public String toString() { return \"Student [name=\" + name + \"]\"; } /* Efficient hashcode override */ @Override public int hashCode() { return name.hashCode() * 12; /* Efficient hashcode, returns unique hashcode for every key, that means the keys will be distributed into unique buckets */ } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Student other = (Student)obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }}",
"e": 30767,
"s": 28910,
"text": null
},
{
"code": null,
"e": 30989,
"s": 30767,
"text": "Output: It contains humongous lines as the output to illustrate milliseconds taken hence, last snapshot off the output roll is appended below in order to figure out the time taken for all the operations. It is as follows:"
},
{
"code": null,
"e": 31244,
"s": 30989,
"text": "We can figure out a significant change wherein example 1 takes close to 1700 milliseconds and here as depicted from the output, it takes close to 180 seconds only. Hence, the multiplier of 10X is justified when we compare the above-demonstrated examples."
},
{
"code": null,
"e": 31251,
"s": 31244,
"text": "Java 8"
},
{
"code": null,
"e": 31268,
"s": 31251,
"text": "Java-Collections"
},
{
"code": null,
"e": 31281,
"s": 31268,
"text": "Java-HashMap"
},
{
"code": null,
"e": 31286,
"s": 31281,
"text": "Java"
},
{
"code": null,
"e": 31291,
"s": 31286,
"text": "Java"
},
{
"code": null,
"e": 31308,
"s": 31291,
"text": "Java-Collections"
},
{
"code": null,
"e": 31406,
"s": 31308,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31421,
"s": 31406,
"text": "Stream In Java"
},
{
"code": null,
"e": 31442,
"s": 31421,
"text": "Constructors in Java"
},
{
"code": null,
"e": 31461,
"s": 31442,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 31491,
"s": 31461,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 31537,
"s": 31491,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 31554,
"s": 31537,
"text": "Generics in Java"
},
{
"code": null,
"e": 31575,
"s": 31554,
"text": "Introduction to Java"
},
{
"code": null,
"e": 31618,
"s": 31575,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 31654,
"s": 31618,
"text": "Internal Working of HashMap in Java"
}
] |
Python - PyTorch clamp() method - GeeksforGeeks
|
26 May, 2020
PyTorch torch.clamp() method clamps all the input elements into the range [ min, max ] and return a resulting tensor.
Syntax: torch.clamp(inp, min, max, out=None)
Arguments
inp: This is input tensor.
min: This is a number and specifies the lower-bound of the range to which input to be clamped.
max: This is a number and specifies the upper-bound of the range to which input to be clamped.
out: The output tensor.
Return: It returns a Tensor.
# Importing the PyTorch library import torch # A constant tensor of size na = torch.randn(6)print(a) # Applying the clamp function and # storing the result in 'out'out = torch.clamp(a, min = 0.5, max = 0.9)print(out)
Output:
-0.9214
-0.1268
1.1570
-0.2753
-0.0746
0.7957
[torch.FloatTensor of size 6]
0.5000
0.5000
0.9000
0.5000
0.5000
0.7957
[torch.FloatTensor of size 6]
Example 2:
# Importing the PyTorch library import torch # A constant tensor of size na = torch.FloatTensor([1, 4, 6, 8, 10, 14])print(a) # Applying the clamp function and # storing the result in 'out'out = torch.clamp(a, min = 5, max = 10)print(out)
Output:
1
4
6
8
10
14
[torch.FloatTensor of size 6]
5
5
6
8
10
10
[torch.FloatTensor of size 6]?
Python-PyTorch
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
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": 25799,
"s": 25771,
"text": "\n26 May, 2020"
},
{
"code": null,
"e": 25917,
"s": 25799,
"text": "PyTorch torch.clamp() method clamps all the input elements into the range [ min, max ] and return a resulting tensor."
},
{
"code": null,
"e": 25962,
"s": 25917,
"text": "Syntax: torch.clamp(inp, min, max, out=None)"
},
{
"code": null,
"e": 25972,
"s": 25962,
"text": "Arguments"
},
{
"code": null,
"e": 25999,
"s": 25972,
"text": "inp: This is input tensor."
},
{
"code": null,
"e": 26094,
"s": 25999,
"text": "min: This is a number and specifies the lower-bound of the range to which input to be clamped."
},
{
"code": null,
"e": 26189,
"s": 26094,
"text": "max: This is a number and specifies the upper-bound of the range to which input to be clamped."
},
{
"code": null,
"e": 26213,
"s": 26189,
"text": "out: The output tensor."
},
{
"code": null,
"e": 26242,
"s": 26213,
"text": "Return: It returns a Tensor."
},
{
"code": "# Importing the PyTorch library import torch # A constant tensor of size na = torch.randn(6)print(a) # Applying the clamp function and # storing the result in 'out'out = torch.clamp(a, min = 0.5, max = 0.9)print(out)",
"e": 26464,
"s": 26242,
"text": null
},
{
"code": null,
"e": 26472,
"s": 26464,
"text": "Output:"
},
{
"code": null,
"e": 26630,
"s": 26472,
"text": " -0.9214\n-0.1268\n 1.1570\n-0.2753\n-0.0746\n 0.7957\n[torch.FloatTensor of size 6]\n 0.5000\n 0.5000\n 0.9000\n 0.5000\n 0.5000\n 0.7957\n[torch.FloatTensor of size 6]\n"
},
{
"code": null,
"e": 26641,
"s": 26630,
"text": "Example 2:"
},
{
"code": "# Importing the PyTorch library import torch # A constant tensor of size na = torch.FloatTensor([1, 4, 6, 8, 10, 14])print(a) # Applying the clamp function and # storing the result in 'out'out = torch.clamp(a, min = 5, max = 10)print(out) ",
"e": 26886,
"s": 26641,
"text": null
},
{
"code": null,
"e": 26894,
"s": 26886,
"text": "Output:"
},
{
"code": null,
"e": 27003,
"s": 26894,
"text": " 1\n 4\n 6\n 8\n 10\n 14\n[torch.FloatTensor of size 6]\n 5\n 5\n 6\n 8\n 10\n 10\n[torch.FloatTensor of size 6]?\n"
},
{
"code": null,
"e": 27018,
"s": 27003,
"text": "Python-PyTorch"
},
{
"code": null,
"e": 27025,
"s": 27018,
"text": "Python"
},
{
"code": null,
"e": 27123,
"s": 27025,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27141,
"s": 27123,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27173,
"s": 27141,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27195,
"s": 27173,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27237,
"s": 27195,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27267,
"s": 27237,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27293,
"s": 27267,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27322,
"s": 27293,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27366,
"s": 27322,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27403,
"s": 27366,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Image based Steganography using Python - GeeksforGeeks
|
20 Aug, 2020
Steganography is the method of hiding secret data in any image/audio/video. In a nutshell, the main motive of steganography is to hide the intended information within any image/audio/video that doesn’t appear to be secret just by looking at it.The idea behind image-based Steganography is very simple. Images are composed of digital data (pixels), which describes what’s inside the picture, usually the colors of all the pixels. Since we know every image is made up of pixels and every pixel contains 3-values (red, green, blue).
Every byte of data is converted to its 8-bit binary code using ASCII values. Now pixels are read from left to right in a group of 3 containing a total of 9 values. The first 8-values are used to store binary data. The value is made odd if 1 occurs and even if 0 occurs. For example : Suppose the message to be hidden is ‘ Hii ‘. Since the message is of 3-bytes, therefore, pixels required to encode the data is 3 x 3 = 9. Consider a 4 x 3 image with a total 12-pixels, which are sufficient to encode the given data.
[(27, 64, 164), (248, 244, 194), (174, 246, 250), (149, 95, 232),
(188, 156, 169), (71, 167, 127), (132, 173, 97), (113, 69, 206),
(255, 29, 213), (53, 153, 220), (246, 225, 229), (142, 82, 175)]
ASCII value of ‘ H ‘ is 72 whose binary equivalent is 01001000.Taking first 3-pixels (27, 64, 164), (248, 244, 194), (174, 246, 250) to encode. Now change the pixel to odd for 1 and even for 0. So, the modifies pixels are (26, 63, 164), (248, 243, 194), (174, 246, 250). Since we have to encode more data, therefore, the last value should be even. Similarly, ‘i‘ can be encoded in this image.The new image will look like :
[(26, 63, 164), (248, 243, 194), (174, 246, 250), (148, 95, 231),
(188, 155, 168), (70, 167, 126), (132, 173, 97), (112, 69, 206),
(254, 29, 213), (53, 153, 220), (246, 225, 229), (142, 82, 175)]
To decode, three pixels are read at a time, till the last value is odd, which means the message is over. Every 3-pixels contain a binary data, which can be extracted by the same encoding logic. If the value if odd the binary bit is 1 else 0.
Below is the implementation of the above idea :
Python
# Python program implementing Image Steganography # PIL module is used to extract# pixels of image and modify itfrom PIL import Image # Convert encoding data into 8-bit binary# form using ASCII value of charactersdef genData(data): # list of binary codes # of given data newd = [] for i in data: newd.append(format(ord(i), '08b')) return newd # Pixels are modified according to the# 8-bit binary data and finally returneddef modPix(pix, data): datalist = genData(data) lendata = len(datalist) imdata = iter(pix) for i in range(lendata): # Extracting 3 pixels at a time pix = [value for value in imdata.__next__()[:3] + imdata.__next__()[:3] + imdata.__next__()[:3]] # Pixel value should be made # odd for 1 and even for 0 for j in range(0, 8): if (datalist[i][j] == '0' and pix[j]% 2 != 0): pix[j] -= 1 elif (datalist[i][j] == '1' and pix[j] % 2 == 0): if(pix[j] != 0): pix[j] -= 1 else: pix[j] += 1 # pix[j] -= 1 # Eighth pixel of every set tells # whether to stop ot read further. # 0 means keep reading; 1 means thec # message is over. if (i == lendata - 1): if (pix[-1] % 2 == 0): if(pix[-1] != 0): pix[-1] -= 1 else: pix[-1] += 1 else: if (pix[-1] % 2 != 0): pix[-1] -= 1 pix = tuple(pix) yield pix[0:3] yield pix[3:6] yield pix[6:9] def encode_enc(newimg, data): w = newimg.size[0] (x, y) = (0, 0) for pixel in modPix(newimg.getdata(), data): # Putting modified pixels in the new image newimg.putpixel((x, y), pixel) if (x == w - 1): x = 0 y += 1 else: x += 1 # Encode data into imagedef encode(): img = input("Enter image name(with extension) : ") image = Image.open(img, 'r') data = input("Enter data to be encoded : ") if (len(data) == 0): raise ValueError('Data is empty') newimg = image.copy() encode_enc(newimg, data) new_img_name = input("Enter the name of new image(with extension) : ") newimg.save(new_img_name, str(new_img_name.split(".")[1].upper())) # Decode the data in the imagedef decode(): img = input("Enter image name(with extension) : ") image = Image.open(img, 'r') data = '' imgdata = iter(image.getdata()) while (True): pixels = [value for value in imgdata.__next__()[:3] + imgdata.__next__()[:3] + imgdata.__next__()[:3]] # string of binary data binstr = '' for i in pixels[:8]: if (i % 2 == 0): binstr += '0' else: binstr += '1' data += chr(int(binstr, 2)) if (pixels[-1] % 2 != 0): return data # Main Functiondef main(): a = int(input(":: Welcome to Steganography ::\n" "1. Encode\n2. Decode\n")) if (a == 1): encode() elif (a == 2): print("Decoded Word : " + decode()) else: raise Exception("Enter correct input") # Driver Codeif __name__ == '__main__' : # Calling main function main()
Output :
PratikBhattacharjee2
AshwinGoel
cryptography
Image-Processing
Python
Technical Scripter
cryptography
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": 25937,
"s": 25909,
"text": "\n20 Aug, 2020"
},
{
"code": null,
"e": 26468,
"s": 25937,
"text": "Steganography is the method of hiding secret data in any image/audio/video. In a nutshell, the main motive of steganography is to hide the intended information within any image/audio/video that doesn’t appear to be secret just by looking at it.The idea behind image-based Steganography is very simple. Images are composed of digital data (pixels), which describes what’s inside the picture, usually the colors of all the pixels. Since we know every image is made up of pixels and every pixel contains 3-values (red, green, blue). "
},
{
"code": null,
"e": 26985,
"s": 26468,
"text": "Every byte of data is converted to its 8-bit binary code using ASCII values. Now pixels are read from left to right in a group of 3 containing a total of 9 values. The first 8-values are used to store binary data. The value is made odd if 1 occurs and even if 0 occurs. For example : Suppose the message to be hidden is ‘ Hii ‘. Since the message is of 3-bytes, therefore, pixels required to encode the data is 3 x 3 = 9. Consider a 4 x 3 image with a total 12-pixels, which are sufficient to encode the given data. "
},
{
"code": null,
"e": 27183,
"s": 26985,
"text": "[(27, 64, 164), (248, 244, 194), (174, 246, 250), (149, 95, 232),\n(188, 156, 169), (71, 167, 127), (132, 173, 97), (113, 69, 206),\n(255, 29, 213), (53, 153, 220), (246, 225, 229), (142, 82, 175)]\n\n"
},
{
"code": null,
"e": 27607,
"s": 27183,
"text": "ASCII value of ‘ H ‘ is 72 whose binary equivalent is 01001000.Taking first 3-pixels (27, 64, 164), (248, 244, 194), (174, 246, 250) to encode. Now change the pixel to odd for 1 and even for 0. So, the modifies pixels are (26, 63, 164), (248, 243, 194), (174, 246, 250). Since we have to encode more data, therefore, the last value should be even. Similarly, ‘i‘ can be encoded in this image.The new image will look like : "
},
{
"code": null,
"e": 27805,
"s": 27607,
"text": "[(26, 63, 164), (248, 243, 194), (174, 246, 250), (148, 95, 231),\n(188, 155, 168), (70, 167, 126), (132, 173, 97), (112, 69, 206),\n(254, 29, 213), (53, 153, 220), (246, 225, 229), (142, 82, 175)]\n\n"
},
{
"code": null,
"e": 28050,
"s": 27807,
"text": "To decode, three pixels are read at a time, till the last value is odd, which means the message is over. Every 3-pixels contain a binary data, which can be extracted by the same encoding logic. If the value if odd the binary bit is 1 else 0. "
},
{
"code": null,
"e": 28100,
"s": 28050,
"text": "Below is the implementation of the above idea : "
},
{
"code": null,
"e": 28107,
"s": 28100,
"text": "Python"
},
{
"code": "# Python program implementing Image Steganography # PIL module is used to extract# pixels of image and modify itfrom PIL import Image # Convert encoding data into 8-bit binary# form using ASCII value of charactersdef genData(data): # list of binary codes # of given data newd = [] for i in data: newd.append(format(ord(i), '08b')) return newd # Pixels are modified according to the# 8-bit binary data and finally returneddef modPix(pix, data): datalist = genData(data) lendata = len(datalist) imdata = iter(pix) for i in range(lendata): # Extracting 3 pixels at a time pix = [value for value in imdata.__next__()[:3] + imdata.__next__()[:3] + imdata.__next__()[:3]] # Pixel value should be made # odd for 1 and even for 0 for j in range(0, 8): if (datalist[i][j] == '0' and pix[j]% 2 != 0): pix[j] -= 1 elif (datalist[i][j] == '1' and pix[j] % 2 == 0): if(pix[j] != 0): pix[j] -= 1 else: pix[j] += 1 # pix[j] -= 1 # Eighth pixel of every set tells # whether to stop ot read further. # 0 means keep reading; 1 means thec # message is over. if (i == lendata - 1): if (pix[-1] % 2 == 0): if(pix[-1] != 0): pix[-1] -= 1 else: pix[-1] += 1 else: if (pix[-1] % 2 != 0): pix[-1] -= 1 pix = tuple(pix) yield pix[0:3] yield pix[3:6] yield pix[6:9] def encode_enc(newimg, data): w = newimg.size[0] (x, y) = (0, 0) for pixel in modPix(newimg.getdata(), data): # Putting modified pixels in the new image newimg.putpixel((x, y), pixel) if (x == w - 1): x = 0 y += 1 else: x += 1 # Encode data into imagedef encode(): img = input(\"Enter image name(with extension) : \") image = Image.open(img, 'r') data = input(\"Enter data to be encoded : \") if (len(data) == 0): raise ValueError('Data is empty') newimg = image.copy() encode_enc(newimg, data) new_img_name = input(\"Enter the name of new image(with extension) : \") newimg.save(new_img_name, str(new_img_name.split(\".\")[1].upper())) # Decode the data in the imagedef decode(): img = input(\"Enter image name(with extension) : \") image = Image.open(img, 'r') data = '' imgdata = iter(image.getdata()) while (True): pixels = [value for value in imgdata.__next__()[:3] + imgdata.__next__()[:3] + imgdata.__next__()[:3]] # string of binary data binstr = '' for i in pixels[:8]: if (i % 2 == 0): binstr += '0' else: binstr += '1' data += chr(int(binstr, 2)) if (pixels[-1] % 2 != 0): return data # Main Functiondef main(): a = int(input(\":: Welcome to Steganography ::\\n\" \"1. Encode\\n2. Decode\\n\")) if (a == 1): encode() elif (a == 2): print(\"Decoded Word : \" + decode()) else: raise Exception(\"Enter correct input\") # Driver Codeif __name__ == '__main__' : # Calling main function main()",
"e": 31543,
"s": 28107,
"text": null
},
{
"code": null,
"e": 31554,
"s": 31543,
"text": "Output : "
},
{
"code": null,
"e": 31577,
"s": 31556,
"text": "PratikBhattacharjee2"
},
{
"code": null,
"e": 31588,
"s": 31577,
"text": "AshwinGoel"
},
{
"code": null,
"e": 31601,
"s": 31588,
"text": "cryptography"
},
{
"code": null,
"e": 31618,
"s": 31601,
"text": "Image-Processing"
},
{
"code": null,
"e": 31625,
"s": 31618,
"text": "Python"
},
{
"code": null,
"e": 31644,
"s": 31625,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31657,
"s": 31644,
"text": "cryptography"
},
{
"code": null,
"e": 31755,
"s": 31657,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31773,
"s": 31755,
"text": "Python Dictionary"
},
{
"code": null,
"e": 31808,
"s": 31773,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 31840,
"s": 31808,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31862,
"s": 31840,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 31904,
"s": 31862,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 31934,
"s": 31904,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 31960,
"s": 31934,
"text": "Python String | replace()"
},
{
"code": null,
"e": 31989,
"s": 31960,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 32033,
"s": 31989,
"text": "Reading and Writing to text files in Python"
}
] |
How to redirect to another webpage in HTML? - GeeksforGeeks
|
24 Apr, 2019
It is often required to redirect to another webpage on loading a webpage, for example, due to the contents being moved to the new webpage.
Demonstrated here are two simple methods to redirect to another webpage on load.
Method-1: Using http-equiv attribute of the meta tag in HTML.
Syntax:
<meta http-equiv="refresh" content="seconds; url=URL">
Example-1:
<!DOCTYPE HTML><html> <head> <title> Redirect to GeeksforGeeks </title> <!-- meta tag to redirect to ide.geeksforgeeks.org after 2 seconds --> <meta http-equiv="refresh" content="2; url=https://ide.geeksforgeeks.org/"></head> <body> <!-- Link to the destination page in case the refresh does not work --> You will be redirected to GeeksforGeeks in a moment. <br> If you are not redirected automatically, <a href="https://ide.geeksforgeeks.org/"> click here </a>.</body> </html>
Output:Before:
After 2 seconds:
Note: In some older browsers, like Internet Explorer 6, refresh may cause unexpected results and impair the browser’s Back button. This is compensated for in most modern browsers (Internet Explorer 7 and higher, Google Chrome, Mozilla Firefox, Microsoft Edge).
Method-2: Using location.href in JavaScript.
Syntax:
window.location.href = "URL"
Example-2:
<!DOCTYPE HTML><html> <head> <title> Redirect to GeeksforGeeks </title> <script type="text/javascript"> /* location.href used to redirect to ide.geeksforgeeks.org */ window.location.href = "https://ide.geeksforgeeks.org/" </script></head> <body> <!-- Link to the destination page in case the redirect does not work --> You will be redirected to GeeksforGeeks in a moment. <br> If you are not redirected automatically, <a href="https://ide.geeksforgeeks.org/"> click here </a>.</body> </html>
Output:
Note: This method works fine for any JavaScript enabled browser.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Misc
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 25617,
"s": 25589,
"text": "\n24 Apr, 2019"
},
{
"code": null,
"e": 25756,
"s": 25617,
"text": "It is often required to redirect to another webpage on loading a webpage, for example, due to the contents being moved to the new webpage."
},
{
"code": null,
"e": 25837,
"s": 25756,
"text": "Demonstrated here are two simple methods to redirect to another webpage on load."
},
{
"code": null,
"e": 25899,
"s": 25837,
"text": "Method-1: Using http-equiv attribute of the meta tag in HTML."
},
{
"code": null,
"e": 25907,
"s": 25899,
"text": "Syntax:"
},
{
"code": null,
"e": 25963,
"s": 25907,
"text": "<meta http-equiv=\"refresh\" content=\"seconds; url=URL\">\n"
},
{
"code": null,
"e": 25974,
"s": 25963,
"text": "Example-1:"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Redirect to GeeksforGeeks </title> <!-- meta tag to redirect to ide.geeksforgeeks.org after 2 seconds --> <meta http-equiv=\"refresh\" content=\"2; url=https://ide.geeksforgeeks.org/\"></head> <body> <!-- Link to the destination page in case the refresh does not work --> You will be redirected to GeeksforGeeks in a moment. <br> If you are not redirected automatically, <a href=\"https://ide.geeksforgeeks.org/\"> click here </a>.</body> </html>",
"e": 26535,
"s": 25974,
"text": null
},
{
"code": null,
"e": 26550,
"s": 26535,
"text": "Output:Before:"
},
{
"code": null,
"e": 26567,
"s": 26550,
"text": "After 2 seconds:"
},
{
"code": null,
"e": 26828,
"s": 26567,
"text": "Note: In some older browsers, like Internet Explorer 6, refresh may cause unexpected results and impair the browser’s Back button. This is compensated for in most modern browsers (Internet Explorer 7 and higher, Google Chrome, Mozilla Firefox, Microsoft Edge)."
},
{
"code": null,
"e": 26873,
"s": 26828,
"text": "Method-2: Using location.href in JavaScript."
},
{
"code": null,
"e": 26881,
"s": 26873,
"text": "Syntax:"
},
{
"code": null,
"e": 26911,
"s": 26881,
"text": "window.location.href = \"URL\"\n"
},
{
"code": null,
"e": 26922,
"s": 26911,
"text": "Example-2:"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Redirect to GeeksforGeeks </title> <script type=\"text/javascript\"> /* location.href used to redirect to ide.geeksforgeeks.org */ window.location.href = \"https://ide.geeksforgeeks.org/\" </script></head> <body> <!-- Link to the destination page in case the redirect does not work --> You will be redirected to GeeksforGeeks in a moment. <br> If you are not redirected automatically, <a href=\"https://ide.geeksforgeeks.org/\"> click here </a>.</body> </html>",
"e": 27498,
"s": 26922,
"text": null
},
{
"code": null,
"e": 27506,
"s": 27498,
"text": "Output:"
},
{
"code": null,
"e": 27571,
"s": 27506,
"text": "Note: This method works fine for any JavaScript enabled browser."
},
{
"code": null,
"e": 27708,
"s": 27571,
"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": 27718,
"s": 27708,
"text": "HTML-Misc"
},
{
"code": null,
"e": 27723,
"s": 27718,
"text": "HTML"
},
{
"code": null,
"e": 27740,
"s": 27723,
"text": "Web Technologies"
},
{
"code": null,
"e": 27745,
"s": 27740,
"text": "HTML"
},
{
"code": null,
"e": 27843,
"s": 27745,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27891,
"s": 27843,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 27915,
"s": 27891,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 27965,
"s": 27915,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 28015,
"s": 27965,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 28052,
"s": 28015,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 28092,
"s": 28052,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28125,
"s": 28092,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28170,
"s": 28125,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28213,
"s": 28170,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python - Read CSV Columns Into List - GeeksforGeeks
|
17 Sep, 2021
CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format. In this article, we will read data from a CSV file into a list. We will use the panda’s library to read the data into a list.
File Used: file.
Method 1: Using Pandas
Here, we have the read_csv() function which helps to read the CSV file by simply creating its object. The column name can be written inside this object to access a particular column, the same as we do in accessing the elements of the array. Pandas library has a function named as tolist() that converts the data into a list that can be used as per our requirement. So, we will use this to convert the column data into a list. Finally, we will print the list.
Approach:
Import the module.
Read data from CSV file.
Convert it into the list.
Print the list.
Below is the implementation:
Python3
# importing modulefrom pandas import * # reading CSV filedata = read_csv("company_sales_data.csv") # converting column data to listmonth = data['month_number'].tolist()fc = data['facecream'].tolist()fw = data['facewash'].tolist()tp = data['toothpaste'].tolist()sh = data['shampoo'].tolist() # printing list dataprint('Facecream:', fc)print('Facewash:', fw)print('Toothpaste:', tp)print('Shampoo:', sh)
Output:
Method 2: Using csv module
In this method we will import the csv library and open the file in reading mode, then we will use the DictReader() function to read the data of the CSV file. This function is like a regular reader, but it maps the information to a dictionary whose keys are given by the column names and all the values as keys. We will create empty lists so that we can store the values in it. Finally, we access the key values and append them into the empty lists and print that list.
Python3
# importing the moduleimport csv # open the file in read modefilename = open('company_sales_data.csv', 'r') # creating dictreader objectfile = csv.DictReader(filename) # creating empty listsmonth = []totalprofit = []totalunit = [] # iterating over each row and append# values to empty listfor col in file: month.append(col['month_number']) totalprofit.append(col['moisturizer']) totalunit.append(col['total_units']) # printing listsprint('Month:', month)print('Moisturizer:', totalprofit)print('Total Units:', totalunit)
Output:
anikakapoor
rajeev0719singh
Picked
python-csv
Technical Scripter 2020
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": 26269,
"s": 26241,
"text": "\n17 Sep, 2021"
},
{
"code": null,
"e": 26654,
"s": 26269,
"text": "CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format. In this article, we will read data from a CSV file into a list. We will use the panda’s library to read the data into a list. "
},
{
"code": null,
"e": 26671,
"s": 26654,
"text": "File Used: file."
},
{
"code": null,
"e": 26694,
"s": 26671,
"text": "Method 1: Using Pandas"
},
{
"code": null,
"e": 27153,
"s": 26694,
"text": "Here, we have the read_csv() function which helps to read the CSV file by simply creating its object. The column name can be written inside this object to access a particular column, the same as we do in accessing the elements of the array. Pandas library has a function named as tolist() that converts the data into a list that can be used as per our requirement. So, we will use this to convert the column data into a list. Finally, we will print the list."
},
{
"code": null,
"e": 27163,
"s": 27153,
"text": "Approach:"
},
{
"code": null,
"e": 27182,
"s": 27163,
"text": "Import the module."
},
{
"code": null,
"e": 27207,
"s": 27182,
"text": "Read data from CSV file."
},
{
"code": null,
"e": 27233,
"s": 27207,
"text": "Convert it into the list."
},
{
"code": null,
"e": 27249,
"s": 27233,
"text": "Print the list."
},
{
"code": null,
"e": 27278,
"s": 27249,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 27286,
"s": 27278,
"text": "Python3"
},
{
"code": "# importing modulefrom pandas import * # reading CSV filedata = read_csv(\"company_sales_data.csv\") # converting column data to listmonth = data['month_number'].tolist()fc = data['facecream'].tolist()fw = data['facewash'].tolist()tp = data['toothpaste'].tolist()sh = data['shampoo'].tolist() # printing list dataprint('Facecream:', fc)print('Facewash:', fw)print('Toothpaste:', tp)print('Shampoo:', sh)",
"e": 27688,
"s": 27286,
"text": null
},
{
"code": null,
"e": 27696,
"s": 27688,
"text": "Output:"
},
{
"code": null,
"e": 27723,
"s": 27696,
"text": "Method 2: Using csv module"
},
{
"code": null,
"e": 28192,
"s": 27723,
"text": "In this method we will import the csv library and open the file in reading mode, then we will use the DictReader() function to read the data of the CSV file. This function is like a regular reader, but it maps the information to a dictionary whose keys are given by the column names and all the values as keys. We will create empty lists so that we can store the values in it. Finally, we access the key values and append them into the empty lists and print that list."
},
{
"code": null,
"e": 28200,
"s": 28192,
"text": "Python3"
},
{
"code": "# importing the moduleimport csv # open the file in read modefilename = open('company_sales_data.csv', 'r') # creating dictreader objectfile = csv.DictReader(filename) # creating empty listsmonth = []totalprofit = []totalunit = [] # iterating over each row and append# values to empty listfor col in file: month.append(col['month_number']) totalprofit.append(col['moisturizer']) totalunit.append(col['total_units']) # printing listsprint('Month:', month)print('Moisturizer:', totalprofit)print('Total Units:', totalunit)",
"e": 28730,
"s": 28200,
"text": null
},
{
"code": null,
"e": 28738,
"s": 28730,
"text": "Output:"
},
{
"code": null,
"e": 28750,
"s": 28738,
"text": "anikakapoor"
},
{
"code": null,
"e": 28766,
"s": 28750,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 28773,
"s": 28766,
"text": "Picked"
},
{
"code": null,
"e": 28784,
"s": 28773,
"text": "python-csv"
},
{
"code": null,
"e": 28808,
"s": 28784,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28815,
"s": 28808,
"text": "Python"
},
{
"code": null,
"e": 28834,
"s": 28815,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28932,
"s": 28834,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28950,
"s": 28932,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28985,
"s": 28950,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29017,
"s": 28985,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29039,
"s": 29017,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29081,
"s": 29039,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29111,
"s": 29081,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29137,
"s": 29111,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29166,
"s": 29137,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29210,
"s": 29166,
"text": "Reading and Writing to text files in Python"
}
] |
Maximum in array which is at-least twice of other elements - GeeksforGeeks
|
09 Apr, 2021
Given an array of integers of length n. Our task is to return the index of the max element if the it is at least twice as much as every other number in the array. If the max element does not satisfy the condition return -1.Examples:
Input : arr = {3, 6, 1, 0}
Output : 1
Here, 6 is the largest integer, and for
every other number in the array x, 6 is
more than twice as big as x. The index of
value 6 is 1, so we return 1.
Input : arr = {1, 2, 3, 4}
Output : -1
4 isn't at least as big as twice the value
of 3, so we return -1.
Approach : Scan through the array to find the unique largest element m, keeping track of it’s index maxIndex. Scan through the array again. If we find some x != m with m < 2*x, we should return -1. Otherwise, we should return maxIndex.
C++
Java
Python3
C#
PHP
Javascript
// CPP program for Maximum of// the array which is at least// twice of other elements of// the array.#include<bits/stdc++.h>using namespace std; // Function to find the// index of Max element// that satisfies the// conditionint findIndex(int arr[], int len) { // Finding index of // max of the array int maxIndex = 0; for (int i = 0; i < len; ++i) if (arr[i] > arr[maxIndex]) maxIndex = i; // Returns -1 if the // max element is not // twice of the i-th // element. for (int i = 0; i < len; ++i) if (maxIndex != i && arr[maxIndex] < 2 * arr[i]) return -1; return maxIndex;} // Driver functionint main(){ int arr[] = {3, 6, 1, 0}; int len = sizeof(arr) / sizeof(arr[0]); cout<<(findIndex(arr, len));} // This code is contributed by Smitha Dinesh Semwal
// Java program for Maximum of the array// which is at least twice of other elements// of the array.import java.util.*;import java.lang.*; class GfG { // Function to find the index of Max element // that satisfies the condition public static int findIndex(int[] arr) { // Finding index of max of the array int maxIndex = 0; for (int i = 0; i < arr.length; ++i) if (arr[i] > arr[maxIndex]) maxIndex = i; // Returns -1 if the max element is not // twice of the i-th element. for (int i = 0; i < arr.length; ++i) if (maxIndex != i && arr[maxIndex] < 2 * arr[i]) return -1; return maxIndex; } // Driver function public static void main(String argc[]){ int[] arr = new int[]{3, 6, 1, 0}; System.out.println(findIndex(arr)); }}
# Python 3 program for Maximum of# the array which is at least twice # of other elements of the array. # Function to find the index of Max# element that satisfies the conditiondef findIndex(arr): # Finding index of max of the array maxIndex = 0 for i in range(0,len(arr)): if (arr[i] > arr[maxIndex]): maxIndex = i # Returns -1 if the max element is not # twice of the i-th element. for i in range(0,len(arr)): if (maxIndex != i and arr[maxIndex] < (2 * arr[i])): return -1 return maxIndex # Driver codearr = [3, 6, 1, 0]print(findIndex(arr)) # This code is contributed by Smitha Dinesh Semwal
// C# program for Maximum of the array// which is at least twice of other elements// of the array.using System; class GfG { // Function to find the index of Max element // that satisfies the condition public static int findIndex(int[] arr) { // Finding index of max of the array int maxIndex = 0; for (int i = 0; i < arr.Length; ++i) if (arr[i] > arr[maxIndex]) maxIndex = i; // Returns -1 if the max element is not // twice of the i-th element. for (int i = 0; i < arr.Length; ++i) if (maxIndex != i && arr[maxIndex] < 2 * arr[i]) return -1; return maxIndex; } // Driver function public static void Main() { int[] arr = new int[]{3, 6, 1, 0}; Console.WriteLine(findIndex(arr)); }} // This code is contributed by vt_m.
<?php// PHP program for Maximum of// the array which is at least// twice of other elements of// the array. // Function to find the// index of Max element// that satisfies the// conditionfunction findIndex($arr, $len){ // Finding index of // max of the array $maxIndex = 0; for ( $i = 0; $i < $len; ++$i) if ($arr[$i] > $arr[$maxIndex]) $maxIndex = $i; // Returns -1 if the // max element is not // twice of the i-th // element. for ($i = 0; $i < $len; ++$i) if ($maxIndex != $i and $arr[$maxIndex] < 2 * $arr[$i]) return -1; return $maxIndex;} // Driver Code$arr = array(3, 6, 1, 0);$len = count($arr); echo findIndex($arr, $len); // This code is contributed by anuj_67.?>
<script> // Javascript program for Maximum of // the array which is at least // twice of other elements of // the array. // Function to find the // index of Max element // that satisfies the // condition function findIndex(arr, len) { // Finding index of // max of the array let maxIndex = 0; for (let i = 0; i < len; ++i) if (arr[i] > arr[maxIndex]) maxIndex = i; // Returns -1 if the // max element is not // twice of the i-th // element. for (let i = 0; i < len; ++i) if (maxIndex != i && arr[maxIndex] < 2 * arr[i]) return -1; return maxIndex; } let arr = [3, 6, 1, 0]; let len = arr.length; document.write(findIndex(arr, len)); // This code is contributed by divyeshrabadiya07.</script>
Output:
1
Time Complexity:
vt_m
divyeshrabadiya07
Arrays
Searching
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Linked List vs Array
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
Array of Strings in C++ (5 Different Ways to Create)
Binary Search
Search an element in a sorted and rotated array
Find the Missing Number
Program to find largest element in an array
k largest(or smallest) elements in an array
|
[
{
"code": null,
"e": 26155,
"s": 26127,
"text": "\n09 Apr, 2021"
},
{
"code": null,
"e": 26390,
"s": 26155,
"text": "Given an array of integers of length n. Our task is to return the index of the max element if the it is at least twice as much as every other number in the array. If the max element does not satisfy the condition return -1.Examples: "
},
{
"code": null,
"e": 26688,
"s": 26390,
"text": "Input : arr = {3, 6, 1, 0}\nOutput : 1\nHere, 6 is the largest integer, and for \nevery other number in the array x, 6 is \nmore than twice as big as x. The index of\nvalue 6 is 1, so we return 1.\n\nInput : arr = {1, 2, 3, 4}\nOutput : -1\n4 isn't at least as big as twice the value\nof 3, so we return -1."
},
{
"code": null,
"e": 26927,
"s": 26690,
"text": "Approach : Scan through the array to find the unique largest element m, keeping track of it’s index maxIndex. Scan through the array again. If we find some x != m with m < 2*x, we should return -1. Otherwise, we should return maxIndex. "
},
{
"code": null,
"e": 26931,
"s": 26927,
"text": "C++"
},
{
"code": null,
"e": 26936,
"s": 26931,
"text": "Java"
},
{
"code": null,
"e": 26944,
"s": 26936,
"text": "Python3"
},
{
"code": null,
"e": 26947,
"s": 26944,
"text": "C#"
},
{
"code": null,
"e": 26951,
"s": 26947,
"text": "PHP"
},
{
"code": null,
"e": 26962,
"s": 26951,
"text": "Javascript"
},
{
"code": "// CPP program for Maximum of// the array which is at least// twice of other elements of// the array.#include<bits/stdc++.h>using namespace std; // Function to find the// index of Max element// that satisfies the// conditionint findIndex(int arr[], int len) { // Finding index of // max of the array int maxIndex = 0; for (int i = 0; i < len; ++i) if (arr[i] > arr[maxIndex]) maxIndex = i; // Returns -1 if the // max element is not // twice of the i-th // element. for (int i = 0; i < len; ++i) if (maxIndex != i && arr[maxIndex] < 2 * arr[i]) return -1; return maxIndex;} // Driver functionint main(){ int arr[] = {3, 6, 1, 0}; int len = sizeof(arr) / sizeof(arr[0]); cout<<(findIndex(arr, len));} // This code is contributed by Smitha Dinesh Semwal",
"e": 27840,
"s": 26962,
"text": null
},
{
"code": "// Java program for Maximum of the array// which is at least twice of other elements// of the array.import java.util.*;import java.lang.*; class GfG { // Function to find the index of Max element // that satisfies the condition public static int findIndex(int[] arr) { // Finding index of max of the array int maxIndex = 0; for (int i = 0; i < arr.length; ++i) if (arr[i] > arr[maxIndex]) maxIndex = i; // Returns -1 if the max element is not // twice of the i-th element. for (int i = 0; i < arr.length; ++i) if (maxIndex != i && arr[maxIndex] < 2 * arr[i]) return -1; return maxIndex; } // Driver function public static void main(String argc[]){ int[] arr = new int[]{3, 6, 1, 0}; System.out.println(findIndex(arr)); }}",
"e": 28761,
"s": 27840,
"text": null
},
{
"code": "# Python 3 program for Maximum of# the array which is at least twice # of other elements of the array. # Function to find the index of Max# element that satisfies the conditiondef findIndex(arr): # Finding index of max of the array maxIndex = 0 for i in range(0,len(arr)): if (arr[i] > arr[maxIndex]): maxIndex = i # Returns -1 if the max element is not # twice of the i-th element. for i in range(0,len(arr)): if (maxIndex != i and arr[maxIndex] < (2 * arr[i])): return -1 return maxIndex # Driver codearr = [3, 6, 1, 0]print(findIndex(arr)) # This code is contributed by Smitha Dinesh Semwal",
"e": 29467,
"s": 28761,
"text": null
},
{
"code": "// C# program for Maximum of the array// which is at least twice of other elements// of the array.using System; class GfG { // Function to find the index of Max element // that satisfies the condition public static int findIndex(int[] arr) { // Finding index of max of the array int maxIndex = 0; for (int i = 0; i < arr.Length; ++i) if (arr[i] > arr[maxIndex]) maxIndex = i; // Returns -1 if the max element is not // twice of the i-th element. for (int i = 0; i < arr.Length; ++i) if (maxIndex != i && arr[maxIndex] < 2 * arr[i]) return -1; return maxIndex; } // Driver function public static void Main() { int[] arr = new int[]{3, 6, 1, 0}; Console.WriteLine(findIndex(arr)); }} // This code is contributed by vt_m.",
"e": 30374,
"s": 29467,
"text": null
},
{
"code": "<?php// PHP program for Maximum of// the array which is at least// twice of other elements of// the array. // Function to find the// index of Max element// that satisfies the// conditionfunction findIndex($arr, $len){ // Finding index of // max of the array $maxIndex = 0; for ( $i = 0; $i < $len; ++$i) if ($arr[$i] > $arr[$maxIndex]) $maxIndex = $i; // Returns -1 if the // max element is not // twice of the i-th // element. for ($i = 0; $i < $len; ++$i) if ($maxIndex != $i and $arr[$maxIndex] < 2 * $arr[$i]) return -1; return $maxIndex;} // Driver Code$arr = array(3, 6, 1, 0);$len = count($arr); echo findIndex($arr, $len); // This code is contributed by anuj_67.?>",
"e": 31155,
"s": 30374,
"text": null
},
{
"code": "<script> // Javascript program for Maximum of // the array which is at least // twice of other elements of // the array. // Function to find the // index of Max element // that satisfies the // condition function findIndex(arr, len) { // Finding index of // max of the array let maxIndex = 0; for (let i = 0; i < len; ++i) if (arr[i] > arr[maxIndex]) maxIndex = i; // Returns -1 if the // max element is not // twice of the i-th // element. for (let i = 0; i < len; ++i) if (maxIndex != i && arr[maxIndex] < 2 * arr[i]) return -1; return maxIndex; } let arr = [3, 6, 1, 0]; let len = arr.length; document.write(findIndex(arr, len)); // This code is contributed by divyeshrabadiya07.</script>",
"e": 32063,
"s": 31155,
"text": null
},
{
"code": null,
"e": 32073,
"s": 32063,
"text": "Output: "
},
{
"code": null,
"e": 32075,
"s": 32073,
"text": "1"
},
{
"code": null,
"e": 32094,
"s": 32075,
"text": "Time Complexity: "
},
{
"code": null,
"e": 32099,
"s": 32094,
"text": "vt_m"
},
{
"code": null,
"e": 32117,
"s": 32099,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 32124,
"s": 32117,
"text": "Arrays"
},
{
"code": null,
"e": 32134,
"s": 32124,
"text": "Searching"
},
{
"code": null,
"e": 32141,
"s": 32134,
"text": "Arrays"
},
{
"code": null,
"e": 32151,
"s": 32141,
"text": "Searching"
},
{
"code": null,
"e": 32249,
"s": 32151,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32272,
"s": 32249,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 32293,
"s": 32272,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 32338,
"s": 32293,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 32386,
"s": 32338,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 32439,
"s": 32386,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 32453,
"s": 32439,
"text": "Binary Search"
},
{
"code": null,
"e": 32501,
"s": 32453,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 32525,
"s": 32501,
"text": "Find the Missing Number"
},
{
"code": null,
"e": 32569,
"s": 32525,
"text": "Program to find largest element in an array"
}
] |
Python | Sort list of list by specified index - GeeksforGeeks
|
23 Dec, 2018
We can sort list of list using the conventional sort function. This sorts the list by the first index of lists. But more than often there can be circumstances that requires the sorting of list of list by other index elements than first. Lets discuss certain ways in which this task can be performed.
Method #1 : Using sort() + lambdasort() can be used to perform this variation of sort by passing a function as a key that performs the sorting according to the desired inner list index.
# Python 3 code to demonstrate # to sort list of list by given index # using sort() + lambda # initializing list test_list = [['Rash', 4, 28], ['Varsha', 2, 20], ['Nikhil', 1, 20], ['Akshat', 3, 21]] # printing original list print ("The original list is : " + str(test_list)) # using sort() + lambda# to sort list of list # sort by second indextest_list.sort(key = lambda test_list: test_list[1]) # printing resultprint ("List after sorting by 2nd element of lists : " + str(test_list))
Output :
The original list is : [['Rash', 4, 28], ['Varsha', 2, 20], ['Nikhil', 1, 20], ['Akshat', 3, 21]]
List after sorting by 2nd element of lists : [['Nikhil', 1, 20], ['Varsha', 2, 20], ['Akshat', 3, 21], ['Rash', 4, 28]]
Method #2 : Using sorted() + itemgetter()This can also be applied to perform this particular task. The advantage that it holds is that it does not modify the original list. itemgetter() is used to get the index element by which the sort operation needs to be performed.
# Python3 code to demonstrate # to sort list of list by given index # using sorted() + itemgetter()from operator import itemgetter # initializing list test_list = [['Rash', 4, 28], ['Varsha', 2, 20], ['Nikhil', 1, 20], ['Akshat', 3, 21]] # printing original list print ("The original list is : " + str(test_list)) # using sort() + lambda# to sort list of list # sort by second indexres = sorted(test_list, key = itemgetter(1)) # printing resultprint ("List after sorting by 2nd element of lists : " + str(res))
Output :
The original list is : [['Rash', 4, 28], ['Varsha', 2, 20], ['Nikhil', 1, 20], ['Akshat', 3, 21]]
List after sorting by 2nd element of lists : [['Nikhil', 1, 20], ['Varsha', 2, 20], ['Akshat', 3, 21], ['Rash', 4, 28]]
Python list-programs
python-list
Python
Sorting
python-list
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
|
[
{
"code": null,
"e": 25493,
"s": 25465,
"text": "\n23 Dec, 2018"
},
{
"code": null,
"e": 25793,
"s": 25493,
"text": "We can sort list of list using the conventional sort function. This sorts the list by the first index of lists. But more than often there can be circumstances that requires the sorting of list of list by other index elements than first. Lets discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 25979,
"s": 25793,
"text": "Method #1 : Using sort() + lambdasort() can be used to perform this variation of sort by passing a function as a key that performs the sorting according to the desired inner list index."
},
{
"code": "# Python 3 code to demonstrate # to sort list of list by given index # using sort() + lambda # initializing list test_list = [['Rash', 4, 28], ['Varsha', 2, 20], ['Nikhil', 1, 20], ['Akshat', 3, 21]] # printing original list print (\"The original list is : \" + str(test_list)) # using sort() + lambda# to sort list of list # sort by second indextest_list.sort(key = lambda test_list: test_list[1]) # printing resultprint (\"List after sorting by 2nd element of lists : \" + str(test_list))",
"e": 26472,
"s": 25979,
"text": null
},
{
"code": null,
"e": 26481,
"s": 26472,
"text": "Output :"
},
{
"code": null,
"e": 26700,
"s": 26481,
"text": "The original list is : [['Rash', 4, 28], ['Varsha', 2, 20], ['Nikhil', 1, 20], ['Akshat', 3, 21]]\nList after sorting by 2nd element of lists : [['Nikhil', 1, 20], ['Varsha', 2, 20], ['Akshat', 3, 21], ['Rash', 4, 28]]\n"
},
{
"code": null,
"e": 26970,
"s": 26700,
"text": "Method #2 : Using sorted() + itemgetter()This can also be applied to perform this particular task. The advantage that it holds is that it does not modify the original list. itemgetter() is used to get the index element by which the sort operation needs to be performed."
},
{
"code": "# Python3 code to demonstrate # to sort list of list by given index # using sorted() + itemgetter()from operator import itemgetter # initializing list test_list = [['Rash', 4, 28], ['Varsha', 2, 20], ['Nikhil', 1, 20], ['Akshat', 3, 21]] # printing original list print (\"The original list is : \" + str(test_list)) # using sort() + lambda# to sort list of list # sort by second indexres = sorted(test_list, key = itemgetter(1)) # printing resultprint (\"List after sorting by 2nd element of lists : \" + str(res))",
"e": 27485,
"s": 26970,
"text": null
},
{
"code": null,
"e": 27494,
"s": 27485,
"text": "Output :"
},
{
"code": null,
"e": 27713,
"s": 27494,
"text": "The original list is : [['Rash', 4, 28], ['Varsha', 2, 20], ['Nikhil', 1, 20], ['Akshat', 3, 21]]\nList after sorting by 2nd element of lists : [['Nikhil', 1, 20], ['Varsha', 2, 20], ['Akshat', 3, 21], ['Rash', 4, 28]]\n"
},
{
"code": null,
"e": 27734,
"s": 27713,
"text": "Python list-programs"
},
{
"code": null,
"e": 27746,
"s": 27734,
"text": "python-list"
},
{
"code": null,
"e": 27753,
"s": 27746,
"text": "Python"
},
{
"code": null,
"e": 27761,
"s": 27753,
"text": "Sorting"
},
{
"code": null,
"e": 27773,
"s": 27761,
"text": "python-list"
},
{
"code": null,
"e": 27781,
"s": 27773,
"text": "Sorting"
},
{
"code": null,
"e": 27879,
"s": 27781,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27914,
"s": 27879,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27946,
"s": 27914,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27968,
"s": 27946,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28010,
"s": 27968,
"text": "Different ways to create Pandas Dataframe"
}
] |
Tailwind CSS Font Size - GeeksforGeeks
|
23 Mar, 2022
This class accepts lots of value in tailwind CSS in which all the properties are covered as in class form. It is the alternative to the CSS font-size property. This class is used to set the font size of the text in an HTML document.
Font size classes:
text-xs: This class defines the text size as extra small.
text-sm: This class defines the text size as small.
text-base: This class defines the text size as base size.
text-lg: This class defines the text size as large.
text-xl: This class defines the text size as extra-large.
text-2xl: This class defines the text size as 2 times extra-large.
text-3xl: This class defines the text size as 3 times extra-large.
text-4xl: This class defines the text size as 4 times extra-large.
text-5xl: This class defines the text size as 5 times extra-large.
text-6xl: This class defines the text size as 6 times extra-large.
text-7xl: This class defines the text size as 7 times extra-large.
text-8xl: This class defines the text size as 8 times extra-large.
text-9xl: This class defines the text size as 9 times extra-large.
Note: Change the size in the component with the required size mentioned above.
Syntax:
<element class="text-size">...</element>
Example:
HTML
<!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center mx-4 space-y-2"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Font Size Class</b> <div class="mx-24 bg-green-200"> <p class="text-xs"> Geeksforgeeks: A Computer Science portal for Geeks </p> <p class="text-sm"> Geeksforgeeks: A Computer Science portal for Geeks </p> <p class="text-base"> Geeksforgeeks: A Computer Science portal for Geeks </p> <p class="text-lg"> Geeksforgeeks: A Computer Science portal for Geeks </p> <p class="text-xl"> Geeksforgeeks: A Computer Science portal for Geeks </p> </div></body> </html>
Output:
Tailwind CSS
Tailwind-Typography
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 37385,
"s": 37357,
"text": "\n23 Mar, 2022"
},
{
"code": null,
"e": 37619,
"s": 37385,
"text": "This class accepts lots of value in tailwind CSS in which all the properties are covered as in class form. It is the alternative to the CSS font-size property. This class is used to set the font size of the text in an HTML document."
},
{
"code": null,
"e": 37638,
"s": 37619,
"text": "Font size classes:"
},
{
"code": null,
"e": 37696,
"s": 37638,
"text": "text-xs: This class defines the text size as extra small."
},
{
"code": null,
"e": 37748,
"s": 37696,
"text": "text-sm: This class defines the text size as small."
},
{
"code": null,
"e": 37806,
"s": 37748,
"text": "text-base: This class defines the text size as base size."
},
{
"code": null,
"e": 37858,
"s": 37806,
"text": "text-lg: This class defines the text size as large."
},
{
"code": null,
"e": 37916,
"s": 37858,
"text": "text-xl: This class defines the text size as extra-large."
},
{
"code": null,
"e": 37983,
"s": 37916,
"text": "text-2xl: This class defines the text size as 2 times extra-large."
},
{
"code": null,
"e": 38050,
"s": 37983,
"text": "text-3xl: This class defines the text size as 3 times extra-large."
},
{
"code": null,
"e": 38117,
"s": 38050,
"text": "text-4xl: This class defines the text size as 4 times extra-large."
},
{
"code": null,
"e": 38184,
"s": 38117,
"text": "text-5xl: This class defines the text size as 5 times extra-large."
},
{
"code": null,
"e": 38251,
"s": 38184,
"text": "text-6xl: This class defines the text size as 6 times extra-large."
},
{
"code": null,
"e": 38318,
"s": 38251,
"text": "text-7xl: This class defines the text size as 7 times extra-large."
},
{
"code": null,
"e": 38385,
"s": 38318,
"text": "text-8xl: This class defines the text size as 8 times extra-large."
},
{
"code": null,
"e": 38452,
"s": 38385,
"text": "text-9xl: This class defines the text size as 9 times extra-large."
},
{
"code": null,
"e": 38531,
"s": 38452,
"text": "Note: Change the size in the component with the required size mentioned above."
},
{
"code": null,
"e": 38539,
"s": 38531,
"text": "Syntax:"
},
{
"code": null,
"e": 38580,
"s": 38539,
"text": "<element class=\"text-size\">...</element>"
},
{
"code": null,
"e": 38589,
"s": 38580,
"text": "Example:"
},
{
"code": null,
"e": 38594,
"s": 38589,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center mx-4 space-y-2\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Font Size Class</b> <div class=\"mx-24 bg-green-200\"> <p class=\"text-xs\"> Geeksforgeeks: A Computer Science portal for Geeks </p> <p class=\"text-sm\"> Geeksforgeeks: A Computer Science portal for Geeks </p> <p class=\"text-base\"> Geeksforgeeks: A Computer Science portal for Geeks </p> <p class=\"text-lg\"> Geeksforgeeks: A Computer Science portal for Geeks </p> <p class=\"text-xl\"> Geeksforgeeks: A Computer Science portal for Geeks </p> </div></body> </html> ",
"e": 39474,
"s": 38594,
"text": null
},
{
"code": null,
"e": 39482,
"s": 39474,
"text": "Output:"
},
{
"code": null,
"e": 39495,
"s": 39482,
"text": "Tailwind CSS"
},
{
"code": null,
"e": 39515,
"s": 39495,
"text": "Tailwind-Typography"
},
{
"code": null,
"e": 39519,
"s": 39515,
"text": "CSS"
},
{
"code": null,
"e": 39536,
"s": 39519,
"text": "Web Technologies"
},
{
"code": null,
"e": 39634,
"s": 39536,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39696,
"s": 39634,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 39746,
"s": 39696,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 39794,
"s": 39746,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 39852,
"s": 39794,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 39907,
"s": 39852,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 39947,
"s": 39907,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 39980,
"s": 39947,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 40025,
"s": 39980,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 40068,
"s": 40025,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Queries to find Kth greatest character in a range [L, R] from a string with updates - GeeksforGeeks
|
22 Nov, 2021
Given a string str of length N, and Q queries of the following two types:
(1 L R K): Find the Kth greatest character (non-distinct) from the range of indices [L, R] (1-based indexing)(2 J C): Replace the Jth character from the string by character C.
(1 L R K): Find the Kth greatest character (non-distinct) from the range of indices [L, R] (1-based indexing)
(2 J C): Replace the Jth character from the string by character C.
Examples:
Input: str = “abcddef”, Q = 3, queries[][] = {{1, 2, 5, 3}, {2, 4, g}, {1, 1, 4, 3}}Output:cb Explanation : Query 1: String between indices (2, 5) is “bcdd”. The third largest character is ‘c’. Therefore, c is the required output. Query 2: Replace S[4] by ‘g’. Therefore, S modifies to “abcgdef”. Query 3: String between indices (1, 4) is “abcg”. The third largest character is ‘b’. Therefore, b is the required output.
Input: str=” afcdehgk”, Q = 4, queries[][] = {{1, 2, 5, 4}, {2, 5, m}, {1, 3, 7, 2}, {1, 1, 6, 4}}Output:chd
Naive Approach: The simplest approach to solve the problem is as follows:
For each query of type ( 1 L R K ), find the substring of S from the range of indices [L, R], and sort this substring in non-increasing order. Print the character at the Kth index in the substring.
For each query of type ( 2 J C ), replace the Jth character in S by C.
Time Complexity: O ( Q * ( N log(N) ) ), where N logN is the computational complexity of sorting each substring.Auxiliary Space: O(N)
The below code 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 find the kth greatest// character from the strijngchar find_kth_largest(string str, int k){ // Sorting the string in // non-increasing Order sort(str.begin(), str.end(), greater<char>()); return str[k - 1];} // Function to print the K-th character// from the substring S[l] .. S[r]char printCharacter(string str, int l, int r, int k){ // 0-based indexing l = l - 1; r = r - 1; // Substring of str from the // indices l to r. string temp = str.substr(l, r - l + 1); // Extract kth Largest character char ans = find_kth_largest(temp, k); return ans;} // Function to replace character at// pos of str by the character svoid updateString(string str, int pos, char s){ // Index of S to be updated. int index = pos - 1; char c = s; // Character to be replaced // at index in S str[index] = c;} // Driver Codeint main(){ // Given string string str = "abcddef"; // Count of queries int Q = 3; // Queries cout << printCharacter(str, 1, 2, 2) << endl; updateString(str, 4, 'g'); cout << printCharacter(str, 1, 5, 4) << endl; return 0;}
// Java Program to implement// the above approach//include "bits/stdJava.h"import java.util.*;class GFG{ // Function to find the kth greatest// character from the strijngstatic char find_kth_largest(char []str, int k){ // Sorting the String in // non-increasing Order Arrays.sort(str); reverse(str); return str[k - 1];} static char[] reverse(char a[]) { int i, n = a.length; char t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a;} // Function to print the K-th character// from the subString S[l] .. S[r]static char printCharacter(String str, int l, int r, int k){ // 0-based indexing l = l - 1; r = r - 1; // SubString of str from the // indices l to r. String temp = str.substring(l, r - l + 1); // Extract kth Largest character char ans = find_kth_largest(temp.toCharArray(), k); return ans;} // Function to replace character at// pos of str by the character sstatic void updateString(char []str, int pos, char s){ // Index of S to be updated. int index = pos - 1; char c = s; // Character to be replaced // at index in S str[index] = c;} // Driver Codepublic static void main(String[] args){ // Given String String str = "abcddef"; // Count of queries int Q = 3; // Queries System.out.print(printCharacter(str, 1, 2, 2) + "\n"); updateString(str.toCharArray(), 4, 'g'); System.out.print(printCharacter(str, 1, 5, 4) + "\n");}} // This code is contributed by shikhasingrajput
# Python3 Program to implement# the above approach# Function to find the kth greatest# character from the stringdef find_kth_largest(strr, k): # Sorting the in # non-increasing Order strr = sorted(strr) strr = strr[:: -1] return strr[k - 1] # Function to print the K-th character# from the subS[l] .. S[r]def printCharacter(strr, l, r, k): #0-based indexing l = l - 1 r = r - 1 # Subof strr from the # indices l to r. temp= strr[l: r - l + 1] #Extract kth Largest character ans = find_kth_largest(temp, k) return ans # Function to replace character at# pos of strr by the character sdef updateString(strr, pos, s): # Index of S to be updated. index = pos - 1 c = s # Character to be replaced # at index in S strr[index] = c # Driver Codeif __name__ == '__main__': # Given string strr = "abcddef" strr=[i for i in strr] # Count of queries Q = 3 # Queries print(printCharacter(strr, 1, 2, 2)) updateString(strr, 4, 'g') print(printCharacter(strr, 1, 5, 4)) # This code is contributed by Mohit Kumar 29
// C# program to implement// the above approachusing System; class GFG{ // Function to find the kth greatest// character from the stringstatic char find_kth_largest(char []str, int k){ // Sorting the String in // non-increasing Order Array.Sort(str); reverse(str); return str[k - 1];} static char[] reverse(char []a){ int i, n = a.Length; char t; for(i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a;} // Function to print the K-th character// from the subString S[l] .. S[r]static char printchar(String str, int l, int r, int k){ // 0-based indexing l = l - 1; r = r - 1; // SubString of str from the // indices l to r. String temp = str.Substring(l, r - l + 1); // Extract kth Largest character char ans = find_kth_largest( temp.ToCharArray(), k); return ans;} // Function to replace character at// pos of str by the character sstatic void updateString(char []str, int pos, char s){ // Index of S to be updated. int index = pos - 1; char c = s; // char to be replaced // at index in S str[index] = c;} // Driver Codepublic static void Main(String[] args){ // Given String String str = "abcddef"; // Count of queries //int Q = 3; // Queries Console.Write(printchar(str, 1, 2, 2) + "\n"); updateString(str.ToCharArray(), 4, 'g'); Console.Write(printchar(str, 1, 5, 4) + "\n");}} // This code is contributed by Amit Katiyar
<script>// Javascript Program to implement// the above approach//include "bits/stdJava.h" // Function to find the kth greatest// character from the strijngfunction find_kth_largest(str,k){ // Sorting the String in // non-increasing Order str.sort(); reverse(str); return str[k - 1];} function reverse(a){ let i, n = a.length; let t; for (i = 0; i < Math.floor(n / 2); i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a;} // Function to print the K-th character// from the subString S[l] .. S[r]function printCharacter(str,l,r,k){ // 0-based indexing l = l - 1; r = r - 1; // SubString of str from the // indices l to r. let temp = str.substring(l, r - l + 1); // Extract kth Largest character let ans = find_kth_largest(temp.split(""), k); return ans;} // Function to replace character at// pos of str by the character sfunction updateString(str,pos,s){ // Index of S to be updated. let index = pos - 1; let c = s; // Character to be replaced // at index in S str[index] = c;} // Driver Code// Given Stringlet str = "abcddef";// Count of querieslet Q = 3; // Queriesdocument.write(printCharacter(str, 1, 2, 2) + "<br>");updateString(str.split(""), 4, 'g');document.write(printCharacter(str, 1, 5, 4) + "<br>"); // This code is contributed by avanitrachhadiya2155</script>
a
b
Efficient Approach: The above approach can be optimized by precomputing the count of all the characters which are greater than or equal to character C ( ‘a’ ≤ C ≤ ‘z’ ) efficiently using a Fenwick Tree.Follow the steps below to solve the problem:
Create a Fenwick Tree to store the frequencies of all characters from ‘a’ to ‘z‘
For every query of type 1, check for each character from ‘z’ to ‘a’, whether it is the Kth the greatest character.
In order to perform this, traverse from ‘z’ to ‘a’ and for each character, check if the count of all the characters traversed becomes ≥ K or not. Print the character for which the count becomes ≥ K.
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; // Maximum Size of a Stringconst int maxn = 100005; // Fenwick Tree to store the// frequencies of 26 alphabetsint BITree[26][maxn]; // Size of the String.int N; // Function to update Fenwick Tree for// Character c at index valvoid update_BITree(int index, char C, int val){ while (index <= N) { // Add val to current node // Fenwick Tree BITree[C - 'a'][index] += val; // Move index to parent node // in update View index += (index & -index); }} // Function to get sum of frequencies// of character c till indexint sum_BITree(int index, char C){ // Stores the sum int s = 0; while (index) { // Add current element of // Fenwick tree to sum s += BITree[C - 'a'][index]; // Move index to parent node // in getSum View index -= (index & -index); } return s;} // Function to create the Fenwick treevoid buildTree(string str){ for (int i = 1; i <= N; i++) { update_BITree(i, str[i], 1); } cout << endl;} // Function to print the kth largest// character in the range of l to rchar printCharacter(string str, int l, int r, int k){ // Stores the count of // characters int count = 0; // Stores the required // character char ans; for (char C = 'z'; C >= 'a'; C--) { // Calculate frequency of // C in the given range int times = sum_BITree(r, C) - sum_BITree(l - 1, C); // Increase count count += times; // If count exceeds K if (count >= k) { // Required character // found ans = C; break; } } return ans;} // Function to update character// at pos by character svoid updateTree(string str, int pos, char s){ // 0 based index system int index = pos; update_BITree(index, str[index], -1); str[index] = s; update_BITree(index, s, 1);} // Driver Codeint main(){ string str = "abcddef"; N = str.size(); // Makes the string 1-based indexed str = '#' + str; // Number of queries int Q = 3; // Construct the Fenwick Tree buildTree(str); cout << printCharacter(str, 1, 2, 2) << endl; updateTree(str, 4, 'g'); cout << printCharacter(str, 1, 5, 4) << endl; return 0;}
// Java Program to implement// the above approach //include "bits/stdJava.h"import java.util.*;class GFG{ // Maximum Size of a Stringstatic int maxn = 100005; // Fenwick Tree to store the// frequencies of 26 alphabetsstatic int [][]BITree = new int[26][maxn]; // Size of the String.static int N; // Function to update Fenwick Tree for// Character c at index valstatic void update_BITree(int index, char C, int val){ while (index <= N) { // Add val to current node // Fenwick Tree BITree[C - 'a'][index] += val; // Move index to parent node // in update View index += (index & -index); }} // Function to get sum of frequencies// of character c till indexstatic int sum_BITree(int index, char C){ // Stores the sum int s = 0; while (index > 0) { // Add current element of // Fenwick tree to sum s += BITree[C - 'a'][index]; // Move index to parent node // in getSum View index -= (index & -index); } return s;} // Function to create the Fenwick treestatic void buildTree(String str){ for (int i = 1; i <= N; i++) { update_BITree(i, str.charAt(i), 1); } System.out.println();} // Function to print the kth largest// character in the range of l to rstatic char printCharacter(String str, int l, int r, int k){ // Stores the count of // characters int count = 0; // Stores the required // character char ans = 0; for (char C = 'z'; C >= 'a'; C--) { // Calculate frequency of // C in the given range int times = sum_BITree(r, C) - sum_BITree(l - 1, C); // Increase count count += times; // If count exceeds K if (count >= k) { // Required character // found ans = C; break; } } return ans;} // Function to update character// at pos by character sstatic void updateTree(String str, int pos, char s){ // 0 based index system int index = pos; update_BITree(index, str.charAt(index), -1); str = str.substring(0, index) + s + str.substring(index + 1); update_BITree(index, s, 1);} // Driver Codepublic static void main(String[] args){ String str = "abcddef"; N = str.length(); // Makes the String 1-based indexed str = '/' + str; // Number of queries int Q = 3; // Construct the Fenwick Tree buildTree(str); System.out.print(printCharacter(str, 1, 2, 2) + "\n"); updateTree(str, 4, 'g'); System.out.print(printCharacter(str, 1, 5, 4) + "\n"); }} // This code is contributed by shikhasingrajput
# Python3 Program to implement# the above approach # Maximum Size of a Stringmaxn = 100005 # Fenwick Tree to store the# frequencies of 26 alphabetsBITree = [[0 for x in range(maxn)] for y in range(26)] # Size of the String.N = 0 # Function to update Fenwick Tree for# Character c at index valdef update_BITree(index, C, val): while (index <= N): # Add val to current node # Fenwick Tree BITree[ord(C) - ord('a')][index]+= val # Move index to parent node # in update View index += (index & -index) # Function to get sum of# frequencies of character# c till indexdef sum_BITree(index, C): # Stores the sum s = 0 while (index): # Add current element of # Fenwick tree to sum s += BITree[ord(C) - ord('a')][index] # Move index to parent node # in getSum View index -= (index & -index) return s # Function to create# the Fenwick treedef buildTree(st): for i in range(1, N + 1): update_BITree(i, st[i], 1) print() # Function to print the# kth largest character# in the range of l to rdef printCharacter(st, l, r, k): # Stores the count of # characters count = 0 for C in range(ord('z'), ord('a') - 1, -1): # Calculate frequency of # C in the given range times = (sum_BITree(r, chr(C)) - sum_BITree(l - 1, chr(C))) # Increase count count += times # If count exceeds K if (count >= k): # Required character # found ans = chr( C) break return ans # Function to update character# at pos by character sdef updateTree(st, pos, s): # 0 based index system index = pos; update_BITree(index, st[index], -1) st.replace(st[index], s, 1) update_BITree(index, s, 1) # Driver Codeif __name__ == "__main__": st = "abcddef" N = len(st) # Makes the string # 1-based indexed st = '#' + st # Number of queries Q = 3 # Construct the Fenwick Tree buildTree(st) print (printCharacter(st, 1, 2, 2)) updateTree(st, 4, 'g') print (printCharacter(st, 1, 5, 4)) # This code is contributed by Chitranayal
// C# Program to implement// the above approachusing System;class GFG{ // Maximum Size of a Stringstatic int maxn = 100005; // Fenwick Tree to store the// frequencies of 26 alphabetsstatic int [,]BITree = new int[26, maxn]; // Size of the String.static int N; // Function to update Fenwick Tree for// char c at index valstatic void update_BITree(int index, char C, int val){ while (index <= N) { // Add val to current node // Fenwick Tree BITree[C - 'a', index] += val; // Move index to parent node // in update View index += (index & -index); }} // Function to get sum of frequencies// of character c till indexstatic int sum_BITree(int index, char C){ // Stores the sum int s = 0; while (index > 0) { // Add current element of // Fenwick tree to sum s += BITree[C - 'a', index]; // Move index to parent node // in getSum View index -= (index & -index); } return s;} // Function to create the Fenwick treestatic void buildTree(String str){ for (int i = 1; i <= N; i++) { update_BITree(i, str[i], 1); } Console.WriteLine();} // Function to print the kth largest// character in the range of l to rstatic char printchar(String str, int l, int r, int k){ // Stores the count of // characters int count = 0; // Stores the required // character char ans = (char)0; for (char C = 'z'; C >= 'a'; C--) { // Calculate frequency of // C in the given range int times = sum_BITree(r, C) - sum_BITree(l - 1, C); // Increase count count += times; // If count exceeds K if (count >= k) { // Required character // found ans = C; break; } } return ans;} // Function to update character// at pos by character sstatic void updateTree(String str, int pos, char s){ // 0 based index system int index = pos; update_BITree(index, str[index], -1); str = str.Substring(0, index) + s + str.Substring(index + 1); update_BITree(index, s, 1);} // Driver Codepublic static void Main(String[] args){ String str = "abcddef"; N = str.Length; // Makes the String 1-based indexed str = '/' + str; // Number of queries int Q = 3; // Construct the Fenwick Tree buildTree(str); Console.Write(printchar(str, 1, 2, 2) + "\n"); updateTree(str, 4, 'g'); Console.Write(printchar(str, 1, 5, 4) + "\n");}} // This code is contributed by Rajput-Ji
<script>// Javascript Program to implement// the above approach // Maximum Size of a Stringlet maxn = 100005; // Fenwick Tree to store the// frequencies of 26 alphabetslet BITree = new Array(26);for(let i=0;i<26;i++){ BITree[i]=new Array(maxn); for(let j=0;j<maxn;j++) { BITree[i][j]=0; } } // Size of the String.let N; // Function to update Fenwick Tree for// Character c at index valfunction update_BITree(index,C,val){ while (index <= N) { // Add val to current node // Fenwick Tree BITree[C.charCodeAt(0) - 'a'.charCodeAt(0)][index] += val; // Move index to parent node // in update View index += (index & -index); }} // Function to get sum of frequencies// of character c till indexfunction sum_BITree(index,C){ // Stores the sum let s = 0; while (index > 0) { // Add current element of // Fenwick tree to sum s += BITree[C.charCodeAt(0) - 'a'.charCodeAt(0)][index]; // Move index to parent node // in getSum View index -= (index & -index); } return s;} // Function to create the Fenwick treefunction buildTree(str){ for (let i = 1; i <= N; i++) { update_BITree(i, str[i], 1); } document.write("<br>");} // Function to print the kth largest// character in the range of l to rfunction printCharacter(str,l,r,k){ // Stores the count of // characters let count = 0; // Stores the required // character let ans = 0; for (let C = 'z'.charCodeAt(0); C >= 'a'.charCodeAt(0); C--) { // Calculate frequency of // C in the given range let times = sum_BITree(r, String.fromCharCode(C)) - sum_BITree(l - 1, String.fromCharCode(C)); // Increase count count += times; // If count exceeds K if (count >= k) { // Required character // found ans = String.fromCharCode(C); break; } } return ans;} // Function to update character// at pos by character sfunction updateTree(str,pos,s){ // 0 based index system let index = pos; update_BITree(index, str[index], -1); str = str.substring(0, index) + s + str.substring(index + 1); update_BITree(index, s, 1);} // Driver Codelet str = "abcddef";N = str.length; // Makes the String 1-based indexedstr = '/' + str; // Number of querieslet Q = 3; // Construct the Fenwick TreebuildTree(str); document.write(printCharacter(str, 1, 2, 2) + "<br>");updateTree(str, 4, 'g');document.write(printCharacter(str, 1, 5, 4) + "<br>"); // This code is contributed by rag2127</script>
a
b
Time Complexity: O( QlogN + NlogN ) Auxiliary Space: O(26 * maxn), where maxn denotes the maximum possible length of the string.
mohit kumar 29
shikhasingrajput
amit143katiyar
Rajput-Ji
ukasp
sumitgumber28
akshaysingh98088
avanitrachhadiya2155
rag2127
sagartomar9927
ankita_saini
array-range-queries
BIT
frequency-counting
Advanced Data Structure
Arrays
Mathematical
Searching
Sorting
Strings
Arrays
Searching
Strings
Mathematical
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Tree Introduction with example
Ordered Set and GNU C++ PBDS
Red-Black Tree | Set 2 (Insert)
Disjoint Set Data Structures
Binary Indexed Tree or Fenwick Tree
Arrays in Java
Arrays in C/C++
Maximum and minimum of an array using minimum number of comparisons
Write a program to reverse an array or string
Program for array rotation
|
[
{
"code": null,
"e": 26819,
"s": 26791,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 26893,
"s": 26819,
"text": "Given a string str of length N, and Q queries of the following two types:"
},
{
"code": null,
"e": 27069,
"s": 26893,
"text": "(1 L R K): Find the Kth greatest character (non-distinct) from the range of indices [L, R] (1-based indexing)(2 J C): Replace the Jth character from the string by character C."
},
{
"code": null,
"e": 27179,
"s": 27069,
"text": "(1 L R K): Find the Kth greatest character (non-distinct) from the range of indices [L, R] (1-based indexing)"
},
{
"code": null,
"e": 27246,
"s": 27179,
"text": "(2 J C): Replace the Jth character from the string by character C."
},
{
"code": null,
"e": 27256,
"s": 27246,
"text": "Examples:"
},
{
"code": null,
"e": 27676,
"s": 27256,
"text": "Input: str = “abcddef”, Q = 3, queries[][] = {{1, 2, 5, 3}, {2, 4, g}, {1, 1, 4, 3}}Output:cb Explanation : Query 1: String between indices (2, 5) is “bcdd”. The third largest character is ‘c’. Therefore, c is the required output. Query 2: Replace S[4] by ‘g’. Therefore, S modifies to “abcgdef”. Query 3: String between indices (1, 4) is “abcg”. The third largest character is ‘b’. Therefore, b is the required output."
},
{
"code": null,
"e": 27785,
"s": 27676,
"text": "Input: str=” afcdehgk”, Q = 4, queries[][] = {{1, 2, 5, 4}, {2, 5, m}, {1, 3, 7, 2}, {1, 1, 6, 4}}Output:chd"
},
{
"code": null,
"e": 27859,
"s": 27785,
"text": "Naive Approach: The simplest approach to solve the problem is as follows:"
},
{
"code": null,
"e": 28057,
"s": 27859,
"text": "For each query of type ( 1 L R K ), find the substring of S from the range of indices [L, R], and sort this substring in non-increasing order. Print the character at the Kth index in the substring."
},
{
"code": null,
"e": 28128,
"s": 28057,
"text": "For each query of type ( 2 J C ), replace the Jth character in S by C."
},
{
"code": null,
"e": 28262,
"s": 28128,
"text": "Time Complexity: O ( Q * ( N log(N) ) ), where N logN is the computational complexity of sorting each substring.Auxiliary Space: O(N)"
},
{
"code": null,
"e": 28322,
"s": 28262,
"text": "The below code is the implementation of the above approach:"
},
{
"code": null,
"e": 28326,
"s": 28322,
"text": "C++"
},
{
"code": null,
"e": 28331,
"s": 28326,
"text": "Java"
},
{
"code": null,
"e": 28339,
"s": 28331,
"text": "Python3"
},
{
"code": null,
"e": 28342,
"s": 28339,
"text": "C#"
},
{
"code": null,
"e": 28353,
"s": 28342,
"text": "Javascript"
},
{
"code": "// C++ Program to implement// the above approach #include \"bits/stdc++.h\"using namespace std; // Function to find the kth greatest// character from the strijngchar find_kth_largest(string str, int k){ // Sorting the string in // non-increasing Order sort(str.begin(), str.end(), greater<char>()); return str[k - 1];} // Function to print the K-th character// from the substring S[l] .. S[r]char printCharacter(string str, int l, int r, int k){ // 0-based indexing l = l - 1; r = r - 1; // Substring of str from the // indices l to r. string temp = str.substr(l, r - l + 1); // Extract kth Largest character char ans = find_kth_largest(temp, k); return ans;} // Function to replace character at// pos of str by the character svoid updateString(string str, int pos, char s){ // Index of S to be updated. int index = pos - 1; char c = s; // Character to be replaced // at index in S str[index] = c;} // Driver Codeint main(){ // Given string string str = \"abcddef\"; // Count of queries int Q = 3; // Queries cout << printCharacter(str, 1, 2, 2) << endl; updateString(str, 4, 'g'); cout << printCharacter(str, 1, 5, 4) << endl; return 0;}",
"e": 29654,
"s": 28353,
"text": null
},
{
"code": "// Java Program to implement// the above approach//include \"bits/stdJava.h\"import java.util.*;class GFG{ // Function to find the kth greatest// character from the strijngstatic char find_kth_largest(char []str, int k){ // Sorting the String in // non-increasing Order Arrays.sort(str); reverse(str); return str[k - 1];} static char[] reverse(char a[]) { int i, n = a.length; char t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a;} // Function to print the K-th character// from the subString S[l] .. S[r]static char printCharacter(String str, int l, int r, int k){ // 0-based indexing l = l - 1; r = r - 1; // SubString of str from the // indices l to r. String temp = str.substring(l, r - l + 1); // Extract kth Largest character char ans = find_kth_largest(temp.toCharArray(), k); return ans;} // Function to replace character at// pos of str by the character sstatic void updateString(char []str, int pos, char s){ // Index of S to be updated. int index = pos - 1; char c = s; // Character to be replaced // at index in S str[index] = c;} // Driver Codepublic static void main(String[] args){ // Given String String str = \"abcddef\"; // Count of queries int Q = 3; // Queries System.out.print(printCharacter(str, 1, 2, 2) + \"\\n\"); updateString(str.toCharArray(), 4, 'g'); System.out.print(printCharacter(str, 1, 5, 4) + \"\\n\");}} // This code is contributed by shikhasingrajput",
"e": 31295,
"s": 29654,
"text": null
},
{
"code": "# Python3 Program to implement# the above approach# Function to find the kth greatest# character from the stringdef find_kth_largest(strr, k): # Sorting the in # non-increasing Order strr = sorted(strr) strr = strr[:: -1] return strr[k - 1] # Function to print the K-th character# from the subS[l] .. S[r]def printCharacter(strr, l, r, k): #0-based indexing l = l - 1 r = r - 1 # Subof strr from the # indices l to r. temp= strr[l: r - l + 1] #Extract kth Largest character ans = find_kth_largest(temp, k) return ans # Function to replace character at# pos of strr by the character sdef updateString(strr, pos, s): # Index of S to be updated. index = pos - 1 c = s # Character to be replaced # at index in S strr[index] = c # Driver Codeif __name__ == '__main__': # Given string strr = \"abcddef\" strr=[i for i in strr] # Count of queries Q = 3 # Queries print(printCharacter(strr, 1, 2, 2)) updateString(strr, 4, 'g') print(printCharacter(strr, 1, 5, 4)) # This code is contributed by Mohit Kumar 29",
"e": 32395,
"s": 31295,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System; class GFG{ // Function to find the kth greatest// character from the stringstatic char find_kth_largest(char []str, int k){ // Sorting the String in // non-increasing Order Array.Sort(str); reverse(str); return str[k - 1];} static char[] reverse(char []a){ int i, n = a.Length; char t; for(i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a;} // Function to print the K-th character// from the subString S[l] .. S[r]static char printchar(String str, int l, int r, int k){ // 0-based indexing l = l - 1; r = r - 1; // SubString of str from the // indices l to r. String temp = str.Substring(l, r - l + 1); // Extract kth Largest character char ans = find_kth_largest( temp.ToCharArray(), k); return ans;} // Function to replace character at// pos of str by the character sstatic void updateString(char []str, int pos, char s){ // Index of S to be updated. int index = pos - 1; char c = s; // char to be replaced // at index in S str[index] = c;} // Driver Codepublic static void Main(String[] args){ // Given String String str = \"abcddef\"; // Count of queries //int Q = 3; // Queries Console.Write(printchar(str, 1, 2, 2) + \"\\n\"); updateString(str.ToCharArray(), 4, 'g'); Console.Write(printchar(str, 1, 5, 4) + \"\\n\");}} // This code is contributed by Amit Katiyar",
"e": 34010,
"s": 32395,
"text": null
},
{
"code": "<script>// Javascript Program to implement// the above approach//include \"bits/stdJava.h\" // Function to find the kth greatest// character from the strijngfunction find_kth_largest(str,k){ // Sorting the String in // non-increasing Order str.sort(); reverse(str); return str[k - 1];} function reverse(a){ let i, n = a.length; let t; for (i = 0; i < Math.floor(n / 2); i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a;} // Function to print the K-th character// from the subString S[l] .. S[r]function printCharacter(str,l,r,k){ // 0-based indexing l = l - 1; r = r - 1; // SubString of str from the // indices l to r. let temp = str.substring(l, r - l + 1); // Extract kth Largest character let ans = find_kth_largest(temp.split(\"\"), k); return ans;} // Function to replace character at// pos of str by the character sfunction updateString(str,pos,s){ // Index of S to be updated. let index = pos - 1; let c = s; // Character to be replaced // at index in S str[index] = c;} // Driver Code// Given Stringlet str = \"abcddef\";// Count of querieslet Q = 3; // Queriesdocument.write(printCharacter(str, 1, 2, 2) + \"<br>\");updateString(str.split(\"\"), 4, 'g');document.write(printCharacter(str, 1, 5, 4) + \"<br>\"); // This code is contributed by avanitrachhadiya2155</script>",
"e": 35426,
"s": 34010,
"text": null
},
{
"code": null,
"e": 35430,
"s": 35426,
"text": "a\nb"
},
{
"code": null,
"e": 35677,
"s": 35430,
"text": "Efficient Approach: The above approach can be optimized by precomputing the count of all the characters which are greater than or equal to character C ( ‘a’ ≤ C ≤ ‘z’ ) efficiently using a Fenwick Tree.Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 35758,
"s": 35677,
"text": "Create a Fenwick Tree to store the frequencies of all characters from ‘a’ to ‘z‘"
},
{
"code": null,
"e": 35873,
"s": 35758,
"text": "For every query of type 1, check for each character from ‘z’ to ‘a’, whether it is the Kth the greatest character."
},
{
"code": null,
"e": 36072,
"s": 35873,
"text": "In order to perform this, traverse from ‘z’ to ‘a’ and for each character, check if the count of all the characters traversed becomes ≥ K or not. Print the character for which the count becomes ≥ K."
},
{
"code": null,
"e": 36123,
"s": 36072,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 36127,
"s": 36123,
"text": "C++"
},
{
"code": null,
"e": 36132,
"s": 36127,
"text": "Java"
},
{
"code": null,
"e": 36140,
"s": 36132,
"text": "Python3"
},
{
"code": null,
"e": 36143,
"s": 36140,
"text": "C#"
},
{
"code": null,
"e": 36154,
"s": 36143,
"text": "Javascript"
},
{
"code": "// C++ Program to implement// the above approach #include \"bits/stdc++.h\"using namespace std; // Maximum Size of a Stringconst int maxn = 100005; // Fenwick Tree to store the// frequencies of 26 alphabetsint BITree[26][maxn]; // Size of the String.int N; // Function to update Fenwick Tree for// Character c at index valvoid update_BITree(int index, char C, int val){ while (index <= N) { // Add val to current node // Fenwick Tree BITree[C - 'a'][index] += val; // Move index to parent node // in update View index += (index & -index); }} // Function to get sum of frequencies// of character c till indexint sum_BITree(int index, char C){ // Stores the sum int s = 0; while (index) { // Add current element of // Fenwick tree to sum s += BITree[C - 'a'][index]; // Move index to parent node // in getSum View index -= (index & -index); } return s;} // Function to create the Fenwick treevoid buildTree(string str){ for (int i = 1; i <= N; i++) { update_BITree(i, str[i], 1); } cout << endl;} // Function to print the kth largest// character in the range of l to rchar printCharacter(string str, int l, int r, int k){ // Stores the count of // characters int count = 0; // Stores the required // character char ans; for (char C = 'z'; C >= 'a'; C--) { // Calculate frequency of // C in the given range int times = sum_BITree(r, C) - sum_BITree(l - 1, C); // Increase count count += times; // If count exceeds K if (count >= k) { // Required character // found ans = C; break; } } return ans;} // Function to update character// at pos by character svoid updateTree(string str, int pos, char s){ // 0 based index system int index = pos; update_BITree(index, str[index], -1); str[index] = s; update_BITree(index, s, 1);} // Driver Codeint main(){ string str = \"abcddef\"; N = str.size(); // Makes the string 1-based indexed str = '#' + str; // Number of queries int Q = 3; // Construct the Fenwick Tree buildTree(str); cout << printCharacter(str, 1, 2, 2) << endl; updateTree(str, 4, 'g'); cout << printCharacter(str, 1, 5, 4) << endl; return 0;}",
"e": 38615,
"s": 36154,
"text": null
},
{
"code": "// Java Program to implement// the above approach //include \"bits/stdJava.h\"import java.util.*;class GFG{ // Maximum Size of a Stringstatic int maxn = 100005; // Fenwick Tree to store the// frequencies of 26 alphabetsstatic int [][]BITree = new int[26][maxn]; // Size of the String.static int N; // Function to update Fenwick Tree for// Character c at index valstatic void update_BITree(int index, char C, int val){ while (index <= N) { // Add val to current node // Fenwick Tree BITree[C - 'a'][index] += val; // Move index to parent node // in update View index += (index & -index); }} // Function to get sum of frequencies// of character c till indexstatic int sum_BITree(int index, char C){ // Stores the sum int s = 0; while (index > 0) { // Add current element of // Fenwick tree to sum s += BITree[C - 'a'][index]; // Move index to parent node // in getSum View index -= (index & -index); } return s;} // Function to create the Fenwick treestatic void buildTree(String str){ for (int i = 1; i <= N; i++) { update_BITree(i, str.charAt(i), 1); } System.out.println();} // Function to print the kth largest// character in the range of l to rstatic char printCharacter(String str, int l, int r, int k){ // Stores the count of // characters int count = 0; // Stores the required // character char ans = 0; for (char C = 'z'; C >= 'a'; C--) { // Calculate frequency of // C in the given range int times = sum_BITree(r, C) - sum_BITree(l - 1, C); // Increase count count += times; // If count exceeds K if (count >= k) { // Required character // found ans = C; break; } } return ans;} // Function to update character// at pos by character sstatic void updateTree(String str, int pos, char s){ // 0 based index system int index = pos; update_BITree(index, str.charAt(index), -1); str = str.substring(0, index) + s + str.substring(index + 1); update_BITree(index, s, 1);} // Driver Codepublic static void main(String[] args){ String str = \"abcddef\"; N = str.length(); // Makes the String 1-based indexed str = '/' + str; // Number of queries int Q = 3; // Construct the Fenwick Tree buildTree(str); System.out.print(printCharacter(str, 1, 2, 2) + \"\\n\"); updateTree(str, 4, 'g'); System.out.print(printCharacter(str, 1, 5, 4) + \"\\n\"); }} // This code is contributed by shikhasingrajput",
"e": 41214,
"s": 38615,
"text": null
},
{
"code": "# Python3 Program to implement# the above approach # Maximum Size of a Stringmaxn = 100005 # Fenwick Tree to store the# frequencies of 26 alphabetsBITree = [[0 for x in range(maxn)] for y in range(26)] # Size of the String.N = 0 # Function to update Fenwick Tree for# Character c at index valdef update_BITree(index, C, val): while (index <= N): # Add val to current node # Fenwick Tree BITree[ord(C) - ord('a')][index]+= val # Move index to parent node # in update View index += (index & -index) # Function to get sum of# frequencies of character# c till indexdef sum_BITree(index, C): # Stores the sum s = 0 while (index): # Add current element of # Fenwick tree to sum s += BITree[ord(C) - ord('a')][index] # Move index to parent node # in getSum View index -= (index & -index) return s # Function to create# the Fenwick treedef buildTree(st): for i in range(1, N + 1): update_BITree(i, st[i], 1) print() # Function to print the# kth largest character# in the range of l to rdef printCharacter(st, l, r, k): # Stores the count of # characters count = 0 for C in range(ord('z'), ord('a') - 1, -1): # Calculate frequency of # C in the given range times = (sum_BITree(r, chr(C)) - sum_BITree(l - 1, chr(C))) # Increase count count += times # If count exceeds K if (count >= k): # Required character # found ans = chr( C) break return ans # Function to update character# at pos by character sdef updateTree(st, pos, s): # 0 based index system index = pos; update_BITree(index, st[index], -1) st.replace(st[index], s, 1) update_BITree(index, s, 1) # Driver Codeif __name__ == \"__main__\": st = \"abcddef\" N = len(st) # Makes the string # 1-based indexed st = '#' + st # Number of queries Q = 3 # Construct the Fenwick Tree buildTree(st) print (printCharacter(st, 1, 2, 2)) updateTree(st, 4, 'g') print (printCharacter(st, 1, 5, 4)) # This code is contributed by Chitranayal",
"e": 43613,
"s": 41214,
"text": null
},
{
"code": "// C# Program to implement// the above approachusing System;class GFG{ // Maximum Size of a Stringstatic int maxn = 100005; // Fenwick Tree to store the// frequencies of 26 alphabetsstatic int [,]BITree = new int[26, maxn]; // Size of the String.static int N; // Function to update Fenwick Tree for// char c at index valstatic void update_BITree(int index, char C, int val){ while (index <= N) { // Add val to current node // Fenwick Tree BITree[C - 'a', index] += val; // Move index to parent node // in update View index += (index & -index); }} // Function to get sum of frequencies// of character c till indexstatic int sum_BITree(int index, char C){ // Stores the sum int s = 0; while (index > 0) { // Add current element of // Fenwick tree to sum s += BITree[C - 'a', index]; // Move index to parent node // in getSum View index -= (index & -index); } return s;} // Function to create the Fenwick treestatic void buildTree(String str){ for (int i = 1; i <= N; i++) { update_BITree(i, str[i], 1); } Console.WriteLine();} // Function to print the kth largest// character in the range of l to rstatic char printchar(String str, int l, int r, int k){ // Stores the count of // characters int count = 0; // Stores the required // character char ans = (char)0; for (char C = 'z'; C >= 'a'; C--) { // Calculate frequency of // C in the given range int times = sum_BITree(r, C) - sum_BITree(l - 1, C); // Increase count count += times; // If count exceeds K if (count >= k) { // Required character // found ans = C; break; } } return ans;} // Function to update character// at pos by character sstatic void updateTree(String str, int pos, char s){ // 0 based index system int index = pos; update_BITree(index, str[index], -1); str = str.Substring(0, index) + s + str.Substring(index + 1); update_BITree(index, s, 1);} // Driver Codepublic static void Main(String[] args){ String str = \"abcddef\"; N = str.Length; // Makes the String 1-based indexed str = '/' + str; // Number of queries int Q = 3; // Construct the Fenwick Tree buildTree(str); Console.Write(printchar(str, 1, 2, 2) + \"\\n\"); updateTree(str, 4, 'g'); Console.Write(printchar(str, 1, 5, 4) + \"\\n\");}} // This code is contributed by Rajput-Ji",
"e": 46051,
"s": 43613,
"text": null
},
{
"code": "<script>// Javascript Program to implement// the above approach // Maximum Size of a Stringlet maxn = 100005; // Fenwick Tree to store the// frequencies of 26 alphabetslet BITree = new Array(26);for(let i=0;i<26;i++){ BITree[i]=new Array(maxn); for(let j=0;j<maxn;j++) { BITree[i][j]=0; } } // Size of the String.let N; // Function to update Fenwick Tree for// Character c at index valfunction update_BITree(index,C,val){ while (index <= N) { // Add val to current node // Fenwick Tree BITree[C.charCodeAt(0) - 'a'.charCodeAt(0)][index] += val; // Move index to parent node // in update View index += (index & -index); }} // Function to get sum of frequencies// of character c till indexfunction sum_BITree(index,C){ // Stores the sum let s = 0; while (index > 0) { // Add current element of // Fenwick tree to sum s += BITree[C.charCodeAt(0) - 'a'.charCodeAt(0)][index]; // Move index to parent node // in getSum View index -= (index & -index); } return s;} // Function to create the Fenwick treefunction buildTree(str){ for (let i = 1; i <= N; i++) { update_BITree(i, str[i], 1); } document.write(\"<br>\");} // Function to print the kth largest// character in the range of l to rfunction printCharacter(str,l,r,k){ // Stores the count of // characters let count = 0; // Stores the required // character let ans = 0; for (let C = 'z'.charCodeAt(0); C >= 'a'.charCodeAt(0); C--) { // Calculate frequency of // C in the given range let times = sum_BITree(r, String.fromCharCode(C)) - sum_BITree(l - 1, String.fromCharCode(C)); // Increase count count += times; // If count exceeds K if (count >= k) { // Required character // found ans = String.fromCharCode(C); break; } } return ans;} // Function to update character// at pos by character sfunction updateTree(str,pos,s){ // 0 based index system let index = pos; update_BITree(index, str[index], -1); str = str.substring(0, index) + s + str.substring(index + 1); update_BITree(index, s, 1);} // Driver Codelet str = \"abcddef\";N = str.length; // Makes the String 1-based indexedstr = '/' + str; // Number of querieslet Q = 3; // Construct the Fenwick TreebuildTree(str); document.write(printCharacter(str, 1, 2, 2) + \"<br>\");updateTree(str, 4, 'g');document.write(printCharacter(str, 1, 5, 4) + \"<br>\"); // This code is contributed by rag2127</script>",
"e": 48615,
"s": 46051,
"text": null
},
{
"code": null,
"e": 48619,
"s": 48615,
"text": "a\nb"
},
{
"code": null,
"e": 48748,
"s": 48619,
"text": "Time Complexity: O( QlogN + NlogN ) Auxiliary Space: O(26 * maxn), where maxn denotes the maximum possible length of the string."
},
{
"code": null,
"e": 48763,
"s": 48748,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 48780,
"s": 48763,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 48795,
"s": 48780,
"text": "amit143katiyar"
},
{
"code": null,
"e": 48805,
"s": 48795,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 48811,
"s": 48805,
"text": "ukasp"
},
{
"code": null,
"e": 48825,
"s": 48811,
"text": "sumitgumber28"
},
{
"code": null,
"e": 48842,
"s": 48825,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 48863,
"s": 48842,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 48871,
"s": 48863,
"text": "rag2127"
},
{
"code": null,
"e": 48886,
"s": 48871,
"text": "sagartomar9927"
},
{
"code": null,
"e": 48899,
"s": 48886,
"text": "ankita_saini"
},
{
"code": null,
"e": 48919,
"s": 48899,
"text": "array-range-queries"
},
{
"code": null,
"e": 48923,
"s": 48919,
"text": "BIT"
},
{
"code": null,
"e": 48942,
"s": 48923,
"text": "frequency-counting"
},
{
"code": null,
"e": 48966,
"s": 48942,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 48973,
"s": 48966,
"text": "Arrays"
},
{
"code": null,
"e": 48986,
"s": 48973,
"text": "Mathematical"
},
{
"code": null,
"e": 48996,
"s": 48986,
"text": "Searching"
},
{
"code": null,
"e": 49004,
"s": 48996,
"text": "Sorting"
},
{
"code": null,
"e": 49012,
"s": 49004,
"text": "Strings"
},
{
"code": null,
"e": 49019,
"s": 49012,
"text": "Arrays"
},
{
"code": null,
"e": 49029,
"s": 49019,
"text": "Searching"
},
{
"code": null,
"e": 49037,
"s": 49029,
"text": "Strings"
},
{
"code": null,
"e": 49050,
"s": 49037,
"text": "Mathematical"
},
{
"code": null,
"e": 49058,
"s": 49050,
"text": "Sorting"
},
{
"code": null,
"e": 49156,
"s": 49058,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 49196,
"s": 49156,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 49225,
"s": 49196,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 49257,
"s": 49225,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 49286,
"s": 49257,
"text": "Disjoint Set Data Structures"
},
{
"code": null,
"e": 49322,
"s": 49286,
"text": "Binary Indexed Tree or Fenwick Tree"
},
{
"code": null,
"e": 49337,
"s": 49322,
"text": "Arrays in Java"
},
{
"code": null,
"e": 49353,
"s": 49337,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 49421,
"s": 49353,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 49467,
"s": 49421,
"text": "Write a program to reverse an array or string"
}
] |
C Program For Finding The Middle Element Of A Given Linked List - GeeksforGeeks
|
08 Dec, 2021
Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list is 1->2->3->4->5->6 then the output should be 4.
Method 1: Traverse the whole linked list and count the no. of nodes. Now traverse the list again till count/2 and return the node at count/2.
Method 2: Traverse linked list using two pointers. Move one pointer by one and the other pointers by two. When the fast pointer reaches the end slow pointer will reach the middle of the linked list.
Below image shows how printMiddle function works in the code :
C
// C program to find middle of linked list#include<stdio.h> #include<stdlib.h> // Link list nodestruct Node { int data; struct Node* next; }; // Function to get the middle of // the linked listvoid printMiddle(struct Node *head) { struct Node *slow_ptr = head; struct Node *fast_ptr = head; if (head!=NULL) { while (fast_ptr != NULL && fast_ptr->next != NULL) { fast_ptr = fast_ptr->next->next; slow_ptr = slow_ptr->next; } printf("The middle element is [%d]", slow_ptr->data); } } void push(struct Node** head_ref, int new_data) { // Allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // Put in the data new_node->data = new_data; // Link the old list off the new node new_node->next = (*head_ref); // Move the head to point to the new node (*head_ref) = new_node; } // A utility function to print a given// linked list void printList(struct Node *ptr) { while (ptr != NULL) { printf("%d->", ptr->data); ptr = ptr->next; } printf("NULL"); } // Driver codeint main() { // Start with the empty list struct Node* head = NULL; int i; for (i = 5; i > 0; i--) { push(&head, i); printList(head); printMiddle(head); } return 0; }
Output:
5->NULL
The middle element is [5]
4->5->NULL
The middle element is [5]
3->4->5->NULL
The middle element is [4]
2->3->4->5->NULL
The middle element is [4]
1->2->3->4->5->NULL
The middle element is [3]
Method 3: Initialize mid element as head and initialize a counter as 0. Traverse the list from head, while traversing increment the counter and change mid to mid->next whenever the counter is odd. So the mid will move only half of the total length of the list. Thanks to Narendra Kangralkar for suggesting this method.
C
// C program to implement the // above approach#include <stdio.h>#include <stdlib.h> // Link list nodestruct node { int data; struct node* next;}; // Function to get the middle of // the linked listvoid printMiddle(struct node* head){ int count = 0; struct node* mid = head; while (head != NULL) { // Update mid, when 'count' // is odd number if (count & 1) mid = mid->next; ++count; head = head->next; } // If empty list is provided if (mid != NULL) printf("The middle element is [%d]", mid->data);} void push(struct node** head_ref, int new_data){ // Allocate node struct node* new_node = (struct node*)malloc(sizeof(struct node)); // Put in the data new_node->data = new_data; // Link the old list off the new node new_node->next = (*head_ref); // Move the head to point to the new node (*head_ref) = new_node;} // A utility function to print a // given linked listvoid printList(struct node* ptr){ while (ptr != NULL) { printf("%d->", ptr->data); ptr = ptr->next; } printf("NULL");} // Driver codeint main(){ // Start with the empty list struct node* head = NULL; int i; for (i = 5; i > 0; i--) { push(&head, i); printList(head); printMiddle(head); } return 0;}
Output:
5->NULL
The middle element is [5]
4->5->NULL
The middle element is [5]
3->4->5->NULL
The middle element is [4]
2->3->4->5->NULL
The middle element is [4]
1->2->3->4->5->NULL
The middle element is [3]
Please refer complete article on Find the middle of a given linked list for more details!
Adobe
Amazon
Flipkart
GE
Hike
Linked Lists
MAQ Software
Microsoft
Morgan Stanley
Nagarro
Payu
Qualcomm
Samsung
Veritas
VMWare
Wipro
Zoho
C Language
C Programs
Linked List
VMWare
Zoho
Flipkart
Morgan Stanley
Amazon
Microsoft
Samsung
Hike
Payu
MAQ Software
Adobe
Wipro
Qualcomm
Nagarro
GE
Veritas
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Strings in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
Header files in C/C++ and its uses
Basics of File Handling in C
|
[
{
"code": null,
"e": 25531,
"s": 25503,
"text": "\n08 Dec, 2021"
},
{
"code": null,
"e": 25870,
"s": 25531,
"text": "Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list is 1->2->3->4->5->6 then the output should be 4. "
},
{
"code": null,
"e": 26013,
"s": 25870,
"text": "Method 1: Traverse the whole linked list and count the no. of nodes. Now traverse the list again till count/2 and return the node at count/2. "
},
{
"code": null,
"e": 26212,
"s": 26013,
"text": "Method 2: Traverse linked list using two pointers. Move one pointer by one and the other pointers by two. When the fast pointer reaches the end slow pointer will reach the middle of the linked list."
},
{
"code": null,
"e": 26275,
"s": 26212,
"text": "Below image shows how printMiddle function works in the code :"
},
{
"code": null,
"e": 26277,
"s": 26275,
"text": "C"
},
{
"code": "// C program to find middle of linked list#include<stdio.h> #include<stdlib.h> // Link list nodestruct Node { int data; struct Node* next; }; // Function to get the middle of // the linked listvoid printMiddle(struct Node *head) { struct Node *slow_ptr = head; struct Node *fast_ptr = head; if (head!=NULL) { while (fast_ptr != NULL && fast_ptr->next != NULL) { fast_ptr = fast_ptr->next->next; slow_ptr = slow_ptr->next; } printf(\"The middle element is [%d]\", slow_ptr->data); } } void push(struct Node** head_ref, int new_data) { // Allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // Put in the data new_node->data = new_data; // Link the old list off the new node new_node->next = (*head_ref); // Move the head to point to the new node (*head_ref) = new_node; } // A utility function to print a given// linked list void printList(struct Node *ptr) { while (ptr != NULL) { printf(\"%d->\", ptr->data); ptr = ptr->next; } printf(\"NULL\"); } // Driver codeint main() { // Start with the empty list struct Node* head = NULL; int i; for (i = 5; i > 0; i--) { push(&head, i); printList(head); printMiddle(head); } return 0; } ",
"e": 27703,
"s": 26277,
"text": null
},
{
"code": null,
"e": 27711,
"s": 27703,
"text": "Output:"
},
{
"code": null,
"e": 27915,
"s": 27711,
"text": "5->NULL\nThe middle element is [5]\n\n4->5->NULL\nThe middle element is [5]\n\n3->4->5->NULL\nThe middle element is [4]\n\n2->3->4->5->NULL\nThe middle element is [4]\n\n1->2->3->4->5->NULL\nThe middle element is [3]"
},
{
"code": null,
"e": 28235,
"s": 27915,
"text": "Method 3: Initialize mid element as head and initialize a counter as 0. Traverse the list from head, while traversing increment the counter and change mid to mid->next whenever the counter is odd. So the mid will move only half of the total length of the list. Thanks to Narendra Kangralkar for suggesting this method. "
},
{
"code": null,
"e": 28237,
"s": 28235,
"text": "C"
},
{
"code": "// C program to implement the // above approach#include <stdio.h>#include <stdlib.h> // Link list nodestruct node { int data; struct node* next;}; // Function to get the middle of // the linked listvoid printMiddle(struct node* head){ int count = 0; struct node* mid = head; while (head != NULL) { // Update mid, when 'count' // is odd number if (count & 1) mid = mid->next; ++count; head = head->next; } // If empty list is provided if (mid != NULL) printf(\"The middle element is [%d]\", mid->data);} void push(struct node** head_ref, int new_data){ // Allocate node struct node* new_node = (struct node*)malloc(sizeof(struct node)); // Put in the data new_node->data = new_data; // Link the old list off the new node new_node->next = (*head_ref); // Move the head to point to the new node (*head_ref) = new_node;} // A utility function to print a // given linked listvoid printList(struct node* ptr){ while (ptr != NULL) { printf(\"%d->\", ptr->data); ptr = ptr->next; } printf(\"NULL\");} // Driver codeint main(){ // Start with the empty list struct node* head = NULL; int i; for (i = 5; i > 0; i--) { push(&head, i); printList(head); printMiddle(head); } return 0;}",
"e": 29639,
"s": 28237,
"text": null
},
{
"code": null,
"e": 29647,
"s": 29639,
"text": "Output:"
},
{
"code": null,
"e": 29851,
"s": 29647,
"text": "5->NULL\nThe middle element is [5]\n\n4->5->NULL\nThe middle element is [5]\n\n3->4->5->NULL\nThe middle element is [4]\n\n2->3->4->5->NULL\nThe middle element is [4]\n\n1->2->3->4->5->NULL\nThe middle element is [3]"
},
{
"code": null,
"e": 29941,
"s": 29851,
"text": "Please refer complete article on Find the middle of a given linked list for more details!"
},
{
"code": null,
"e": 29947,
"s": 29941,
"text": "Adobe"
},
{
"code": null,
"e": 29954,
"s": 29947,
"text": "Amazon"
},
{
"code": null,
"e": 29963,
"s": 29954,
"text": "Flipkart"
},
{
"code": null,
"e": 29966,
"s": 29963,
"text": "GE"
},
{
"code": null,
"e": 29971,
"s": 29966,
"text": "Hike"
},
{
"code": null,
"e": 29984,
"s": 29971,
"text": "Linked Lists"
},
{
"code": null,
"e": 29997,
"s": 29984,
"text": "MAQ Software"
},
{
"code": null,
"e": 30007,
"s": 29997,
"text": "Microsoft"
},
{
"code": null,
"e": 30022,
"s": 30007,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 30030,
"s": 30022,
"text": "Nagarro"
},
{
"code": null,
"e": 30035,
"s": 30030,
"text": "Payu"
},
{
"code": null,
"e": 30044,
"s": 30035,
"text": "Qualcomm"
},
{
"code": null,
"e": 30052,
"s": 30044,
"text": "Samsung"
},
{
"code": null,
"e": 30060,
"s": 30052,
"text": "Veritas"
},
{
"code": null,
"e": 30067,
"s": 30060,
"text": "VMWare"
},
{
"code": null,
"e": 30073,
"s": 30067,
"text": "Wipro"
},
{
"code": null,
"e": 30078,
"s": 30073,
"text": "Zoho"
},
{
"code": null,
"e": 30089,
"s": 30078,
"text": "C Language"
},
{
"code": null,
"e": 30100,
"s": 30089,
"text": "C Programs"
},
{
"code": null,
"e": 30112,
"s": 30100,
"text": "Linked List"
},
{
"code": null,
"e": 30119,
"s": 30112,
"text": "VMWare"
},
{
"code": null,
"e": 30124,
"s": 30119,
"text": "Zoho"
},
{
"code": null,
"e": 30133,
"s": 30124,
"text": "Flipkart"
},
{
"code": null,
"e": 30148,
"s": 30133,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 30155,
"s": 30148,
"text": "Amazon"
},
{
"code": null,
"e": 30165,
"s": 30155,
"text": "Microsoft"
},
{
"code": null,
"e": 30173,
"s": 30165,
"text": "Samsung"
},
{
"code": null,
"e": 30178,
"s": 30173,
"text": "Hike"
},
{
"code": null,
"e": 30183,
"s": 30178,
"text": "Payu"
},
{
"code": null,
"e": 30196,
"s": 30183,
"text": "MAQ Software"
},
{
"code": null,
"e": 30202,
"s": 30196,
"text": "Adobe"
},
{
"code": null,
"e": 30208,
"s": 30202,
"text": "Wipro"
},
{
"code": null,
"e": 30217,
"s": 30208,
"text": "Qualcomm"
},
{
"code": null,
"e": 30225,
"s": 30217,
"text": "Nagarro"
},
{
"code": null,
"e": 30228,
"s": 30225,
"text": "GE"
},
{
"code": null,
"e": 30236,
"s": 30228,
"text": "Veritas"
},
{
"code": null,
"e": 30248,
"s": 30236,
"text": "Linked List"
},
{
"code": null,
"e": 30346,
"s": 30248,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30384,
"s": 30346,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 30410,
"s": 30384,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 30430,
"s": 30410,
"text": "Multithreading in C"
},
{
"code": null,
"e": 30452,
"s": 30430,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 30493,
"s": 30452,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 30506,
"s": 30493,
"text": "Strings in C"
},
{
"code": null,
"e": 30547,
"s": 30506,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 30588,
"s": 30547,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 30623,
"s": 30588,
"text": "Header files in C/C++ and its uses"
}
] |
How to Run a Python Script using Docker? - GeeksforGeeks
|
14 Apr, 2022
The task is to build a docker image and execute a python script that adds two given numbers. This has been achieved via a series of steps.
We will be creating a Folder docker_2 at the desktop location in our PC . Inside the Folder another Folder called docker_assignment is created. Then two files dockerfile and test.py are created in this folder.
Folder
Inside the dockerfile we will start by first taking the python base image from docker hub. A tag latest is used to get the latest official python image. It is very important to set your working directory inside your container. I have chosen /usr/src/app. All commands will be executed here as well as the images will be copied here only.
I have then copied the test.py file from my pc to the container current working directory(./ or /usr/src/app) by using the COPY command.
#Deriving the latest base image
FROM python:latest
#Labels as key value pair
LABEL Maintainer="roushan.me17"
# Any working directory can be chosen as per choice like '/' or '/home' etc
# i have chosen /usr/app/src
WORKDIR /usr/app/src
#to COPY the remote file at working directory in container
COPY test.py ./
# Now the structure looks like this '/usr/app/src/test.py'
#CMD instruction should be used to run the software
#contained by your image, along with any arguments.
CMD [ "python", "./test.py"]
After you have created both the Python script and the Dockerfile, you can now use the Docker build command to build your Docker Image.
Here -t is for adding tags so as to identify your image easily.
docker image build -t python:0.0.1 /home/roushan/Desktop/docker_2/docker_assignment
After you have built your Docker Image, you can list all the Images to check whether your image has been successfully built or not.
docker images
You will find your Image name listed here and with the tag name, you can easily find it.
Now, you can use the Docker run command to run your Docker Container.
docker run python:0.0.1
After running the Docker Container, you will see the output printed after adding the two numbers.
To conclude, in this article, we saw how to build a simple addition Python script and run it inside the Docker Container.
wolowitzcoefficient
sumitgumber28
rkbhola5
gtasop
Docker Container
linux
Advanced Computer Subject
Python
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Decision Tree
Decision Tree Introduction with example
System Design Tutorial
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 25779,
"s": 25751,
"text": "\n14 Apr, 2022"
},
{
"code": null,
"e": 25918,
"s": 25779,
"text": "The task is to build a docker image and execute a python script that adds two given numbers. This has been achieved via a series of steps."
},
{
"code": null,
"e": 26128,
"s": 25918,
"text": "We will be creating a Folder docker_2 at the desktop location in our PC . Inside the Folder another Folder called docker_assignment is created. Then two files dockerfile and test.py are created in this folder."
},
{
"code": null,
"e": 26136,
"s": 26128,
"text": "Folder "
},
{
"code": null,
"e": 26474,
"s": 26136,
"text": "Inside the dockerfile we will start by first taking the python base image from docker hub. A tag latest is used to get the latest official python image. It is very important to set your working directory inside your container. I have chosen /usr/src/app. All commands will be executed here as well as the images will be copied here only."
},
{
"code": null,
"e": 26613,
"s": 26474,
"text": "I have then copied the test.py file from my pc to the container current working directory(./ or /usr/src/app) by using the COPY command. "
},
{
"code": null,
"e": 27123,
"s": 26613,
"text": "#Deriving the latest base image\nFROM python:latest\n\n\n#Labels as key value pair\nLABEL Maintainer=\"roushan.me17\"\n\n\n# Any working directory can be chosen as per choice like '/' or '/home' etc\n# i have chosen /usr/app/src\nWORKDIR /usr/app/src\n\n#to COPY the remote file at working directory in container\nCOPY test.py ./\n# Now the structure looks like this '/usr/app/src/test.py'\n\n\n#CMD instruction should be used to run the software\n#contained by your image, along with any arguments.\n\nCMD [ \"python\", \"./test.py\"]"
},
{
"code": null,
"e": 27258,
"s": 27123,
"text": "After you have created both the Python script and the Dockerfile, you can now use the Docker build command to build your Docker Image."
},
{
"code": null,
"e": 27322,
"s": 27258,
"text": "Here -t is for adding tags so as to identify your image easily."
},
{
"code": null,
"e": 27406,
"s": 27322,
"text": "docker image build -t python:0.0.1 /home/roushan/Desktop/docker_2/docker_assignment"
},
{
"code": null,
"e": 27538,
"s": 27406,
"text": "After you have built your Docker Image, you can list all the Images to check whether your image has been successfully built or not."
},
{
"code": null,
"e": 27552,
"s": 27538,
"text": "docker images"
},
{
"code": null,
"e": 27641,
"s": 27552,
"text": "You will find your Image name listed here and with the tag name, you can easily find it."
},
{
"code": null,
"e": 27711,
"s": 27641,
"text": "Now, you can use the Docker run command to run your Docker Container."
},
{
"code": null,
"e": 27735,
"s": 27711,
"text": "docker run python:0.0.1"
},
{
"code": null,
"e": 27833,
"s": 27735,
"text": "After running the Docker Container, you will see the output printed after adding the two numbers."
},
{
"code": null,
"e": 27955,
"s": 27833,
"text": "To conclude, in this article, we saw how to build a simple addition Python script and run it inside the Docker Container."
},
{
"code": null,
"e": 27975,
"s": 27955,
"text": "wolowitzcoefficient"
},
{
"code": null,
"e": 27989,
"s": 27975,
"text": "sumitgumber28"
},
{
"code": null,
"e": 27998,
"s": 27989,
"text": "rkbhola5"
},
{
"code": null,
"e": 28005,
"s": 27998,
"text": "gtasop"
},
{
"code": null,
"e": 28022,
"s": 28005,
"text": "Docker Container"
},
{
"code": null,
"e": 28028,
"s": 28022,
"text": "linux"
},
{
"code": null,
"e": 28054,
"s": 28028,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 28061,
"s": 28054,
"text": "Python"
},
{
"code": null,
"e": 28070,
"s": 28061,
"text": "TechTips"
},
{
"code": null,
"e": 28168,
"s": 28070,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28191,
"s": 28168,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 28214,
"s": 28191,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 28228,
"s": 28214,
"text": "Decision Tree"
},
{
"code": null,
"e": 28268,
"s": 28228,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 28291,
"s": 28268,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 28319,
"s": 28291,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 28369,
"s": 28319,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 28391,
"s": 28369,
"text": "Python map() function"
}
] |
Chomsky Hierarchy in Theory of Computation - GeeksforGeeks
|
10 May, 2022
According to Chomsky hierarchy, grammar is divided into 4 types as follows:
Type 0 is known as unrestricted grammar.Type 1 is known as context-sensitive grammar.Type 2 is known as a context-free grammar.Type 3 Regular Grammar.
Type 0 is known as unrestricted grammar.
Type 1 is known as context-sensitive grammar.
Type 2 is known as a context-free grammar.
Type 3 Regular Grammar.
Type 0: Unrestricted Grammar:
Type-0 grammars include all formal grammar. Type 0 grammar languages are recognized by turing machine. These languages are also known as the Recursively Enumerable languages.
Grammar Production in the form of where
\alpha is ( V + T)* V ( V + T)*
V : Variables
T : Terminals.
is ( V + T )*.
In type 0 there must be at least one variable on the Left side of production.
For example:
Sab --> ba
A --> S
Here, Variables are S, A, and Terminals a, b.
Type 1: Context-Sensitive Grammar
Type-1 grammars generate context-sensitive languages. The language generated by the grammar is recognized by the Linear Bound Automata
In Type 1
First of all Type 1 grammar should be Type 0.
Grammar Production in the form of
|\alpha |<=|\beta |
That is the count of symbol in is less than or equal to
Also β ∈ (V + T)+
i.e. β can not be ε For Example:
S --> AB
AB --> abc
B --> b
Type 2: Context-Free Grammar: Type-2 grammars generate context-free languages. The language generated by the grammar is recognized by a Pushdown automata. In Type 2:
First of all, it should be Type 1.
The left-hand side of production can have only one variable and there is no restriction on
|\alpha | = 1.
For example:
S --> AB
A --> a
B --> b
Type 3: Regular Grammar: Type-3 grammars generate regular languages. These languages are exactly all languages that can be accepted by a finite-state automaton. Type 3 is the most restricted form of grammar.
Type 3 should be in the given form only :
V --> VT / T (left-regular grammar)
(or)
V --> TV /T (right-regular grammar)
For example:
S --> a
The above form is called strictly regular grammar.
There is another form of regular grammar called extended regular grammar. In this form:
V --> VT* / T*. (extended left-regular grammar)
(or)
V --> T*V /T* (extended right-regular grammar)
For example :
S --> ab.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
VaibhavRai3
chaitalykundu
sandravsnair
umeshg17
niharikatanwar61
bumblebeecoding
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between DFA and NFA
Regular expression to ∈-NFA
NPDA for accepting the language L = {wwR | w ∈ (a,b)*}
Design 101 sequence detector (Mealy machine)
Closure properties of Regular languages
Conversion of Epsilon-NFA to NFA
Difference between Pushdown Automata and Finite Automata
Last Minute Notes - Theory of Computation
Variation of Turing Machine
Boyer-Moore Majority Voting Algorithm
|
[
{
"code": null,
"e": 31079,
"s": 31051,
"text": "\n10 May, 2022"
},
{
"code": null,
"e": 31156,
"s": 31079,
"text": "According to Chomsky hierarchy, grammar is divided into 4 types as follows: "
},
{
"code": null,
"e": 31307,
"s": 31156,
"text": "Type 0 is known as unrestricted grammar.Type 1 is known as context-sensitive grammar.Type 2 is known as a context-free grammar.Type 3 Regular Grammar."
},
{
"code": null,
"e": 31348,
"s": 31307,
"text": "Type 0 is known as unrestricted grammar."
},
{
"code": null,
"e": 31394,
"s": 31348,
"text": "Type 1 is known as context-sensitive grammar."
},
{
"code": null,
"e": 31437,
"s": 31394,
"text": "Type 2 is known as a context-free grammar."
},
{
"code": null,
"e": 31461,
"s": 31437,
"text": "Type 3 Regular Grammar."
},
{
"code": null,
"e": 31492,
"s": 31461,
"text": "Type 0: Unrestricted Grammar: "
},
{
"code": null,
"e": 31668,
"s": 31492,
"text": "Type-0 grammars include all formal grammar. Type 0 grammar languages are recognized by turing machine. These languages are also known as the Recursively Enumerable languages. "
},
{
"code": null,
"e": 31710,
"s": 31668,
"text": "Grammar Production in the form of where "
},
{
"code": null,
"e": 31782,
"s": 31710,
"text": "\\alpha is ( V + T)* V ( V + T)* \nV : Variables \nT : Terminals. "
},
{
"code": null,
"e": 31798,
"s": 31782,
"text": "is ( V + T )*. "
},
{
"code": null,
"e": 31877,
"s": 31798,
"text": "In type 0 there must be at least one variable on the Left side of production. "
},
{
"code": null,
"e": 31891,
"s": 31877,
"text": "For example: "
},
{
"code": null,
"e": 31911,
"s": 31891,
"text": "Sab --> ba \nA --> S"
},
{
"code": null,
"e": 31958,
"s": 31911,
"text": "Here, Variables are S, A, and Terminals a, b. "
},
{
"code": null,
"e": 31992,
"s": 31958,
"text": "Type 1: Context-Sensitive Grammar"
},
{
"code": null,
"e": 32128,
"s": 31992,
"text": "Type-1 grammars generate context-sensitive languages. The language generated by the grammar is recognized by the Linear Bound Automata "
},
{
"code": null,
"e": 32139,
"s": 32128,
"text": "In Type 1 "
},
{
"code": null,
"e": 32186,
"s": 32139,
"text": "First of all Type 1 grammar should be Type 0. "
},
{
"code": null,
"e": 32221,
"s": 32186,
"text": "Grammar Production in the form of "
},
{
"code": null,
"e": 32242,
"s": 32221,
"text": "\n|\\alpha |<=|\\beta |"
},
{
"code": null,
"e": 32299,
"s": 32242,
"text": "That is the count of symbol in is less than or equal to "
},
{
"code": null,
"e": 32318,
"s": 32299,
"text": "Also β ∈ (V + T)+"
},
{
"code": null,
"e": 32352,
"s": 32318,
"text": "i.e. β can not be ε For Example:"
},
{
"code": null,
"e": 32383,
"s": 32352,
"text": "S --> AB\nAB --> abc \nB --> b "
},
{
"code": null,
"e": 32550,
"s": 32383,
"text": "Type 2: Context-Free Grammar: Type-2 grammars generate context-free languages. The language generated by the grammar is recognized by a Pushdown automata. In Type 2:"
},
{
"code": null,
"e": 32586,
"s": 32550,
"text": "First of all, it should be Type 1. "
},
{
"code": null,
"e": 32678,
"s": 32586,
"text": "The left-hand side of production can have only one variable and there is no restriction on "
},
{
"code": null,
"e": 32703,
"s": 32678,
"text": "|\\alpha | = 1. "
},
{
"code": null,
"e": 32716,
"s": 32703,
"text": "For example:"
},
{
"code": null,
"e": 32744,
"s": 32716,
"text": "S --> AB \nA --> a \nB --> b "
},
{
"code": null,
"e": 32953,
"s": 32744,
"text": "Type 3: Regular Grammar: Type-3 grammars generate regular languages. These languages are exactly all languages that can be accepted by a finite-state automaton. Type 3 is the most restricted form of grammar. "
},
{
"code": null,
"e": 32996,
"s": 32953,
"text": "Type 3 should be in the given form only : "
},
{
"code": null,
"e": 33091,
"s": 32996,
"text": "V --> VT / T (left-regular grammar)\n(or)\nV --> TV /T (right-regular grammar)"
},
{
"code": null,
"e": 33104,
"s": 33091,
"text": "For example:"
},
{
"code": null,
"e": 33112,
"s": 33104,
"text": "S --> a"
},
{
"code": null,
"e": 33163,
"s": 33112,
"text": "The above form is called strictly regular grammar."
},
{
"code": null,
"e": 33251,
"s": 33163,
"text": "There is another form of regular grammar called extended regular grammar. In this form:"
},
{
"code": null,
"e": 33368,
"s": 33251,
"text": "V --> VT* / T*. (extended left-regular grammar)\n(or) \nV --> T*V /T* (extended right-regular grammar)"
},
{
"code": null,
"e": 33383,
"s": 33368,
"text": "For example : "
},
{
"code": null,
"e": 33394,
"s": 33383,
"text": "S --> ab. "
},
{
"code": null,
"e": 33522,
"s": 33394,
"text": "Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 33534,
"s": 33522,
"text": "VaibhavRai3"
},
{
"code": null,
"e": 33548,
"s": 33534,
"text": "chaitalykundu"
},
{
"code": null,
"e": 33561,
"s": 33548,
"text": "sandravsnair"
},
{
"code": null,
"e": 33570,
"s": 33561,
"text": "umeshg17"
},
{
"code": null,
"e": 33587,
"s": 33570,
"text": "niharikatanwar61"
},
{
"code": null,
"e": 33603,
"s": 33587,
"text": "bumblebeecoding"
},
{
"code": null,
"e": 33636,
"s": 33603,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 33734,
"s": 33636,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33765,
"s": 33734,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 33793,
"s": 33765,
"text": "Regular expression to ∈-NFA"
},
{
"code": null,
"e": 33848,
"s": 33793,
"text": "NPDA for accepting the language L = {wwR | w ∈ (a,b)*}"
},
{
"code": null,
"e": 33893,
"s": 33848,
"text": "Design 101 sequence detector (Mealy machine)"
},
{
"code": null,
"e": 33933,
"s": 33893,
"text": "Closure properties of Regular languages"
},
{
"code": null,
"e": 33966,
"s": 33933,
"text": "Conversion of Epsilon-NFA to NFA"
},
{
"code": null,
"e": 34023,
"s": 33966,
"text": "Difference between Pushdown Automata and Finite Automata"
},
{
"code": null,
"e": 34065,
"s": 34023,
"text": "Last Minute Notes - Theory of Computation"
},
{
"code": null,
"e": 34093,
"s": 34065,
"text": "Variation of Turing Machine"
}
] |
Set the width of an element to 100% in Bootstrap
|
To set the width of an element to 100%, use the .w-100 class in Bootstrap.
You can try to run the following code to set element’s width
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "container">
<h3>Set element width</h3>
<div class = "w-100 bg-success">Normal width</div>
<div class = "w-50 bg-danger">Width is 25%</div>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1137,
"s": 1062,
"text": "To set the width of an element to 100%, use the .w-100 class in Bootstrap."
},
{
"code": null,
"e": 1198,
"s": 1137,
"text": "You can try to run the following code to set element’s width"
},
{
"code": null,
"e": 1208,
"s": 1198,
"text": "Live Demo"
},
{
"code": null,
"e": 1827,
"s": 1208,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link rel = \"stylesheet\" href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container\">\n <h3>Set element width</h3>\n <div class = \"w-100 bg-success\">Normal width</div>\n <div class = \"w-50 bg-danger\">Width is 25%</div>\n </div>\n </body>\n</html>"
}
] |
Program to count number of points that lie on a line in Python
|
Suppose we have a list of coordinates. Each coordinate has two values x and y, representing a point on the Cartesian plane. Now find the maximum number of points that lie on some line.
So, if the input is like coordinates = [[6, 2],[8, 3],[10, 4],[1, 1],[2, 2],[6, 6],[7, 7]], then the output will be 4, as the points are [1, 1], [2, 2], [6, 6], [7, 7]] that lies on a line.
To solve this, we will follow these steps −
res := 0
res := 0
for i in range 0 to size of points list, do(x1, y1) := points[i]slopes := a new mapsame := 1for j in range i + 1 to size of points, do(x2, y2) := points[j]if x2 is same as x1, thenslopes[inf] := 1 + (slopes[inf] if exits otherwise 0)otherwise when x1 is same as x2 and y1 is same as y2, thensame := same + 1otherwise,slope :=(y2 - y1) /(x2 - x1)slopes[slope] := 1 + (slopes[slope] if exits otherwise 0)if slopes is not empty, thenres := maximum of res and (same + maximum of list of all values of slopes)
for i in range 0 to size of points list, do
(x1, y1) := points[i]
(x1, y1) := points[i]
slopes := a new map
slopes := a new map
same := 1
same := 1
for j in range i + 1 to size of points, do(x2, y2) := points[j]if x2 is same as x1, thenslopes[inf] := 1 + (slopes[inf] if exits otherwise 0)otherwise when x1 is same as x2 and y1 is same as y2, thensame := same + 1otherwise,slope :=(y2 - y1) /(x2 - x1)slopes[slope] := 1 + (slopes[slope] if exits otherwise 0)
for j in range i + 1 to size of points, do
(x2, y2) := points[j]
(x2, y2) := points[j]
if x2 is same as x1, thenslopes[inf] := 1 + (slopes[inf] if exits otherwise 0)
if x2 is same as x1, then
slopes[inf] := 1 + (slopes[inf] if exits otherwise 0)
slopes[inf] := 1 + (slopes[inf] if exits otherwise 0)
otherwise when x1 is same as x2 and y1 is same as y2, thensame := same + 1
otherwise when x1 is same as x2 and y1 is same as y2, then
same := same + 1
same := same + 1
otherwise,slope :=(y2 - y1) /(x2 - x1)slopes[slope] := 1 + (slopes[slope] if exits otherwise 0)
otherwise,
slope :=(y2 - y1) /(x2 - x1)
slope :=(y2 - y1) /(x2 - x1)
slopes[slope] := 1 + (slopes[slope] if exits otherwise 0)
slopes[slope] := 1 + (slopes[slope] if exits otherwise 0)
if slopes is not empty, thenres := maximum of res and (same + maximum of list of all values of slopes)
if slopes is not empty, then
res := maximum of res and (same + maximum of list of all values of slopes)
res := maximum of res and (same + maximum of list of all values of slopes)
return res
return res
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, points):
res = 0
for i in range(len(points)):
x1, y1 = points[i][0], points[i][1]
slopes = {}
same = 1
for j in range(i + 1, len(points)):
x2, y2 = points[j][0], points[j][1]
if x2 == x1:
slopes[float("inf")] = slopes.get(float("inf"), 0) + 1
elif x1 == x2 and y1 == y2:
same += 1
else:
slope = (y2 - y1) / (x2 - x1)
slopes[slope] = slopes.get(slope, 0) + 1
if slopes:
res = max(res, same + max(slopes.values()))
return res
ob = Solution()
coordinates = [[6, 2],[8, 3],[10, 4],[1, 1],[2, 2],[6, 6],[7, 7]]
print(ob.solve(coordinates))
[[6, 2],[8, 3],[10, 4],[1, 1],[2, 2],[6, 6],[7, 7]]
4
|
[
{
"code": null,
"e": 1247,
"s": 1062,
"text": "Suppose we have a list of coordinates. Each coordinate has two values x and y, representing a point on the Cartesian plane. Now find the maximum number of points that lie on some line."
},
{
"code": null,
"e": 1437,
"s": 1247,
"text": "So, if the input is like coordinates = [[6, 2],[8, 3],[10, 4],[1, 1],[2, 2],[6, 6],[7, 7]], then the output will be 4, as the points are [1, 1], [2, 2], [6, 6], [7, 7]] that lies on a line."
},
{
"code": null,
"e": 1481,
"s": 1437,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1490,
"s": 1481,
"text": "res := 0"
},
{
"code": null,
"e": 1499,
"s": 1490,
"text": "res := 0"
},
{
"code": null,
"e": 2004,
"s": 1499,
"text": "for i in range 0 to size of points list, do(x1, y1) := points[i]slopes := a new mapsame := 1for j in range i + 1 to size of points, do(x2, y2) := points[j]if x2 is same as x1, thenslopes[inf] := 1 + (slopes[inf] if exits otherwise 0)otherwise when x1 is same as x2 and y1 is same as y2, thensame := same + 1otherwise,slope :=(y2 - y1) /(x2 - x1)slopes[slope] := 1 + (slopes[slope] if exits otherwise 0)if slopes is not empty, thenres := maximum of res and (same + maximum of list of all values of slopes)"
},
{
"code": null,
"e": 2048,
"s": 2004,
"text": "for i in range 0 to size of points list, do"
},
{
"code": null,
"e": 2070,
"s": 2048,
"text": "(x1, y1) := points[i]"
},
{
"code": null,
"e": 2092,
"s": 2070,
"text": "(x1, y1) := points[i]"
},
{
"code": null,
"e": 2112,
"s": 2092,
"text": "slopes := a new map"
},
{
"code": null,
"e": 2132,
"s": 2112,
"text": "slopes := a new map"
},
{
"code": null,
"e": 2142,
"s": 2132,
"text": "same := 1"
},
{
"code": null,
"e": 2152,
"s": 2142,
"text": "same := 1"
},
{
"code": null,
"e": 2463,
"s": 2152,
"text": "for j in range i + 1 to size of points, do(x2, y2) := points[j]if x2 is same as x1, thenslopes[inf] := 1 + (slopes[inf] if exits otherwise 0)otherwise when x1 is same as x2 and y1 is same as y2, thensame := same + 1otherwise,slope :=(y2 - y1) /(x2 - x1)slopes[slope] := 1 + (slopes[slope] if exits otherwise 0)"
},
{
"code": null,
"e": 2506,
"s": 2463,
"text": "for j in range i + 1 to size of points, do"
},
{
"code": null,
"e": 2528,
"s": 2506,
"text": "(x2, y2) := points[j]"
},
{
"code": null,
"e": 2550,
"s": 2528,
"text": "(x2, y2) := points[j]"
},
{
"code": null,
"e": 2629,
"s": 2550,
"text": "if x2 is same as x1, thenslopes[inf] := 1 + (slopes[inf] if exits otherwise 0)"
},
{
"code": null,
"e": 2655,
"s": 2629,
"text": "if x2 is same as x1, then"
},
{
"code": null,
"e": 2709,
"s": 2655,
"text": "slopes[inf] := 1 + (slopes[inf] if exits otherwise 0)"
},
{
"code": null,
"e": 2763,
"s": 2709,
"text": "slopes[inf] := 1 + (slopes[inf] if exits otherwise 0)"
},
{
"code": null,
"e": 2838,
"s": 2763,
"text": "otherwise when x1 is same as x2 and y1 is same as y2, thensame := same + 1"
},
{
"code": null,
"e": 2897,
"s": 2838,
"text": "otherwise when x1 is same as x2 and y1 is same as y2, then"
},
{
"code": null,
"e": 2914,
"s": 2897,
"text": "same := same + 1"
},
{
"code": null,
"e": 2931,
"s": 2914,
"text": "same := same + 1"
},
{
"code": null,
"e": 3027,
"s": 2931,
"text": "otherwise,slope :=(y2 - y1) /(x2 - x1)slopes[slope] := 1 + (slopes[slope] if exits otherwise 0)"
},
{
"code": null,
"e": 3038,
"s": 3027,
"text": "otherwise,"
},
{
"code": null,
"e": 3067,
"s": 3038,
"text": "slope :=(y2 - y1) /(x2 - x1)"
},
{
"code": null,
"e": 3096,
"s": 3067,
"text": "slope :=(y2 - y1) /(x2 - x1)"
},
{
"code": null,
"e": 3154,
"s": 3096,
"text": "slopes[slope] := 1 + (slopes[slope] if exits otherwise 0)"
},
{
"code": null,
"e": 3212,
"s": 3154,
"text": "slopes[slope] := 1 + (slopes[slope] if exits otherwise 0)"
},
{
"code": null,
"e": 3315,
"s": 3212,
"text": "if slopes is not empty, thenres := maximum of res and (same + maximum of list of all values of slopes)"
},
{
"code": null,
"e": 3344,
"s": 3315,
"text": "if slopes is not empty, then"
},
{
"code": null,
"e": 3419,
"s": 3344,
"text": "res := maximum of res and (same + maximum of list of all values of slopes)"
},
{
"code": null,
"e": 3494,
"s": 3419,
"text": "res := maximum of res and (same + maximum of list of all values of slopes)"
},
{
"code": null,
"e": 3505,
"s": 3494,
"text": "return res"
},
{
"code": null,
"e": 3516,
"s": 3505,
"text": "return res"
},
{
"code": null,
"e": 3586,
"s": 3516,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3597,
"s": 3586,
"text": " Live Demo"
},
{
"code": null,
"e": 4350,
"s": 3597,
"text": "class Solution:\n def solve(self, points):\n res = 0\n for i in range(len(points)):\n x1, y1 = points[i][0], points[i][1]\n slopes = {}\n same = 1\n for j in range(i + 1, len(points)):\n x2, y2 = points[j][0], points[j][1]\n if x2 == x1:\n slopes[float(\"inf\")] = slopes.get(float(\"inf\"), 0) + 1\n elif x1 == x2 and y1 == y2:\n same += 1\n else:\n slope = (y2 - y1) / (x2 - x1)\n slopes[slope] = slopes.get(slope, 0) + 1\n if slopes:\n res = max(res, same + max(slopes.values()))\n return res\nob = Solution()\ncoordinates = [[6, 2],[8, 3],[10, 4],[1, 1],[2, 2],[6, 6],[7, 7]]\nprint(ob.solve(coordinates))"
},
{
"code": null,
"e": 4402,
"s": 4350,
"text": "[[6, 2],[8, 3],[10, 4],[1, 1],[2, 2],[6, 6],[7, 7]]"
},
{
"code": null,
"e": 4404,
"s": 4402,
"text": "4"
}
] |
Python Web Scraping - Data Processing
|
In earlier chapters, we learned about extracting the data from web pages or web scraping by various Python modules. In this chapter, let us look into various techniques to process the data that has been scraped.
To process the data that has been scraped, we must store the data on our local machine in a particular format like spreadsheet (CSV), JSON or sometimes in databases like MySQL.
First, we are going to write the information, after grabbing from web page, into a CSV file or a spreadsheet. Let us first understand through a simple example in which we will first grab the information using BeautifulSoup module, as did earlier, and then by using Python CSV module we will write that textual information into CSV file.
First, we need to import the necessary Python libraries as follows −
import requests
from bs4 import BeautifulSoup
import csv
In this following line of code, we use requests to make a GET HTTP requests for the url:
https://authoraditiagarwal.com/ by making a GET request.
r = requests.get('https://authoraditiagarwal.com/')
Now, we need to create a Soup object as follows −
soup = BeautifulSoup(r.text, 'lxml')
Now, with the help of next lines of code, we will write the grabbed data into a CSV file named dataprocessing.csv.
f = csv.writer(open(' dataprocessing.csv ','w'))
f.writerow(['Title'])
f.writerow([soup.title.text])
After running this script, the textual information or the title of the webpage will be saved in the above mentioned CSV file on your local machine.
Similarly, we can save the collected information in a JSON file. The following is an easy to understand Python script for doing the same in which we are grabbing the same information as we did in last Python script, but this time the grabbed information is saved in JSONfile.txt by using JSON Python module.
import requests
from bs4 import BeautifulSoup
import csv
import json
r = requests.get('https://authoraditiagarwal.com/')
soup = BeautifulSoup(r.text, 'lxml')
y = json.dumps(soup.title.text)
with open('JSONFile.txt', 'wt') as outfile:
json.dump(y, outfile)
After running this script, the grabbed information i.e. title of the webpage will be saved in the above mentioned text file on your local machine.
Sometimes we may want to save scraped data in our local storage for archive purpose. But what if the we need to store and analyze this data at a massive scale? The answer is cloud storage service named Amazon S3 or AWS S3 (Simple Storage Service). Basically AWS S3 is an object storage which is built to store and retrieve any amount of data from anywhere.
We can follow the following steps for storing data in AWS S3 −
Step 1 − First we need an AWS account which will provide us the secret keys for using in our Python script while storing the data. It will create a S3 bucket in which we can store our data.
Step 2 − Next, we need to install boto3 Python library for accessing S3 bucket. It can be
installed with the help of the following command −
pip install boto3
Step 3 − Next, we can use the following Python script for scraping data from web page and saving it to AWS S3 bucket.
First, we need to import Python libraries for scraping, here we are working with requests, and boto3 saving data to S3 bucket.
import requests
import boto3
Now we can scrape the data from our URL.
data = requests.get("Enter the URL").text
Now for storing data to S3 bucket, we need to create S3 client as follows −
s3 = boto3.client('s3')
bucket_name = "our-content"
Next line of code will create S3 bucket as follows −
s3.create_bucket(Bucket = bucket_name, ACL = 'public-read')
s3.put_object(Bucket = bucket_name, Key = '', Body = data, ACL = "public-read")
Now you can check the bucket with name our-content from your AWS account.
Let us learn how to process data using MySQL. If you want to learn about MySQL, then you can follow the link https://www.tutorialspoint.com/mysql/.
With the help of following steps, we can scrape and process data into MySQL table −
Step 1 − First, by using MySQL we need to create a database and table in which we want to save our scraped data. For example, we are creating the table with following query −
CREATE TABLE Scrap_pages (id BIGINT(7) NOT NULL AUTO_INCREMENT,
title VARCHAR(200), content VARCHAR(10000),PRIMARY KEY(id));
Step 2 − Next, we need to deal with Unicode. Note that MySQL does not handle Unicode by default. We need to turn on this feature with the help of following commands which will change the default character set for the database, for the table and for both of the columns −
ALTER DATABASE scrap CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
ALTER TABLE Scrap_pages CONVERT TO CHARACTER SET utf8mb4 COLLATE
utf8mb4_unicode_ci;
ALTER TABLE Scrap_pages CHANGE title title VARCHAR(200) CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
ALTER TABLE pages CHANGE content content VARCHAR(10000) CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
Step 3 − Now, integrate MySQL with Python. For this, we will need PyMySQL which can be installed with the help of the following command
pip install PyMySQL
Step 4 − Now, our database named Scrap, created earlier, is ready to save the data, after scraped from web, into table named Scrap_pages. Here in our example we are going to scrape data from Wikipedia and it will be saved into our database.
First, we need to import the required Python modules.
from urllib.request import urlopen
from bs4 import BeautifulSoup
import datetime
import random
import pymysql
import re
Now, make a connection, that is integrate this with Python.
conn = pymysql.connect(host='127.0.0.1',user='root', passwd = None, db = 'mysql',
charset = 'utf8')
cur = conn.cursor()
cur.execute("USE scrap")
random.seed(datetime.datetime.now())
def store(title, content):
cur.execute('INSERT INTO scrap_pages (title, content) VALUES ''("%s","%s")', (title, content))
cur.connection.commit()
Now, connect with Wikipedia and get data from it.
def getLinks(articleUrl):
html = urlopen('http://en.wikipedia.org'+articleUrl)
bs = BeautifulSoup(html, 'html.parser')
title = bs.find('h1').get_text()
content = bs.find('div', {'id':'mw-content-text'}).find('p').get_text()
store(title, content)
return bs.find('div', {'id':'bodyContent'}).findAll('a',href=re.compile('^(/wiki/)((?!:).)*$'))
links = getLinks('/wiki/Kevin_Bacon')
try:
while len(links) > 0:
newArticle = links[random.randint(0, len(links)-1)].attrs['href']
print(newArticle)
links = getLinks(newArticle)
Lastly, we need to close both cursor and connection.
finally:
cur.close()
conn.close()
This will save the data gather from Wikipedia into table named scrap_pages. If you are familiar with MySQL and web scraping, then the above code would not be tough to understand.
PostgreSQL, developed by a worldwide team of volunteers, is an open source relational database Management system (RDMS). The process of processing the scraped data using PostgreSQL is similar to that of MySQL. There would be two changes: First, the commands would be different to MySQL and second, here we will use psycopg2 Python library to perform its integration with Python.
If you are not familiar with PostgreSQL then you can learn it at
https://www.tutorialspoint.com/postgresql/. And with the help of following command we can install psycopg2 Python library −
pip install psycopg2
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2124,
"s": 1912,
"text": "In earlier chapters, we learned about extracting the data from web pages or web scraping by various Python modules. In this chapter, let us look into various techniques to process the data that has been scraped."
},
{
"code": null,
"e": 2301,
"s": 2124,
"text": "To process the data that has been scraped, we must store the data on our local machine in a particular format like spreadsheet (CSV), JSON or sometimes in databases like MySQL."
},
{
"code": null,
"e": 2638,
"s": 2301,
"text": "First, we are going to write the information, after grabbing from web page, into a CSV file or a spreadsheet. Let us first understand through a simple example in which we will first grab the information using BeautifulSoup module, as did earlier, and then by using Python CSV module we will write that textual information into CSV file."
},
{
"code": null,
"e": 2707,
"s": 2638,
"text": "First, we need to import the necessary Python libraries as follows −"
},
{
"code": null,
"e": 2765,
"s": 2707,
"text": "import requests\nfrom bs4 import BeautifulSoup\nimport csv\n"
},
{
"code": null,
"e": 2911,
"s": 2765,
"text": "In this following line of code, we use requests to make a GET HTTP requests for the url:\nhttps://authoraditiagarwal.com/ by making a GET request."
},
{
"code": null,
"e": 2964,
"s": 2911,
"text": "r = requests.get('https://authoraditiagarwal.com/')\n"
},
{
"code": null,
"e": 3014,
"s": 2964,
"text": "Now, we need to create a Soup object as follows −"
},
{
"code": null,
"e": 3052,
"s": 3014,
"text": "soup = BeautifulSoup(r.text, 'lxml')\n"
},
{
"code": null,
"e": 3167,
"s": 3052,
"text": "Now, with the help of next lines of code, we will write the grabbed data into a CSV file named dataprocessing.csv."
},
{
"code": null,
"e": 3269,
"s": 3167,
"text": "f = csv.writer(open(' dataprocessing.csv ','w'))\nf.writerow(['Title'])\nf.writerow([soup.title.text])\n"
},
{
"code": null,
"e": 3417,
"s": 3269,
"text": "After running this script, the textual information or the title of the webpage will be saved in the above mentioned CSV file on your local machine."
},
{
"code": null,
"e": 3725,
"s": 3417,
"text": "Similarly, we can save the collected information in a JSON file. The following is an easy to understand Python script for doing the same in which we are grabbing the same information as we did in last Python script, but this time the grabbed information is saved in JSONfile.txt by using JSON Python module."
},
{
"code": null,
"e": 3985,
"s": 3725,
"text": "import requests\nfrom bs4 import BeautifulSoup\nimport csv\nimport json\nr = requests.get('https://authoraditiagarwal.com/')\nsoup = BeautifulSoup(r.text, 'lxml')\ny = json.dumps(soup.title.text)\nwith open('JSONFile.txt', 'wt') as outfile:\n json.dump(y, outfile)\n"
},
{
"code": null,
"e": 4132,
"s": 3985,
"text": "After running this script, the grabbed information i.e. title of the webpage will be saved in the above mentioned text file on your local machine."
},
{
"code": null,
"e": 4489,
"s": 4132,
"text": "Sometimes we may want to save scraped data in our local storage for archive purpose. But what if the we need to store and analyze this data at a massive scale? The answer is cloud storage service named Amazon S3 or AWS S3 (Simple Storage Service). Basically AWS S3 is an object storage which is built to store and retrieve any amount of data from anywhere."
},
{
"code": null,
"e": 4552,
"s": 4489,
"text": "We can follow the following steps for storing data in AWS S3 −"
},
{
"code": null,
"e": 4742,
"s": 4552,
"text": "Step 1 − First we need an AWS account which will provide us the secret keys for using in our Python script while storing the data. It will create a S3 bucket in which we can store our data."
},
{
"code": null,
"e": 4883,
"s": 4742,
"text": "Step 2 − Next, we need to install boto3 Python library for accessing S3 bucket. It can be\ninstalled with the help of the following command −"
},
{
"code": null,
"e": 4902,
"s": 4883,
"text": "pip install boto3\n"
},
{
"code": null,
"e": 5020,
"s": 4902,
"text": "Step 3 − Next, we can use the following Python script for scraping data from web page and saving it to AWS S3 bucket."
},
{
"code": null,
"e": 5147,
"s": 5020,
"text": "First, we need to import Python libraries for scraping, here we are working with requests, and boto3 saving data to S3 bucket."
},
{
"code": null,
"e": 5177,
"s": 5147,
"text": "import requests\nimport boto3\n"
},
{
"code": null,
"e": 5218,
"s": 5177,
"text": "Now we can scrape the data from our URL."
},
{
"code": null,
"e": 5261,
"s": 5218,
"text": "data = requests.get(\"Enter the URL\").text\n"
},
{
"code": null,
"e": 5337,
"s": 5261,
"text": "Now for storing data to S3 bucket, we need to create S3 client as follows −"
},
{
"code": null,
"e": 5390,
"s": 5337,
"text": "s3 = boto3.client('s3')\nbucket_name = \"our-content\"\n"
},
{
"code": null,
"e": 5443,
"s": 5390,
"text": "Next line of code will create S3 bucket as follows −"
},
{
"code": null,
"e": 5584,
"s": 5443,
"text": "s3.create_bucket(Bucket = bucket_name, ACL = 'public-read')\ns3.put_object(Bucket = bucket_name, Key = '', Body = data, ACL = \"public-read\")\n"
},
{
"code": null,
"e": 5658,
"s": 5584,
"text": "Now you can check the bucket with name our-content from your AWS account."
},
{
"code": null,
"e": 5806,
"s": 5658,
"text": "Let us learn how to process data using MySQL. If you want to learn about MySQL, then you can follow the link https://www.tutorialspoint.com/mysql/."
},
{
"code": null,
"e": 5890,
"s": 5806,
"text": "With the help of following steps, we can scrape and process data into MySQL table −"
},
{
"code": null,
"e": 6065,
"s": 5890,
"text": "Step 1 − First, by using MySQL we need to create a database and table in which we want to save our scraped data. For example, we are creating the table with following query −"
},
{
"code": null,
"e": 6191,
"s": 6065,
"text": "CREATE TABLE Scrap_pages (id BIGINT(7) NOT NULL AUTO_INCREMENT,\ntitle VARCHAR(200), content VARCHAR(10000),PRIMARY KEY(id));\n"
},
{
"code": null,
"e": 6462,
"s": 6191,
"text": "Step 2 − Next, we need to deal with Unicode. Note that MySQL does not handle Unicode by default. We need to turn on this feature with the help of following commands which will change the default character set for the database, for the table and for both of the columns −"
},
{
"code": null,
"e": 6835,
"s": 6462,
"text": "ALTER DATABASE scrap CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;\nALTER TABLE Scrap_pages CONVERT TO CHARACTER SET utf8mb4 COLLATE\nutf8mb4_unicode_ci;\nALTER TABLE Scrap_pages CHANGE title title VARCHAR(200) CHARACTER SET utf8mb4\nCOLLATE utf8mb4_unicode_ci;\nALTER TABLE pages CHANGE content content VARCHAR(10000) CHARACTER SET utf8mb4\nCOLLATE utf8mb4_unicode_ci;\n"
},
{
"code": null,
"e": 6971,
"s": 6835,
"text": "Step 3 − Now, integrate MySQL with Python. For this, we will need PyMySQL which can be installed with the help of the following command"
},
{
"code": null,
"e": 6993,
"s": 6971,
"text": "pip install PyMySQL \n"
},
{
"code": null,
"e": 7234,
"s": 6993,
"text": "Step 4 − Now, our database named Scrap, created earlier, is ready to save the data, after scraped from web, into table named Scrap_pages. Here in our example we are going to scrape data from Wikipedia and it will be saved into our database."
},
{
"code": null,
"e": 7288,
"s": 7234,
"text": "First, we need to import the required Python modules."
},
{
"code": null,
"e": 7409,
"s": 7288,
"text": "from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport datetime\nimport random\nimport pymysql\nimport re\n"
},
{
"code": null,
"e": 7469,
"s": 7409,
"text": "Now, make a connection, that is integrate this with Python."
},
{
"code": null,
"e": 7804,
"s": 7469,
"text": "conn = pymysql.connect(host='127.0.0.1',user='root', passwd = None, db = 'mysql',\ncharset = 'utf8')\ncur = conn.cursor()\ncur.execute(\"USE scrap\")\nrandom.seed(datetime.datetime.now())\ndef store(title, content):\n cur.execute('INSERT INTO scrap_pages (title, content) VALUES ''(\"%s\",\"%s\")', (title, content))\n cur.connection.commit()\n"
},
{
"code": null,
"e": 7854,
"s": 7804,
"text": "Now, connect with Wikipedia and get data from it."
},
{
"code": null,
"e": 8414,
"s": 7854,
"text": "def getLinks(articleUrl):\n html = urlopen('http://en.wikipedia.org'+articleUrl)\n bs = BeautifulSoup(html, 'html.parser')\n title = bs.find('h1').get_text()\n content = bs.find('div', {'id':'mw-content-text'}).find('p').get_text()\n store(title, content)\n return bs.find('div', {'id':'bodyContent'}).findAll('a',href=re.compile('^(/wiki/)((?!:).)*$'))\nlinks = getLinks('/wiki/Kevin_Bacon')\ntry:\n while len(links) > 0:\n newArticle = links[random.randint(0, len(links)-1)].attrs['href']\n print(newArticle)\n links = getLinks(newArticle)\n"
},
{
"code": null,
"e": 8467,
"s": 8414,
"text": "Lastly, we need to close both cursor and connection."
},
{
"code": null,
"e": 8508,
"s": 8467,
"text": "finally:\n cur.close()\n conn.close()\n"
},
{
"code": null,
"e": 8687,
"s": 8508,
"text": "This will save the data gather from Wikipedia into table named scrap_pages. If you are familiar with MySQL and web scraping, then the above code would not be tough to understand."
},
{
"code": null,
"e": 9066,
"s": 8687,
"text": "PostgreSQL, developed by a worldwide team of volunteers, is an open source relational database Management system (RDMS). The process of processing the scraped data using PostgreSQL is similar to that of MySQL. There would be two changes: First, the commands would be different to MySQL and second, here we will use psycopg2 Python library to perform its integration with Python."
},
{
"code": null,
"e": 9255,
"s": 9066,
"text": "If you are not familiar with PostgreSQL then you can learn it at\nhttps://www.tutorialspoint.com/postgresql/. And with the help of following command we can install psycopg2 Python library −"
},
{
"code": null,
"e": 9278,
"s": 9255,
"text": "pip install psycopg2 \n"
},
{
"code": null,
"e": 9315,
"s": 9278,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 9331,
"s": 9315,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 9364,
"s": 9331,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 9383,
"s": 9364,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 9418,
"s": 9383,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 9440,
"s": 9418,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 9474,
"s": 9440,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 9502,
"s": 9474,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 9537,
"s": 9502,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 9551,
"s": 9537,
"text": " Lets Kode It"
},
{
"code": null,
"e": 9584,
"s": 9551,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 9601,
"s": 9584,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9608,
"s": 9601,
"text": " Print"
},
{
"code": null,
"e": 9619,
"s": 9608,
"text": " Add Notes"
}
] |
JasmineJS - Inequality Check
|
Till now, we have discussed different methods in Jasmine which help us test different scenarios based on our requirements. In this chapter, we will learn about different matchers that will help us check the inequality condition in JS file. Following are the matchers used for this purpose.
As the name suggests this matcher helps to check greater than condition. Let us modify our customerMatcher.js using the following piece of code.
describe("Different Methods of Expect Block",function () {
var exp = 8;
it("Example of toBeGreaterThan()", function () {
expect(exp).toBeGreaterThan(5);
});
});
In the above piece of code, we are expecting that the value of the variable “exp” will be greater than 5. Now as the value of the variable “exp” is “8” which is greater than “5”, this piece of code will generate a green screenshot.
Now again let us modify the value of the variable to “4” and make this test fail. To do that we need to modify the js file using the following piece of code.
describe("Different Methods of Expect Block",function () {
var exp = 4;
it ("Example of toBeGreaterThan()", function () {
expect(exp).toBeGreaterThan(5);
});
});
This code will fail because value 4 cannot be greater than 5. Hence it will produce the following output.
This matcher helps to check the less than condition of the test scenario. It behaves exactly opposite to that of toBeGreaterThan() matcher. Now let us see how this matcher works. Let us modify the customerMatcher.js file accordingly.
describe("Different Methodsof Expect Block",function () {
var exp = 4;
it("Example of toBeLessThan()", function() {
expect(exp).toBeLessThan(5);
});
});
Like the previous example, we have one variable having value as “4”. In this piece of code, we are checking whether the value of this variable is less than 5 or not. This piece of code will generate the following output.
Now to make this fail, we need to assign some bigger number to the variable exp. Let us do that and test the application. We will assign 25 as the value to the exp, which will definitely throw an error and yield the following screenshot in red.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2340,
"s": 2050,
"text": "Till now, we have discussed different methods in Jasmine which help us test different scenarios based on our requirements. In this chapter, we will learn about different matchers that will help us check the inequality condition in JS file. Following are the matchers used for this purpose."
},
{
"code": null,
"e": 2485,
"s": 2340,
"text": "As the name suggests this matcher helps to check greater than condition. Let us modify our customerMatcher.js using the following piece of code."
},
{
"code": null,
"e": 2668,
"s": 2485,
"text": "describe(\"Different Methods of Expect Block\",function () { \n var exp = 8; \n\t\n it(\"Example of toBeGreaterThan()\", function () {\n expect(exp).toBeGreaterThan(5);\n });\n}); "
},
{
"code": null,
"e": 2900,
"s": 2668,
"text": "In the above piece of code, we are expecting that the value of the variable “exp” will be greater than 5. Now as the value of the variable “exp” is “8” which is greater than “5”, this piece of code will generate a green screenshot."
},
{
"code": null,
"e": 3058,
"s": 2900,
"text": "Now again let us modify the value of the variable to “4” and make this test fail. To do that we need to modify the js file using the following piece of code."
},
{
"code": null,
"e": 3242,
"s": 3058,
"text": "describe(\"Different Methods of Expect Block\",function () { \n var exp = 4; \n\t\n it (\"Example of toBeGreaterThan()\", function () {\n expect(exp).toBeGreaterThan(5); \n });\n});"
},
{
"code": null,
"e": 3348,
"s": 3242,
"text": "This code will fail because value 4 cannot be greater than 5. Hence it will produce the following output."
},
{
"code": null,
"e": 3582,
"s": 3348,
"text": "This matcher helps to check the less than condition of the test scenario. It behaves exactly opposite to that of toBeGreaterThan() matcher. Now let us see how this matcher works. Let us modify the customerMatcher.js file accordingly."
},
{
"code": null,
"e": 3761,
"s": 3582,
"text": "describe(\"Different Methodsof Expect Block\",function () { \n var exp = 4; \n\t\n it(\"Example of toBeLessThan()\", function() { \n expect(exp).toBeLessThan(5); \n });\n}); "
},
{
"code": null,
"e": 3982,
"s": 3761,
"text": "Like the previous example, we have one variable having value as “4”. In this piece of code, we are checking whether the value of this variable is less than 5 or not. This piece of code will generate the following output."
},
{
"code": null,
"e": 4227,
"s": 3982,
"text": "Now to make this fail, we need to assign some bigger number to the variable exp. Let us do that and test the application. We will assign 25 as the value to the exp, which will definitely throw an error and yield the following screenshot in red."
},
{
"code": null,
"e": 4234,
"s": 4227,
"text": " Print"
},
{
"code": null,
"e": 4245,
"s": 4234,
"text": " Add Notes"
}
] |
I created a Deep Learning powered Discord Bot to react with smily 😎 | by Anurag Bhattacharjee | Towards Data Science
|
I have been reading a lot of paper articles lately, mostly on Deep Learning, RNN, CNN, LSTM[1], Transformer(Attention is all you need)[3], BERT etc. The list is only growing. But the best way to learn anything is to experience it. And also if I deploy a bot with my face, in my office server it can give proxy for me sometimes when I am busy reading. 😜 Just Kidding. As an experienced software developer its just an urge to implement the new knowledge acquired.
But there are some big hindrances. Where will I get so much data to train a Neural Net? Even if I manage data, I will need a machine with hi-fi configuration or at-least with a powerful GPU to train my model with the data. But, if there is a will there is way. 🤓 After a bit of research I found, DeepMoji 🧙🏻♂️. We can use pre trained models like DeepMoji to implement our bot. It’s a common practice now a days to work on a pre-trained model and make it better according to the need.
This is a perfect opportunity for me to make a BOT in discord(as my office communication is held in discord) and experience how a NLP process works using a varient of LSTM and attention mechanism. This BOT can listen to all the messages being received and react with emoticons.
DeepMoji is a model built on Keras and the backend on Tensorflow. Deepmoji is based on this paper[2] developped by Bjarke Felbo, Alan Mislove, Anders Søgaard, Iyad Rahwan and Sune Lehmann.
This paper shows that by extending the distant supervision to a more diverse set of noisy labels, the models can learn richer representations. Through emoji prediction on a dataset of 1.2 billion tweets containing one of 64 common emojis they have obtained state-of-the-art performance on 8 benchmark datasets within sentiment, emotion and sarcasm detection using a single pretrained model.
TorchMoji is a pyTorch implementation of the DeepMoji model built by huggingface. DeepMoji is built on python 2.7. So we will use TochMoji which is a implementation in python3. So we will use torchmoji for our implementation.
The most hectic part for me in this journey was the setup. Because I couldn’t find any proper example to implement torchMoji in a project. All the examples are the test cases used in jupyter notebook. But I am particularly interested in implementing it inside a project using my VS Code so that I can connect it with my discord BOT and send a response from there.
You can see my full code here: https://github.com/anuragbhattacharjee/discord-nlp-smily-bot/
*** Giving ⭐️ Star on github repositories helps us both grow. You will get all the updates of the project and I will get the inspiration to update the project.
So Let’s Start.
Setting up discord bot is straight forward. Navigate to application page. Create an application and then create a bot under your application.
After creating the BOT you will see their are several settings for the BOT. You will be needing your `BOT Token` under your Bot settings to connect it from your code.
If you go to the OAuth2 settings you can create a link with needed permission and by clicking the link a discord server owner can add the bot to their server. For testing purpose I created a server for myself and added the bot first before testing it in my office server.
At this point you should see the bot has joined in your server. But it’s offline. Because we are yet to connect it to our code to give it a life. 🤖❤
If you had any problem creating the discord bot, follow detail visual steps in the link below:
discordpy.readthedocs.io
I spent a lot of time here. Because the torchMoji was saying to use Conda to brew the project. But I was facing a round of errors while trying to download all the dependencies.
Though you can use any of the environment management tool as you prefer (conda/venv), you just need to know how to use it. Conda is mostly preffered while using in data science because they set up all the environment packages needed in one go. Which is easier. But Venv is more flexible I think.
Anyways, after failing a few trial and error, I finally found a way. I downloaded the torchMoji project and used it in my project as a package. I uses venv for my environment management. You can follow along my github repo for the setup. https://github.com/anuragbhattacharjee/discord-nlp-smily-bot/
After the setup is done. Now is the time to make some tests. I had to make some changes in the torchMoji library to work properly in my code module.
Now writing a code to use the torchMoji to predict a smily is pretty straight forward:
We can test it by running it in terminal
python3>>> from emojize import Emojize>>> e = Emojize()>>> e.predict("I am doing great today!"):smile:
This is where the fun begins. After your project is set, it’s now time to connect to your bot and make some tests.
To connect to discord we need to install discord.py package which should have already been installed if you have installed the requirements.txt.
Now to connect to discord bot we need to make an .env file and put our secret key in the .env file as DISCORD_TOKEN. I have made a env.demo file and pushed it in my git repo so that you can just use it. 😁
After the token is set, we can connect to discord.Client() and listen to several events of the client.
I have made a simple implementation just by sending a smily message and reacting to all messages. But we can make it smarter by inspecting the message if I have been mentioned or if there is my name in the message just to make it more human, because what kinda developer replies to every message in the thread. 🤷🏻♂️
But I am leaving it up to implement for your need. Don’t forget to fork and star the repo if needed.
Here are the details discord events that you can use:
discordpy.readthedocs.io
References:
[1] LONG SHORT-TERM MEMORY by Hochreiter and Schmidhuber, 1997; Sutskever et al., 2014 https://www.bioinf.jku.at/publications/older/2604.pdf
[2] Using millions of emoji occurrences to learn any-domain representations for detecting sentiment, emotion and sarcasmby Bjarke Felbo, Alan Mislove, Anders Søgaard, Iyad Rahwan, Sune Lehmannhttps://arxiv.org/abs/1708.00524
[3] Attention Is All You Needby Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhinhttps://arxiv.org/abs/1706.03762
[4] DeepMoji https://github.com/bfelbo/DeepMoji
[5] TorchMoji https://github.com/huggingface/torchMoji
I hope you enjoyed this blog. This is the second story of the series that I am writing on several topics of NLP. If you want to read more of my blogs than you can follow me on here in medium.
I am Anurag. Working professionally as a Software Engineer since 2014. I am currently working on an NLU micro-service for my current employer. Recently I am studying research paper to understand more about NLP. In my free time, I like to develop web and mobile apps that simple and useful. You can connect with me here:
🔗 https://www.linkedin.com/in/anuragbhattacharjee/🕸 http://anuragbhattacharjee.com
Happy Coding 😀
|
[
{
"code": null,
"e": 634,
"s": 172,
"text": "I have been reading a lot of paper articles lately, mostly on Deep Learning, RNN, CNN, LSTM[1], Transformer(Attention is all you need)[3], BERT etc. The list is only growing. But the best way to learn anything is to experience it. And also if I deploy a bot with my face, in my office server it can give proxy for me sometimes when I am busy reading. 😜 Just Kidding. As an experienced software developer its just an urge to implement the new knowledge acquired."
},
{
"code": null,
"e": 1119,
"s": 634,
"text": "But there are some big hindrances. Where will I get so much data to train a Neural Net? Even if I manage data, I will need a machine with hi-fi configuration or at-least with a powerful GPU to train my model with the data. But, if there is a will there is way. 🤓 After a bit of research I found, DeepMoji 🧙🏻♂️. We can use pre trained models like DeepMoji to implement our bot. It’s a common practice now a days to work on a pre-trained model and make it better according to the need."
},
{
"code": null,
"e": 1397,
"s": 1119,
"text": "This is a perfect opportunity for me to make a BOT in discord(as my office communication is held in discord) and experience how a NLP process works using a varient of LSTM and attention mechanism. This BOT can listen to all the messages being received and react with emoticons."
},
{
"code": null,
"e": 1586,
"s": 1397,
"text": "DeepMoji is a model built on Keras and the backend on Tensorflow. Deepmoji is based on this paper[2] developped by Bjarke Felbo, Alan Mislove, Anders Søgaard, Iyad Rahwan and Sune Lehmann."
},
{
"code": null,
"e": 1977,
"s": 1586,
"text": "This paper shows that by extending the distant supervision to a more diverse set of noisy labels, the models can learn richer representations. Through emoji prediction on a dataset of 1.2 billion tweets containing one of 64 common emojis they have obtained state-of-the-art performance on 8 benchmark datasets within sentiment, emotion and sarcasm detection using a single pretrained model."
},
{
"code": null,
"e": 2203,
"s": 1977,
"text": "TorchMoji is a pyTorch implementation of the DeepMoji model built by huggingface. DeepMoji is built on python 2.7. So we will use TochMoji which is a implementation in python3. So we will use torchmoji for our implementation."
},
{
"code": null,
"e": 2567,
"s": 2203,
"text": "The most hectic part for me in this journey was the setup. Because I couldn’t find any proper example to implement torchMoji in a project. All the examples are the test cases used in jupyter notebook. But I am particularly interested in implementing it inside a project using my VS Code so that I can connect it with my discord BOT and send a response from there."
},
{
"code": null,
"e": 2660,
"s": 2567,
"text": "You can see my full code here: https://github.com/anuragbhattacharjee/discord-nlp-smily-bot/"
},
{
"code": null,
"e": 2820,
"s": 2660,
"text": "*** Giving ⭐️ Star on github repositories helps us both grow. You will get all the updates of the project and I will get the inspiration to update the project."
},
{
"code": null,
"e": 2836,
"s": 2820,
"text": "So Let’s Start."
},
{
"code": null,
"e": 2978,
"s": 2836,
"text": "Setting up discord bot is straight forward. Navigate to application page. Create an application and then create a bot under your application."
},
{
"code": null,
"e": 3145,
"s": 2978,
"text": "After creating the BOT you will see their are several settings for the BOT. You will be needing your `BOT Token` under your Bot settings to connect it from your code."
},
{
"code": null,
"e": 3417,
"s": 3145,
"text": "If you go to the OAuth2 settings you can create a link with needed permission and by clicking the link a discord server owner can add the bot to their server. For testing purpose I created a server for myself and added the bot first before testing it in my office server."
},
{
"code": null,
"e": 3566,
"s": 3417,
"text": "At this point you should see the bot has joined in your server. But it’s offline. Because we are yet to connect it to our code to give it a life. 🤖❤"
},
{
"code": null,
"e": 3661,
"s": 3566,
"text": "If you had any problem creating the discord bot, follow detail visual steps in the link below:"
},
{
"code": null,
"e": 3686,
"s": 3661,
"text": "discordpy.readthedocs.io"
},
{
"code": null,
"e": 3863,
"s": 3686,
"text": "I spent a lot of time here. Because the torchMoji was saying to use Conda to brew the project. But I was facing a round of errors while trying to download all the dependencies."
},
{
"code": null,
"e": 4159,
"s": 3863,
"text": "Though you can use any of the environment management tool as you prefer (conda/venv), you just need to know how to use it. Conda is mostly preffered while using in data science because they set up all the environment packages needed in one go. Which is easier. But Venv is more flexible I think."
},
{
"code": null,
"e": 4459,
"s": 4159,
"text": "Anyways, after failing a few trial and error, I finally found a way. I downloaded the torchMoji project and used it in my project as a package. I uses venv for my environment management. You can follow along my github repo for the setup. https://github.com/anuragbhattacharjee/discord-nlp-smily-bot/"
},
{
"code": null,
"e": 4608,
"s": 4459,
"text": "After the setup is done. Now is the time to make some tests. I had to make some changes in the torchMoji library to work properly in my code module."
},
{
"code": null,
"e": 4695,
"s": 4608,
"text": "Now writing a code to use the torchMoji to predict a smily is pretty straight forward:"
},
{
"code": null,
"e": 4736,
"s": 4695,
"text": "We can test it by running it in terminal"
},
{
"code": null,
"e": 4839,
"s": 4736,
"text": "python3>>> from emojize import Emojize>>> e = Emojize()>>> e.predict(\"I am doing great today!\"):smile:"
},
{
"code": null,
"e": 4954,
"s": 4839,
"text": "This is where the fun begins. After your project is set, it’s now time to connect to your bot and make some tests."
},
{
"code": null,
"e": 5099,
"s": 4954,
"text": "To connect to discord we need to install discord.py package which should have already been installed if you have installed the requirements.txt."
},
{
"code": null,
"e": 5304,
"s": 5099,
"text": "Now to connect to discord bot we need to make an .env file and put our secret key in the .env file as DISCORD_TOKEN. I have made a env.demo file and pushed it in my git repo so that you can just use it. 😁"
},
{
"code": null,
"e": 5407,
"s": 5304,
"text": "After the token is set, we can connect to discord.Client() and listen to several events of the client."
},
{
"code": null,
"e": 5724,
"s": 5407,
"text": "I have made a simple implementation just by sending a smily message and reacting to all messages. But we can make it smarter by inspecting the message if I have been mentioned or if there is my name in the message just to make it more human, because what kinda developer replies to every message in the thread. 🤷🏻♂️"
},
{
"code": null,
"e": 5825,
"s": 5724,
"text": "But I am leaving it up to implement for your need. Don’t forget to fork and star the repo if needed."
},
{
"code": null,
"e": 5879,
"s": 5825,
"text": "Here are the details discord events that you can use:"
},
{
"code": null,
"e": 5904,
"s": 5879,
"text": "discordpy.readthedocs.io"
},
{
"code": null,
"e": 5916,
"s": 5904,
"text": "References:"
},
{
"code": null,
"e": 6063,
"s": 5916,
"text": "[1] LONG SHORT-TERM MEMORY by Hochreiter and Schmidhuber, 1997; Sutskever et al., 2014 https://www.bioinf.jku.at/publications/older/2604.pdf"
},
{
"code": null,
"e": 6288,
"s": 6063,
"text": "[2] Using millions of emoji occurrences to learn any-domain representations for detecting sentiment, emotion and sarcasmby Bjarke Felbo, Alan Mislove, Anders Søgaard, Iyad Rahwan, Sune Lehmannhttps://arxiv.org/abs/1708.00524"
},
{
"code": null,
"e": 6473,
"s": 6288,
"text": "[3] Attention Is All You Needby Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhinhttps://arxiv.org/abs/1706.03762"
},
{
"code": null,
"e": 6521,
"s": 6473,
"text": "[4] DeepMoji https://github.com/bfelbo/DeepMoji"
},
{
"code": null,
"e": 6576,
"s": 6521,
"text": "[5] TorchMoji https://github.com/huggingface/torchMoji"
},
{
"code": null,
"e": 6768,
"s": 6576,
"text": "I hope you enjoyed this blog. This is the second story of the series that I am writing on several topics of NLP. If you want to read more of my blogs than you can follow me on here in medium."
},
{
"code": null,
"e": 7088,
"s": 6768,
"text": "I am Anurag. Working professionally as a Software Engineer since 2014. I am currently working on an NLU micro-service for my current employer. Recently I am studying research paper to understand more about NLP. In my free time, I like to develop web and mobile apps that simple and useful. You can connect with me here:"
},
{
"code": null,
"e": 7171,
"s": 7088,
"text": "🔗 https://www.linkedin.com/in/anuragbhattacharjee/🕸 http://anuragbhattacharjee.com"
}
] |
C# Program to count vowels in a string
|
You need to check for both the vowels and consonants, but do not forget to check for both the uppercase as well lowercase.
For counting vowels, check for “aeiou” characters separately i.e.
if (myStr[i] == 'a' || myStr[i] == 'e' || myStr[i] == 'i' || myStr[i] == 'o' || myStr[i] == 'u' || myStr[i] == 'A' || myStr[i] == 'E' || myStr[i] == 'I' || myStr[i] == 'O' || myStr[i] == 'U') {
vowel_count++;
}
The following is the code to count the number of Vowels in a string.
Live Demo
using System;
public class Demo {
public static void Main() {
string myStr;
int i, len, vowel_count, cons_count;
myStr = "Avengers";
vowel_count = 0;
cons_count = 0;
// find length
len = myStr.Length;
for(i=0; i<len; i++) {
if(myStr[i] =='a' || myStr[i]=='e' || myStr[i]=='i' || myStr[i]=='o' || myStr[i]=='u' || myStr[i]=='A' || myStr[i]=='E' || myStr[i]=='I' || myStr[i]=='O' || myStr[i]=='U') {
vowel_count++;
} else {
cons_count++;
}
}
Console.Write("\nVowels in the string: {0}\n", vowel_count);
}
}
Vowels in the string: 3
|
[
{
"code": null,
"e": 1185,
"s": 1062,
"text": "You need to check for both the vowels and consonants, but do not forget to check for both the uppercase as well lowercase."
},
{
"code": null,
"e": 1251,
"s": 1185,
"text": "For counting vowels, check for “aeiou” characters separately i.e."
},
{
"code": null,
"e": 1465,
"s": 1251,
"text": "if (myStr[i] == 'a' || myStr[i] == 'e' || myStr[i] == 'i' || myStr[i] == 'o' || myStr[i] == 'u' || myStr[i] == 'A' || myStr[i] == 'E' || myStr[i] == 'I' || myStr[i] == 'O' || myStr[i] == 'U') {\n vowel_count++;\n}"
},
{
"code": null,
"e": 1534,
"s": 1465,
"text": "The following is the code to count the number of Vowels in a string."
},
{
"code": null,
"e": 1544,
"s": 1534,
"text": "Live Demo"
},
{
"code": null,
"e": 2166,
"s": 1544,
"text": "using System;\npublic class Demo {\n public static void Main() {\n string myStr;\n int i, len, vowel_count, cons_count;\n myStr = \"Avengers\";\n vowel_count = 0;\n cons_count = 0;\n // find length\n len = myStr.Length;\n for(i=0; i<len; i++) {\n if(myStr[i] =='a' || myStr[i]=='e' || myStr[i]=='i' || myStr[i]=='o' || myStr[i]=='u' || myStr[i]=='A' || myStr[i]=='E' || myStr[i]=='I' || myStr[i]=='O' || myStr[i]=='U') {\n vowel_count++;\n } else {\n cons_count++;\n }\n }\n Console.Write(\"\\nVowels in the string: {0}\\n\", vowel_count);\n }\n}"
},
{
"code": null,
"e": 2190,
"s": 2166,
"text": "Vowels in the string: 3"
}
] |
for loop in java
|
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.
The syntax of a for loop is −
for(initialization; Boolean_expression; update) {
// Statements
}
Here is the flow of control in a for loop −
The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables and this step ends with a semi colon (;).
The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables and this step ends with a semi colon (;).
Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop will not be executed and control jumps to the next statement past the for loop.
Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop will not be executed and control jumps to the next statement past the for loop.
After the body of the for loop gets executed, the control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank with a semicolon at the end.
After the body of the for loop gets executed, the control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank with a semicolon at the end.
The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.
The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.
Following is an example code of the for loop in Java.
public class Test {
public static void main(String args[]) {
for(int x = 10; x < 20; x = x + 1) {
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
This will produce the following result −
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
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": 2520,
"s": 2377,
"text": "A for loop is a repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times."
},
{
"code": null,
"e": 2596,
"s": 2520,
"text": "A for loop is useful when you know how many times a task is to be repeated."
},
{
"code": null,
"e": 2626,
"s": 2596,
"text": "The syntax of a for loop is −"
},
{
"code": null,
"e": 2696,
"s": 2626,
"text": "for(initialization; Boolean_expression; update) {\n // Statements\n}\n"
},
{
"code": null,
"e": 2740,
"s": 2696,
"text": "Here is the flow of control in a for loop −"
},
{
"code": null,
"e": 2914,
"s": 2740,
"text": "The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables and this step ends with a semi colon (;)."
},
{
"code": null,
"e": 3088,
"s": 2914,
"text": "The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables and this step ends with a semi colon (;)."
},
{
"code": null,
"e": 3297,
"s": 3088,
"text": "Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop will not be executed and control jumps to the next statement past the for loop."
},
{
"code": null,
"e": 3506,
"s": 3297,
"text": "Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop will not be executed and control jumps to the next statement past the for loop."
},
{
"code": null,
"e": 3729,
"s": 3506,
"text": "After the body of the for loop gets executed, the control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank with a semicolon at the end."
},
{
"code": null,
"e": 3952,
"s": 3729,
"text": "After the body of the for loop gets executed, the control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank with a semicolon at the end."
},
{
"code": null,
"e": 4179,
"s": 3952,
"text": "The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates."
},
{
"code": null,
"e": 4406,
"s": 4179,
"text": "The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates."
},
{
"code": null,
"e": 4460,
"s": 4406,
"text": "Following is an example code of the for loop in Java."
},
{
"code": null,
"e": 4666,
"s": 4460,
"text": "public class Test {\n\n public static void main(String args[]) {\n\n for(int x = 10; x < 20; x = x + 1) {\n System.out.print(\"value of x : \" + x );\n System.out.print(\"\\n\");\n }\n }\n}"
},
{
"code": null,
"e": 4707,
"s": 4666,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 4868,
"s": 4707,
"text": "value of x : 10\nvalue of x : 11\nvalue of x : 12\nvalue of x : 13\nvalue of x : 14\nvalue of x : 15\nvalue of x : 16\nvalue of x : 17\nvalue of x : 18\nvalue of x : 19\n"
},
{
"code": null,
"e": 4901,
"s": 4868,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4917,
"s": 4901,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4950,
"s": 4917,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4966,
"s": 4950,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5001,
"s": 4966,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5015,
"s": 5001,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5049,
"s": 5015,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5063,
"s": 5049,
"text": " Tushar Kale"
},
{
"code": null,
"e": 5100,
"s": 5063,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5115,
"s": 5100,
"text": " Monica Mittal"
},
{
"code": null,
"e": 5148,
"s": 5115,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5167,
"s": 5148,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5174,
"s": 5167,
"text": " Print"
},
{
"code": null,
"e": 5185,
"s": 5174,
"text": " Add Notes"
}
] |
Computer Vision — Auto grading Handwritten Mathematical Answersheets | by Divyaprabha M | Towards Data Science
|
Grading is an essential part of education. Assessing each answer sheet manually, offering fair, unbiased and valid grade is difficult most of the time. This article is about my internship project with my mentor Bijon Guha on building a computer vision model that will automatically evaluate the answer sheets thereby ensuring that the grades are based solely on the student’s performance.
Below are the sample worksheets we are going to examine and grade.
Each of these worksheets was written by different people. There will be variations in line width, character style in the same page, pen nib width and character spacing, etc.
The idea is to correct each line in the worksheet and mark the lines with boxes. Where the green box represents that the line is correct and the red box represents the line is in-correct.
( Note: I have not added all the code here, if you want to check you can visit my GitHub where I have the tutorial in a ipynb notebook )
There are two modules in the workflow Workspace detection module and Analysis Module. Workspace Detection module is responsible for detecting multiple work spaces in a given sheet of paper.
Analysis module is responsible for detecting and localizing characters in lines in any given single workspace, and mathematically analyzing them and then drawing red, green boxes depending upon their correctness.
Workspace detection module assumes that there are valid rectangular boxes in the given scanned worksheet. This image below shows the worksheet design. Three largest rectangular boxes in this worksheet are the work-spaces.
Workspace detection module is done using openCV. We will first find the rectangular boxes, then sort them based on their positions in the worksheet. Since there are many rectangles in the worksheet, we will have to select the valid work-spaces among the other rectangles. Let’s see how each step is done
Rectangles are formed by two horizontal and vertical lines. So the first step is to find all the horizontal and vertical lines ignoring digits, symbols or anything that is written on the worksheet.
This code below will first create a binary image called “vertical_lines_img” which contains all the vertical lines that are present in the worksheet, then another binary image called “horizontal_lines_img” which contains all horizontal lines that are present in the worksheet.
Next, we have to add image “vertical_lines_img” with “horizontal_lines_img” to get the final image.
Contours are defined as the line joining all the points along the boundary of an image that are having the same intensity.
OpenCV has findContour() function that helps in extracting the contours from the image. Each individual contour is a Numpy array of (x,y) coordinates of boundary points of the object. We can use that to find all the objects in the final image (Only objects in the final image are the rectangles).
Since final image is just the binary version of the original image coordinates of the rectangles in the final image is equal to the coordinates of the rectangles in the original image.
Now we know the coordinates lets draw them on the original image using openCV’s drawContours() function.
Now we have found all the rectangles, its time to sort them top-to-bottom based on their coordinates. This code below will do that for us.
sort_contours function will return contours and bounding boxes(top-left and bottom-right coordinates) sorted in the method we have given. In this case method is top to bottom.
There are many rectangles, but we only need the three largest ones. How can we select the three largest rectangles?.... One answer is to find the area of the rectangles, then choose the top 3 rectangles which have the maximum area.
These selected rectangles are the work-spaces that are then extracted from the worksheet and sent to the Analysis Module.
Analysis module as explained above will first detect the lines, predict the characters in each line and finally forms an equation with the predicted characters then evaluate them by marking boxes.
Detecting the lines is the tricky part, everyone has their way of solving equations some solve step by step, some can solve in just one line, some might write steps for pages and some writes exponents way away from the equation confusing the module to treat those exponents as a separate line.
Our line detection module assumes that there is a sufficient gap between lines and there is some intersection between exponential characters and line. First, the detected work-spaces are converted to binary images then compressed in a single array to take the forward derivative. Wherever there is a line there will be a change in the derivative.
The above code is just a glimpse of how line extraction works. To see complete code click extract_line.
After detecting all the lines we have to send the extracted line images to the text_segment function which will use openCV’s find contours to segment the characters and sort them using the function sort_contours described above where method is now set to left-to-right.
It’s easy for us to say whether the given number is an exponent or not but for the model it’s not that easy. Assuming that the exponents are at-least above half of the line, we can drew a baseline at the center of the image any character which is above the baseline is considered as an exponent.
We can use MNIST dataset for digits (28*28 pixels) and Kaggle’s Handwritten Mathematical symbols dataset for symbols(45*45 pixels) to train the model.
How MNIST is actually created?
Handwritten digits of 128 * 128 pixels collected from 500 different writers.A Gaussian filter is applied to the image to soften the edgesThe digit is then placed and centered into a square image by preserving the aspect ratio.The image is then down-sampled to 28 × 28 pixels using bi-cubic interpolation
Handwritten digits of 128 * 128 pixels collected from 500 different writers.
A Gaussian filter is applied to the image to soften the edges
The digit is then placed and centered into a square image by preserving the aspect ratio.
The image is then down-sampled to 28 × 28 pixels using bi-cubic interpolation
Images of symbols are preprocessed in the same way as MNIST digits before training. The reason for preprocessing is that the two data-sets we have chosen have different characteristics like dimensions, thickness and line width this makes hard for the deep learning model to find the patterns. Preprocessing helps us reduce the variations among digits and symbols.
Almost 60,000 images of digits and preprocessed symbols were trained on Deep Columnar Convolutional Neural Network (DCCNN) a single deep and wide neural network architecture that offers near state-of-the-art performance like ensemble models on various image classification challenges, such as MNIST, CIFAR-10, and CIFAR-100 datasets. This model achieved atmost 96 % accuracy.
To see training code click DCCNN_training.ipynb
Evaluation is the last and the most important part. To solve any equation we can use python’s eval method.
The eval method parses the expression passed to it and runs python expression(code) within the program
This is an example of how eval works
>>Enter the function y(in terms of x):‘x*(x+1)*(x+2)’>>Enter the value of x:3>>print(y)60
Steps involved in evaluation process are,
Solve the given math question and save the answerSolve each handwritten lines and compare its derived value with the answer stored.Draw a green bounding box if the line correct and red if the line is wrong.
Solve the given math question and save the answer
Solve each handwritten lines and compare its derived value with the answer stored.
Draw a green bounding box if the line correct and red if the line is wrong.
Let’s take an example, say the question is to solve the equation A*x2 + B*y
where, A=56, B=7, x=3 and y=13 and the answer to this equation is 595 (56*32 +7*13 = 595).
A green box indicates the line is correct, whereas red indicates the line is wrong.
The first and the last line is correct, on solving these lines we get 595 which matches with the actual answer.
The second line (56*7 + 92) is wrong. 32 is 9 but it’s written as 7 and on solving we get 584 which is not equal to 595
The third line (595 + 92) is also wrong, on solving this line we get 684 which again is not equal to 595.
Let’s summarize, the scanned worksheet is sent to the work-spaces detection module it will return all the rectangular work-spaces in the given worksheet, then the detected work-spaces are passed to line extraction module to extract all the lines. The extracted lines are then sent to character segmentation module it will segment the character and the deep learning model DCCNN will predict the digit/symbol. Finally, evaluation module will assess the line and draw red/green bounding box.
Automating grading process not only helps the teachers and also creates a comfortable learning experience for the students. This solution can be made even cooler by recognizing more complex mathematical equations like differential integral equations, recognition of cursive handwriting where the character is not separated, detecting plagiarism and recognizing chemical equations.
Thanks for reading till the end !!... If you have enjoyed this post let me know by clapping and I’d be very grateful if you’d help it spread by sharing with your friends :). ✌️
|
[
{
"code": null,
"e": 561,
"s": 172,
"text": "Grading is an essential part of education. Assessing each answer sheet manually, offering fair, unbiased and valid grade is difficult most of the time. This article is about my internship project with my mentor Bijon Guha on building a computer vision model that will automatically evaluate the answer sheets thereby ensuring that the grades are based solely on the student’s performance."
},
{
"code": null,
"e": 628,
"s": 561,
"text": "Below are the sample worksheets we are going to examine and grade."
},
{
"code": null,
"e": 802,
"s": 628,
"text": "Each of these worksheets was written by different people. There will be variations in line width, character style in the same page, pen nib width and character spacing, etc."
},
{
"code": null,
"e": 990,
"s": 802,
"text": "The idea is to correct each line in the worksheet and mark the lines with boxes. Where the green box represents that the line is correct and the red box represents the line is in-correct."
},
{
"code": null,
"e": 1127,
"s": 990,
"text": "( Note: I have not added all the code here, if you want to check you can visit my GitHub where I have the tutorial in a ipynb notebook )"
},
{
"code": null,
"e": 1317,
"s": 1127,
"text": "There are two modules in the workflow Workspace detection module and Analysis Module. Workspace Detection module is responsible for detecting multiple work spaces in a given sheet of paper."
},
{
"code": null,
"e": 1530,
"s": 1317,
"text": "Analysis module is responsible for detecting and localizing characters in lines in any given single workspace, and mathematically analyzing them and then drawing red, green boxes depending upon their correctness."
},
{
"code": null,
"e": 1752,
"s": 1530,
"text": "Workspace detection module assumes that there are valid rectangular boxes in the given scanned worksheet. This image below shows the worksheet design. Three largest rectangular boxes in this worksheet are the work-spaces."
},
{
"code": null,
"e": 2056,
"s": 1752,
"text": "Workspace detection module is done using openCV. We will first find the rectangular boxes, then sort them based on their positions in the worksheet. Since there are many rectangles in the worksheet, we will have to select the valid work-spaces among the other rectangles. Let’s see how each step is done"
},
{
"code": null,
"e": 2254,
"s": 2056,
"text": "Rectangles are formed by two horizontal and vertical lines. So the first step is to find all the horizontal and vertical lines ignoring digits, symbols or anything that is written on the worksheet."
},
{
"code": null,
"e": 2531,
"s": 2254,
"text": "This code below will first create a binary image called “vertical_lines_img” which contains all the vertical lines that are present in the worksheet, then another binary image called “horizontal_lines_img” which contains all horizontal lines that are present in the worksheet."
},
{
"code": null,
"e": 2631,
"s": 2531,
"text": "Next, we have to add image “vertical_lines_img” with “horizontal_lines_img” to get the final image."
},
{
"code": null,
"e": 2754,
"s": 2631,
"text": "Contours are defined as the line joining all the points along the boundary of an image that are having the same intensity."
},
{
"code": null,
"e": 3051,
"s": 2754,
"text": "OpenCV has findContour() function that helps in extracting the contours from the image. Each individual contour is a Numpy array of (x,y) coordinates of boundary points of the object. We can use that to find all the objects in the final image (Only objects in the final image are the rectangles)."
},
{
"code": null,
"e": 3236,
"s": 3051,
"text": "Since final image is just the binary version of the original image coordinates of the rectangles in the final image is equal to the coordinates of the rectangles in the original image."
},
{
"code": null,
"e": 3341,
"s": 3236,
"text": "Now we know the coordinates lets draw them on the original image using openCV’s drawContours() function."
},
{
"code": null,
"e": 3480,
"s": 3341,
"text": "Now we have found all the rectangles, its time to sort them top-to-bottom based on their coordinates. This code below will do that for us."
},
{
"code": null,
"e": 3656,
"s": 3480,
"text": "sort_contours function will return contours and bounding boxes(top-left and bottom-right coordinates) sorted in the method we have given. In this case method is top to bottom."
},
{
"code": null,
"e": 3888,
"s": 3656,
"text": "There are many rectangles, but we only need the three largest ones. How can we select the three largest rectangles?.... One answer is to find the area of the rectangles, then choose the top 3 rectangles which have the maximum area."
},
{
"code": null,
"e": 4010,
"s": 3888,
"text": "These selected rectangles are the work-spaces that are then extracted from the worksheet and sent to the Analysis Module."
},
{
"code": null,
"e": 4207,
"s": 4010,
"text": "Analysis module as explained above will first detect the lines, predict the characters in each line and finally forms an equation with the predicted characters then evaluate them by marking boxes."
},
{
"code": null,
"e": 4501,
"s": 4207,
"text": "Detecting the lines is the tricky part, everyone has their way of solving equations some solve step by step, some can solve in just one line, some might write steps for pages and some writes exponents way away from the equation confusing the module to treat those exponents as a separate line."
},
{
"code": null,
"e": 4848,
"s": 4501,
"text": "Our line detection module assumes that there is a sufficient gap between lines and there is some intersection between exponential characters and line. First, the detected work-spaces are converted to binary images then compressed in a single array to take the forward derivative. Wherever there is a line there will be a change in the derivative."
},
{
"code": null,
"e": 4952,
"s": 4848,
"text": "The above code is just a glimpse of how line extraction works. To see complete code click extract_line."
},
{
"code": null,
"e": 5222,
"s": 4952,
"text": "After detecting all the lines we have to send the extracted line images to the text_segment function which will use openCV’s find contours to segment the characters and sort them using the function sort_contours described above where method is now set to left-to-right."
},
{
"code": null,
"e": 5518,
"s": 5222,
"text": "It’s easy for us to say whether the given number is an exponent or not but for the model it’s not that easy. Assuming that the exponents are at-least above half of the line, we can drew a baseline at the center of the image any character which is above the baseline is considered as an exponent."
},
{
"code": null,
"e": 5669,
"s": 5518,
"text": "We can use MNIST dataset for digits (28*28 pixels) and Kaggle’s Handwritten Mathematical symbols dataset for symbols(45*45 pixels) to train the model."
},
{
"code": null,
"e": 5700,
"s": 5669,
"text": "How MNIST is actually created?"
},
{
"code": null,
"e": 6004,
"s": 5700,
"text": "Handwritten digits of 128 * 128 pixels collected from 500 different writers.A Gaussian filter is applied to the image to soften the edgesThe digit is then placed and centered into a square image by preserving the aspect ratio.The image is then down-sampled to 28 × 28 pixels using bi-cubic interpolation"
},
{
"code": null,
"e": 6081,
"s": 6004,
"text": "Handwritten digits of 128 * 128 pixels collected from 500 different writers."
},
{
"code": null,
"e": 6143,
"s": 6081,
"text": "A Gaussian filter is applied to the image to soften the edges"
},
{
"code": null,
"e": 6233,
"s": 6143,
"text": "The digit is then placed and centered into a square image by preserving the aspect ratio."
},
{
"code": null,
"e": 6311,
"s": 6233,
"text": "The image is then down-sampled to 28 × 28 pixels using bi-cubic interpolation"
},
{
"code": null,
"e": 6675,
"s": 6311,
"text": "Images of symbols are preprocessed in the same way as MNIST digits before training. The reason for preprocessing is that the two data-sets we have chosen have different characteristics like dimensions, thickness and line width this makes hard for the deep learning model to find the patterns. Preprocessing helps us reduce the variations among digits and symbols."
},
{
"code": null,
"e": 7051,
"s": 6675,
"text": "Almost 60,000 images of digits and preprocessed symbols were trained on Deep Columnar Convolutional Neural Network (DCCNN) a single deep and wide neural network architecture that offers near state-of-the-art performance like ensemble models on various image classification challenges, such as MNIST, CIFAR-10, and CIFAR-100 datasets. This model achieved atmost 96 % accuracy."
},
{
"code": null,
"e": 7099,
"s": 7051,
"text": "To see training code click DCCNN_training.ipynb"
},
{
"code": null,
"e": 7206,
"s": 7099,
"text": "Evaluation is the last and the most important part. To solve any equation we can use python’s eval method."
},
{
"code": null,
"e": 7309,
"s": 7206,
"text": "The eval method parses the expression passed to it and runs python expression(code) within the program"
},
{
"code": null,
"e": 7346,
"s": 7309,
"text": "This is an example of how eval works"
},
{
"code": null,
"e": 7436,
"s": 7346,
"text": ">>Enter the function y(in terms of x):‘x*(x+1)*(x+2)’>>Enter the value of x:3>>print(y)60"
},
{
"code": null,
"e": 7478,
"s": 7436,
"text": "Steps involved in evaluation process are,"
},
{
"code": null,
"e": 7685,
"s": 7478,
"text": "Solve the given math question and save the answerSolve each handwritten lines and compare its derived value with the answer stored.Draw a green bounding box if the line correct and red if the line is wrong."
},
{
"code": null,
"e": 7735,
"s": 7685,
"text": "Solve the given math question and save the answer"
},
{
"code": null,
"e": 7818,
"s": 7735,
"text": "Solve each handwritten lines and compare its derived value with the answer stored."
},
{
"code": null,
"e": 7894,
"s": 7818,
"text": "Draw a green bounding box if the line correct and red if the line is wrong."
},
{
"code": null,
"e": 7970,
"s": 7894,
"text": "Let’s take an example, say the question is to solve the equation A*x2 + B*y"
},
{
"code": null,
"e": 8061,
"s": 7970,
"text": "where, A=56, B=7, x=3 and y=13 and the answer to this equation is 595 (56*32 +7*13 = 595)."
},
{
"code": null,
"e": 8145,
"s": 8061,
"text": "A green box indicates the line is correct, whereas red indicates the line is wrong."
},
{
"code": null,
"e": 8257,
"s": 8145,
"text": "The first and the last line is correct, on solving these lines we get 595 which matches with the actual answer."
},
{
"code": null,
"e": 8377,
"s": 8257,
"text": "The second line (56*7 + 92) is wrong. 32 is 9 but it’s written as 7 and on solving we get 584 which is not equal to 595"
},
{
"code": null,
"e": 8483,
"s": 8377,
"text": "The third line (595 + 92) is also wrong, on solving this line we get 684 which again is not equal to 595."
},
{
"code": null,
"e": 8973,
"s": 8483,
"text": "Let’s summarize, the scanned worksheet is sent to the work-spaces detection module it will return all the rectangular work-spaces in the given worksheet, then the detected work-spaces are passed to line extraction module to extract all the lines. The extracted lines are then sent to character segmentation module it will segment the character and the deep learning model DCCNN will predict the digit/symbol. Finally, evaluation module will assess the line and draw red/green bounding box."
},
{
"code": null,
"e": 9354,
"s": 8973,
"text": "Automating grading process not only helps the teachers and also creates a comfortable learning experience for the students. This solution can be made even cooler by recognizing more complex mathematical equations like differential integral equations, recognition of cursive handwriting where the character is not separated, detecting plagiarism and recognizing chemical equations."
}
] |
How to create Horizontal Slider in Java?
|
To create Horizontal slider in Java, use the Swing JSlider. Let us first create a frame and a Horizontal slider in it −
JFrame frame = new JFrame("Frame with Slider");
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 70);
Now, we will set the values for the slider. Display the ticks −
slider.setMinorTickSpacing(5);
slider.setMajorTickSpacing(20);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
Add the slider in the panel:
JPanel panel = new JPanel();
panel.add(slider);
The following is an example to create horizontal slider −
package my;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.WindowConstants;
public class SwingDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Frame with Slider");
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 70);
slider.setMinorTickSpacing(5);
slider.setMajorTickSpacing(20);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
JPanel panel = new JPanel();
panel.add(slider);
frame.add(panel);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(500, 300);
frame.setVisible(true);
}
}
|
[
{
"code": null,
"e": 1182,
"s": 1062,
"text": "To create Horizontal slider in Java, use the Swing JSlider. Let us first create a frame and a Horizontal slider in it −"
},
{
"code": null,
"e": 1292,
"s": 1182,
"text": "JFrame frame = new JFrame(\"Frame with Slider\");\nJSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 70);"
},
{
"code": null,
"e": 1356,
"s": 1292,
"text": "Now, we will set the values for the slider. Display the ticks −"
},
{
"code": null,
"e": 1553,
"s": 1356,
"text": "slider.setMinorTickSpacing(5);\nslider.setMajorTickSpacing(20);\nslider.setPaintTicks(true);\nslider.setPaintLabels(true);\nAdd the slider in the panel:\nJPanel panel = new JPanel();\npanel.add(slider);"
},
{
"code": null,
"e": 1611,
"s": 1553,
"text": "The following is an example to create horizontal slider −"
},
{
"code": null,
"e": 2297,
"s": 1611,
"text": "package my;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.JSlider;\nimport javax.swing.WindowConstants;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame(\"Frame with Slider\");\n JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 70);\n slider.setMinorTickSpacing(5);\n slider.setMajorTickSpacing(20);\n slider.setPaintTicks(true);\n slider.setPaintLabels(true);\n JPanel panel = new JPanel();\n panel.add(slider);\n frame.add(panel);\n frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);\n frame.setSize(500, 300);\n frame.setVisible(true);\n }\n}"
}
] |
Comparing two strings in MySQL?
|
To compare two strings, which are numbers, let us first create a table. Following is the query −
mysql> create table compareTwoStringsDemo
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Value varchar(100)
-> );
Query OK, 0 rows affected (0.52 sec)
Following is the query to insert some records in the table using insert command −
mysql> insert into compareTwoStringsDemo(Value) values('1235667');
Query OK, 1 row affected (0.66 sec)
mysql> insert into compareTwoStringsDemo(Value) values('999999');
Query OK, 1 row affected (0.11 sec)
mysql> insert into compareTwoStringsDemo(Value) values('999888');
Query OK, 1 row affected (0.17 sec)
mysql> insert into compareTwoStringsDemo(Value) values('567433');
mysql> insert into compareTwoStringsDemo(Value) values('567433');
Query OK, 1 row affected (0.23 sec)
mysql> insert into compareTwoStringsDemo(Value) values('2345123');
Query OK, 1 row affected (0.13 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from compareTwoStringsDemo;
This will produce the following output −
+----+---------+
| Id | Value |
+----+---------+
| 1 | 1235667 |
| 2 | 999999 |
| 3 | 999888 |
| 4 | 567433 |
| 5 | 2345123 |
+----+---------+
5 rows in set (0.00 sec)
Following is the query to compare two strings which are numbers −
mysql> select *from compareTwoStringsDemo
-> where cast(Value as signed) = 999999;
This will produce the following output. The record with the matching string gets displayed −
+----+--------+
| Id | Value |
+----+--------+
| 2 | 999999 |
+----+--------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1159,
"s": 1062,
"text": "To compare two strings, which are numbers, let us first create a table. Following is the query −"
},
{
"code": null,
"e": 1330,
"s": 1159,
"text": "mysql> create table compareTwoStringsDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> Value varchar(100)\n -> );\nQuery OK, 0 rows affected (0.52 sec)"
},
{
"code": null,
"e": 1412,
"s": 1330,
"text": "Following is the query to insert some records in the table using insert command −"
},
{
"code": null,
"e": 1994,
"s": 1412,
"text": "mysql> insert into compareTwoStringsDemo(Value) values('1235667');\nQuery OK, 1 row affected (0.66 sec)\n\nmysql> insert into compareTwoStringsDemo(Value) values('999999');\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into compareTwoStringsDemo(Value) values('999888');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into compareTwoStringsDemo(Value) values('567433');\nmysql> insert into compareTwoStringsDemo(Value) values('567433');\nQuery OK, 1 row affected (0.23 sec)\n\nmysql> insert into compareTwoStringsDemo(Value) values('2345123');\nQuery OK, 1 row affected (0.13 sec)"
},
{
"code": null,
"e": 2080,
"s": 1994,
"text": "Following is the query to display all records from the table using select statement −"
},
{
"code": null,
"e": 2123,
"s": 2080,
"text": "mysql> select *from compareTwoStringsDemo;"
},
{
"code": null,
"e": 2164,
"s": 2123,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2342,
"s": 2164,
"text": "+----+---------+\n| Id | Value |\n+----+---------+\n| 1 | 1235667 |\n| 2 | 999999 |\n| 3 | 999888 |\n| 4 | 567433 |\n| 5 | 2345123 |\n+----+---------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2408,
"s": 2342,
"text": "Following is the query to compare two strings which are numbers −"
},
{
"code": null,
"e": 2491,
"s": 2408,
"text": "mysql> select *from compareTwoStringsDemo\n-> where cast(Value as signed) = 999999;"
},
{
"code": null,
"e": 2584,
"s": 2491,
"text": "This will produce the following output. The record with the matching string gets displayed −"
},
{
"code": null,
"e": 2688,
"s": 2584,
"text": "+----+--------+\n| Id | Value |\n+----+--------+\n| 2 | 999999 |\n+----+--------+\n1 row in set (0.00 sec)"
}
] |
DB2 - Schemas
|
This chapter introduces and describes the concept of Schema.
A schema is a collection of named objects classified logically in the database.
In a database, you cannot create multiple database objects with same name. To do so, the schema provides a group environment. You can create multiple schemas in a database and you can create multiple database objects with same name, with different schema groups.
A schema can contain tables, functions, indices, tablespaces, procedures, triggers etc. For example, you create two different schemas named as “Professional” and “Personal” for an “employee” database. It is possible to make two different tables with the same name “Employee”. In this environment, one table has professional information and the other has personal information of employee. In spite of having two tables with the same name, they have two different schemas “Personal” and “Professional”. Hence, the user can work with both without encountering any problem. This feature is useful when there are constraints on the naming of tables.
Let us see few commands related to Schema:
Syntax:
db2 get schema
Example: [To get current database schema]
db2 get schema
Syntax:
db2 set schema=<schema_name>
Example: [To arrange ‘schema1’ to current instance environment]
db2 set schema=schema1
Syntax: [To create a new schema with authorized user id]
db2 create schema <schema_name> authroization <inst_user>
Example: [To create “schema1” schema authorized with ‘db2inst2”]
db2 create schema schema1 authorization db2inst2
Let us create two different tables with same name but two different schemas. Here, you create employee table with two different schemas, one for personal and the other for professional information.
Step 1: Create two schemas.
Schema 1: [To create schema named professional]
db2 create schema professional authorization db2inst2
Schema 2: [To create schema named personal]
db2 create schema personal authorization db2inst2
Step 2: Create two tables with the same name for Employee details
Table1: professional.employee
[To create a new table ‘employee’ in the database using schema name ‘professional’]
db2 create table professional.employee(id number, name
varchar(20), profession varchar(20), join_date date,
salary number);
Table2: personal.employee
[To create a new table ‘employee’ in the same database, with schema name ‘personal’]
db2 create table personal.employee(id number, name
varchar(20), d_birth date, phone bigint, address
varchar(200));
After executing these steps, you get two tables with same name ’employee’, with two different schemas.
10 Lectures
1.5 hours
Nishant Malik
41 Lectures
8.5 hours
Parth Panjabi
53 Lectures
11.5 hours
Parth Panjabi
33 Lectures
7 hours
Parth Panjabi
44 Lectures
3 hours
Arnab Chakraborty
178 Lectures
14.5 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1989,
"s": 1928,
"text": "This chapter introduces and describes the concept of Schema."
},
{
"code": null,
"e": 2069,
"s": 1989,
"text": "A schema is a collection of named objects classified logically in the database."
},
{
"code": null,
"e": 2332,
"s": 2069,
"text": "In a database, you cannot create multiple database objects with same name. To do so, the schema provides a group environment. You can create multiple schemas in a database and you can create multiple database objects with same name, with different schema groups."
},
{
"code": null,
"e": 2978,
"s": 2332,
"text": "A schema can contain tables, functions, indices, tablespaces, procedures, triggers etc. For example, you create two different schemas named as “Professional” and “Personal” for an “employee” database. It is possible to make two different tables with the same name “Employee”. In this environment, one table has professional information and the other has personal information of employee. In spite of having two tables with the same name, they have two different schemas “Personal” and “Professional”. Hence, the user can work with both without encountering any problem. This feature is useful when there are constraints on the naming of tables."
},
{
"code": null,
"e": 3021,
"s": 2978,
"text": "Let us see few commands related to Schema:"
},
{
"code": null,
"e": 3029,
"s": 3021,
"text": "Syntax:"
},
{
"code": null,
"e": 3046,
"s": 3029,
"text": "db2 get schema "
},
{
"code": null,
"e": 3088,
"s": 3046,
"text": "Example: [To get current database schema]"
},
{
"code": null,
"e": 3106,
"s": 3088,
"text": "db2 get schema "
},
{
"code": null,
"e": 3114,
"s": 3106,
"text": "Syntax:"
},
{
"code": null,
"e": 3145,
"s": 3114,
"text": "db2 set schema=<schema_name> "
},
{
"code": null,
"e": 3209,
"s": 3145,
"text": "Example: [To arrange ‘schema1’ to current instance environment]"
},
{
"code": null,
"e": 3233,
"s": 3209,
"text": "db2 set schema=schema1 "
},
{
"code": null,
"e": 3290,
"s": 3233,
"text": "Syntax: [To create a new schema with authorized user id]"
},
{
"code": null,
"e": 3349,
"s": 3290,
"text": "db2 create schema <schema_name> authroization <inst_user> "
},
{
"code": null,
"e": 3414,
"s": 3349,
"text": "Example: [To create “schema1” schema authorized with ‘db2inst2”]"
},
{
"code": null,
"e": 3464,
"s": 3414,
"text": "db2 create schema schema1 authorization db2inst2 "
},
{
"code": null,
"e": 3662,
"s": 3464,
"text": "Let us create two different tables with same name but two different schemas. Here, you create employee table with two different schemas, one for personal and the other for professional information."
},
{
"code": null,
"e": 3690,
"s": 3662,
"text": "Step 1: Create two schemas."
},
{
"code": null,
"e": 3738,
"s": 3690,
"text": "Schema 1: [To create schema named professional]"
},
{
"code": null,
"e": 3793,
"s": 3738,
"text": "db2 create schema professional authorization db2inst2 "
},
{
"code": null,
"e": 3837,
"s": 3793,
"text": "Schema 2: [To create schema named personal]"
},
{
"code": null,
"e": 3887,
"s": 3837,
"text": "db2 create schema personal authorization db2inst2"
},
{
"code": null,
"e": 3953,
"s": 3887,
"text": "Step 2: Create two tables with the same name for Employee details"
},
{
"code": null,
"e": 3983,
"s": 3953,
"text": "Table1: professional.employee"
},
{
"code": null,
"e": 4067,
"s": 3983,
"text": "[To create a new table ‘employee’ in the database using schema name ‘professional’]"
},
{
"code": null,
"e": 4194,
"s": 4067,
"text": "db2 create table professional.employee(id number, name \nvarchar(20), profession varchar(20), join_date date, \nsalary number); "
},
{
"code": null,
"e": 4220,
"s": 4194,
"text": "Table2: personal.employee"
},
{
"code": null,
"e": 4305,
"s": 4220,
"text": "[To create a new table ‘employee’ in the same database, with schema name ‘personal’]"
},
{
"code": null,
"e": 4424,
"s": 4305,
"text": "db2 create table personal.employee(id number, name \nvarchar(20), d_birth date, phone bigint, address \nvarchar(200)); "
},
{
"code": null,
"e": 4527,
"s": 4424,
"text": "After executing these steps, you get two tables with same name ’employee’, with two different schemas."
},
{
"code": null,
"e": 4562,
"s": 4527,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4577,
"s": 4562,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4612,
"s": 4577,
"text": "\n 41 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4627,
"s": 4612,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 4663,
"s": 4627,
"text": "\n 53 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 4678,
"s": 4663,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 4711,
"s": 4678,
"text": "\n 33 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4726,
"s": 4711,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 4759,
"s": 4726,
"text": "\n 44 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4778,
"s": 4759,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4815,
"s": 4778,
"text": "\n 178 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 4834,
"s": 4815,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4841,
"s": 4834,
"text": " Print"
},
{
"code": null,
"e": 4852,
"s": 4841,
"text": " Add Notes"
}
] |
WebGL - Basics
|
WebGL is mostly a low-level rasterization API rather than a 3D API. To draw an image using WebGL, you have to pass a vector representing the image. It then converts the given vector into pixel format using OpenGL SL and displays the image on the screen. Writing a WebGL application involves a set of steps which
we would be explaining in this chapter.
Just like any other 3D system, you will have x, y and z axes in WebGL, where the z axis signifies depth. The coordinates in WebGL are restricted to (1, 1, 1) and (-1, -1, - 1). It means − if you consider the screen projecting WebGL graphics as a cube, then one corner of the cube will be (1, 1, 1) and the opposite corner will be (-1, -1, -1). WebGL won’t display anything that is drawn beyond these boundaries.
The following diagram depicts the WebGL coordinate system. The z-axis signifies depth. A positive value of z indicates that the object is near the screen/viewer, whereas a negative value of z indicates that the object is away from the screen. Likewise, a positive value of x indicates that the object is to the right side of the screen and a negative value indicates the object is to the left side. Similarly, positive and negative values of y indicate whether the object is at the top or at the bottom portion of the screen.
After getting the WebGL context of the canvas object, you can start drawing graphical elements using WebGL API in JavaScript.
Here are some fundamental terms you need to know before starting with WebGL.
Generally, to draw objects such as a polygon, we mark the points on the plane and join them to form a desired polygon. A vertex is a point which defines the conjunction of the edges of a 3D object. It is represented by three floating point values each representing x, y, z axes respectively.
In the following example, we are drawing a triangle with the following vertices − (0.5, 0.5), (-0.5, 0.5), (-0.5, -0.5).
Note − We have to store these vertices manually using JavaScript arrays and pass them to the WebGL rendering pipeline using vertex buffer.
In WebGL, numerical values are used to identify the vertices. These numerical values are known as indices. These indices are used to draw meshes in WebGL.
Note − Just like vertices, we store the indices using JavaScript arrays and pass them to WebGL rendering pipeline using index buffer.
Unlike OpenGL and JoGL, there are no predefined methods in WebGL to render the vertices directly. We have to store them manually using JavaScript arrays.
var vertices = [ 0.5, 0.5, 0.1,-0.5, 0.5,-0.5]
Buffers are the memory areas of WebGL that hold the data. There are various buffers namely, drawing buffer, frame buffer, vetex buffer, and index buffer. The vertex buffer and index buffer are used to describe and process the geometry of the model.
Vertex buffer objects store data about the vertices, while Index buffer objects store data about the indices. After storing the vertices into arrays, we pass them to WegGL graphics pipeline using these Buffer objects.
Frame buffer is a portion of graphics memory that hold the scene data. This buffer contains details such as width and height of the surface (in pixels), color of each pixel, depth and stencil buffers.
To draw 2D or 3D objects, the WebGL API provides two methods namely, drawArrays() and drawElements(). These two methods accept a parameter called mode using which you can select the object you want to draw. The options provided by this field are restricted to points, lines, and triangles.
To draw a 3D object using these two methods, we have to construct one or more primitive polygons using points, lines, or triangles. Thereafter, using those primitive polygons, we can form a mesh.
A 3D object drawn using primitive polygons is called a mesh. WebGL offers several ways to draw 3D graphical objects, however users normally prefer to draw a mesh.
In the following example, you can observe that we have drawn a square using two triangles→ {1, 2, 3} and {4, 1, 3}.
We normally use triangles to construct meshes. Since WebGL uses GPU accelerated computing, the information about these triangles should be transferred from CPU to GPU which takes a lot of communication overhead.
WebGL provides a solution to reduce the communication overhead. Since it uses ES SL (Embedded System Shader Language) that runs on GPU, we write all the required programs to draw graphical elements on the client system using shader programs (the programs which we write using OpenGL ES Shading Language / GLSL).
These shaders are the programs for GPU and the language used to write shader programs is GLSL. In these shaders, we define exactly how vertices, transformations, materials, lights, and camera interact with one another to create a particular image.
In short, it is a snippet that implements algorithms to get pixels for a mesh. We will discuss more about shaders in later chapters. There are two types of shaders − Vertex Shader and Fragment Shader.
Vertext shader is the program code called on every vertex. It is used to transform (move) the geometry (ex: triangle) from one place to another. It handles the data of each vertex (per-vertex data) such as vertex coordinates, normals, colors, and texture coordinates.
In the ES GL code of vertex shader, programmers have to define attributes to handle the data. These attributes point to a Vertex Buffer Object written in JavaScript.
The following tasks can be performed using vertex shaders −
Vertex transformation
Normal transformation and normalization
Texture coordinate generation
Texture coordinate transformation
Lighting
Color material application
A mesh is formed by multiple triangles, and the surface of each of the triangles is known as a fragment. Fragment shader is the code that runs on all pixels of every fragment. It is written to calculate and fill the color on individual pixels.
The following tasks can be performed using Fragment shaders −
Operations on interpolated values
Texture access
Texture application
Fog
Color sum
The full form of OpenGL ES SL is OpenGL Embedded System Shading Language. To handle the data in the shader programs, ES SL provides three types of variables. They are as follows −
Attributes − These variables hold the input values of the vertex shader program. Attributes point to the vertex buffer objects that contains per-vertex data. Each time the vertex shader is invoked, the attributes point to VBO of different vertices.
Attributes − These variables hold the input values of the vertex shader program. Attributes point to the vertex buffer objects that contains per-vertex data. Each time the vertex shader is invoked, the attributes point to VBO of different vertices.
Uniforms − These variables hold the input data that is common for both vertex and fragment shaders, such as light position, texture coordinates, and color.
Uniforms − These variables hold the input data that is common for both vertex and fragment shaders, such as light position, texture coordinates, and color.
Varyings − These variables are used to pass the data from the vertex shader to the fragment shader.
Varyings − These variables are used to pass the data from the vertex shader to the fragment shader.
With this much basics, we will now move on to discuss the Graphics Pipeline.
10 Lectures
1 hours
Frahaan Hussain
28 Lectures
4 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2399,
"s": 2047,
"text": "WebGL is mostly a low-level rasterization API rather than a 3D API. To draw an image using WebGL, you have to pass a vector representing the image. It then converts the given vector into pixel format using OpenGL SL and displays the image on the screen. Writing a WebGL application involves a set of steps which\nwe would be explaining in this chapter."
},
{
"code": null,
"e": 2811,
"s": 2399,
"text": "Just like any other 3D system, you will have x, y and z axes in WebGL, where the z axis signifies depth. The coordinates in WebGL are restricted to (1, 1, 1) and (-1, -1, - 1). It means − if you consider the screen projecting WebGL graphics as a cube, then one corner of the cube will be (1, 1, 1) and the opposite corner will be (-1, -1, -1). WebGL won’t display anything that is drawn beyond these boundaries."
},
{
"code": null,
"e": 3337,
"s": 2811,
"text": "The following diagram depicts the WebGL coordinate system. The z-axis signifies depth. A positive value of z indicates that the object is near the screen/viewer, whereas a negative value of z indicates that the object is away from the screen. Likewise, a positive value of x indicates that the object is to the right side of the screen and a negative value indicates the object is to the left side. Similarly, positive and negative values of y indicate whether the object is at the top or at the bottom portion of the screen."
},
{
"code": null,
"e": 3463,
"s": 3337,
"text": "After getting the WebGL context of the canvas object, you can start drawing graphical elements using WebGL API in JavaScript."
},
{
"code": null,
"e": 3540,
"s": 3463,
"text": "Here are some fundamental terms you need to know before starting with WebGL."
},
{
"code": null,
"e": 3832,
"s": 3540,
"text": "Generally, to draw objects such as a polygon, we mark the points on the plane and join them to form a desired polygon. A vertex is a point which defines the conjunction of the edges of a 3D object. It is represented by three floating point values each representing x, y, z axes respectively."
},
{
"code": null,
"e": 3953,
"s": 3832,
"text": "In the following example, we are drawing a triangle with the following vertices − (0.5, 0.5), (-0.5, 0.5), (-0.5, -0.5)."
},
{
"code": null,
"e": 4092,
"s": 3953,
"text": "Note − We have to store these vertices manually using JavaScript arrays and pass them to the WebGL rendering pipeline using vertex buffer."
},
{
"code": null,
"e": 4247,
"s": 4092,
"text": "In WebGL, numerical values are used to identify the vertices. These numerical values are known as indices. These indices are used to draw meshes in WebGL."
},
{
"code": null,
"e": 4381,
"s": 4247,
"text": "Note − Just like vertices, we store the indices using JavaScript arrays and pass them to WebGL rendering pipeline using index buffer."
},
{
"code": null,
"e": 4535,
"s": 4381,
"text": "Unlike OpenGL and JoGL, there are no predefined methods in WebGL to render the vertices directly. We have to store them manually using JavaScript arrays."
},
{
"code": null,
"e": 4584,
"s": 4535,
"text": "var vertices = [ 0.5, 0.5, 0.1,-0.5, 0.5,-0.5] \n"
},
{
"code": null,
"e": 4833,
"s": 4584,
"text": "Buffers are the memory areas of WebGL that hold the data. There are various buffers namely, drawing buffer, frame buffer, vetex buffer, and index buffer. The vertex buffer and index buffer are used to describe and process the geometry of the model."
},
{
"code": null,
"e": 5051,
"s": 4833,
"text": "Vertex buffer objects store data about the vertices, while Index buffer objects store data about the indices. After storing the vertices into arrays, we pass them to WegGL graphics pipeline using these Buffer objects."
},
{
"code": null,
"e": 5252,
"s": 5051,
"text": "Frame buffer is a portion of graphics memory that hold the scene data. This buffer contains details such as width and height of the surface (in pixels), color of each pixel, depth and stencil buffers."
},
{
"code": null,
"e": 5542,
"s": 5252,
"text": "To draw 2D or 3D objects, the WebGL API provides two methods namely, drawArrays() and drawElements(). These two methods accept a parameter called mode using which you can select the object you want to draw. The options provided by this field are restricted to points, lines, and triangles."
},
{
"code": null,
"e": 5738,
"s": 5542,
"text": "To draw a 3D object using these two methods, we have to construct one or more primitive polygons using points, lines, or triangles. Thereafter, using those primitive polygons, we can form a mesh."
},
{
"code": null,
"e": 5901,
"s": 5738,
"text": "A 3D object drawn using primitive polygons is called a mesh. WebGL offers several ways to draw 3D graphical objects, however users normally prefer to draw a mesh."
},
{
"code": null,
"e": 6017,
"s": 5901,
"text": "In the following example, you can observe that we have drawn a square using two triangles→ {1, 2, 3} and {4, 1, 3}."
},
{
"code": null,
"e": 6229,
"s": 6017,
"text": "We normally use triangles to construct meshes. Since WebGL uses GPU accelerated computing, the information about these triangles should be transferred from CPU to GPU which takes a lot of communication overhead."
},
{
"code": null,
"e": 6541,
"s": 6229,
"text": "WebGL provides a solution to reduce the communication overhead. Since it uses ES SL (Embedded System Shader Language) that runs on GPU, we write all the required programs to draw graphical elements on the client system using shader programs (the programs which we write using OpenGL ES Shading Language / GLSL)."
},
{
"code": null,
"e": 6789,
"s": 6541,
"text": "These shaders are the programs for GPU and the language used to write shader programs is GLSL. In these shaders, we define exactly how vertices, transformations, materials, lights, and camera interact with one another to create a particular image."
},
{
"code": null,
"e": 6990,
"s": 6789,
"text": "In short, it is a snippet that implements algorithms to get pixels for a mesh. We will discuss more about shaders in later chapters. There are two types of shaders − Vertex Shader and Fragment Shader."
},
{
"code": null,
"e": 7258,
"s": 6990,
"text": "Vertext shader is the program code called on every vertex. It is used to transform (move) the geometry (ex: triangle) from one place to another. It handles the data of each vertex (per-vertex data) such as vertex coordinates, normals, colors, and texture coordinates."
},
{
"code": null,
"e": 7424,
"s": 7258,
"text": "In the ES GL code of vertex shader, programmers have to define attributes to handle the data. These attributes point to a Vertex Buffer Object written in JavaScript."
},
{
"code": null,
"e": 7484,
"s": 7424,
"text": "The following tasks can be performed using vertex shaders −"
},
{
"code": null,
"e": 7506,
"s": 7484,
"text": "Vertex transformation"
},
{
"code": null,
"e": 7546,
"s": 7506,
"text": "Normal transformation and normalization"
},
{
"code": null,
"e": 7576,
"s": 7546,
"text": "Texture coordinate generation"
},
{
"code": null,
"e": 7610,
"s": 7576,
"text": "Texture coordinate transformation"
},
{
"code": null,
"e": 7619,
"s": 7610,
"text": "Lighting"
},
{
"code": null,
"e": 7646,
"s": 7619,
"text": "Color material application"
},
{
"code": null,
"e": 7890,
"s": 7646,
"text": "A mesh is formed by multiple triangles, and the surface of each of the triangles is known as a fragment. Fragment shader is the code that runs on all pixels of every fragment. It is written to calculate and fill the color on individual pixels."
},
{
"code": null,
"e": 7952,
"s": 7890,
"text": "The following tasks can be performed using Fragment shaders −"
},
{
"code": null,
"e": 7986,
"s": 7952,
"text": "Operations on interpolated values"
},
{
"code": null,
"e": 8001,
"s": 7986,
"text": "Texture access"
},
{
"code": null,
"e": 8021,
"s": 8001,
"text": "Texture application"
},
{
"code": null,
"e": 8025,
"s": 8021,
"text": "Fog"
},
{
"code": null,
"e": 8035,
"s": 8025,
"text": "Color sum"
},
{
"code": null,
"e": 8215,
"s": 8035,
"text": "The full form of OpenGL ES SL is OpenGL Embedded System Shading Language. To handle the data in the shader programs, ES SL provides three types of variables. They are as follows −"
},
{
"code": null,
"e": 8464,
"s": 8215,
"text": "Attributes − These variables hold the input values of the vertex shader program. Attributes point to the vertex buffer objects that contains per-vertex data. Each time the vertex shader is invoked, the attributes point to VBO of different vertices."
},
{
"code": null,
"e": 8713,
"s": 8464,
"text": "Attributes − These variables hold the input values of the vertex shader program. Attributes point to the vertex buffer objects that contains per-vertex data. Each time the vertex shader is invoked, the attributes point to VBO of different vertices."
},
{
"code": null,
"e": 8869,
"s": 8713,
"text": "Uniforms − These variables hold the input data that is common for both vertex and fragment shaders, such as light position, texture coordinates, and color."
},
{
"code": null,
"e": 9025,
"s": 8869,
"text": "Uniforms − These variables hold the input data that is common for both vertex and fragment shaders, such as light position, texture coordinates, and color."
},
{
"code": null,
"e": 9125,
"s": 9025,
"text": "Varyings − These variables are used to pass the data from the vertex shader to the fragment shader."
},
{
"code": null,
"e": 9225,
"s": 9125,
"text": "Varyings − These variables are used to pass the data from the vertex shader to the fragment shader."
},
{
"code": null,
"e": 9302,
"s": 9225,
"text": "With this much basics, we will now move on to discuss the Graphics Pipeline."
},
{
"code": null,
"e": 9335,
"s": 9302,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9352,
"s": 9335,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9385,
"s": 9352,
"text": "\n 28 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 9402,
"s": 9385,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9409,
"s": 9402,
"text": " Print"
},
{
"code": null,
"e": 9420,
"s": 9409,
"text": " Add Notes"
}
] |
Redis - Transactions
|
Redis transactions allow the execution of a group of commands in a single step. Following are the two properties of Transactions.
All commands in a transaction are sequentially executed as a single isolated operation. It is not possible that a request issued by another client is served in the middle of the execution of a Redis transaction.
All commands in a transaction are sequentially executed as a single isolated operation. It is not possible that a request issued by another client is served in the middle of the execution of a Redis transaction.
Redis transaction is also atomic. Atomic means either all of the commands or none are processed.
Redis transaction is also atomic. Atomic means either all of the commands or none are processed.
Redis transaction is initiated by command MULTI and then you need to pass a list of commands that should be executed in the transaction, after which the entire transaction is executed by EXEC command.
redis 127.0.0.1:6379> MULTI
OK
List of commands here
redis 127.0.0.1:6379> EXEC
Following example explains how Redis transaction can be initiated and executed.
redis 127.0.0.1:6379> MULTI
OK
redis 127.0.0.1:6379> SET tutorial redis
QUEUED
redis 127.0.0.1:6379> GET tutorial
QUEUED
redis 127.0.0.1:6379> INCR visitors
QUEUED
redis 127.0.0.1:6379> EXEC
1) OK
2) "redis"
3) (integer) 1
Following table shows some basic commands related to Redis transactions.
Discards all commands issued after MULTI
Executes all commands issued after MULTI
Marks the start of a transaction block
Forgets about all watched keys
Watches the given keys to determine the execution of the MULTI/EXEC block
22 Lectures
40 mins
Skillbakerystudios
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2175,
"s": 2045,
"text": "Redis transactions allow the execution of a group of commands in a single step. Following are the two properties of Transactions."
},
{
"code": null,
"e": 2387,
"s": 2175,
"text": "All commands in a transaction are sequentially executed as a single isolated operation. It is not possible that a request issued by another client is served in the middle of the execution of a Redis transaction."
},
{
"code": null,
"e": 2599,
"s": 2387,
"text": "All commands in a transaction are sequentially executed as a single isolated operation. It is not possible that a request issued by another client is served in the middle of the execution of a Redis transaction."
},
{
"code": null,
"e": 2696,
"s": 2599,
"text": "Redis transaction is also atomic. Atomic means either all of the commands or none are processed."
},
{
"code": null,
"e": 2793,
"s": 2696,
"text": "Redis transaction is also atomic. Atomic means either all of the commands or none are processed."
},
{
"code": null,
"e": 2994,
"s": 2793,
"text": "Redis transaction is initiated by command MULTI and then you need to pass a list of commands that should be executed in the transaction, after which the entire transaction is executed by EXEC command."
},
{
"code": null,
"e": 3078,
"s": 2994,
"text": "redis 127.0.0.1:6379> MULTI \nOK \nList of commands here \nredis 127.0.0.1:6379> EXEC\n"
},
{
"code": null,
"e": 3158,
"s": 3078,
"text": "Following example explains how Redis transaction can be initiated and executed."
},
{
"code": null,
"e": 3395,
"s": 3158,
"text": "redis 127.0.0.1:6379> MULTI \nOK \nredis 127.0.0.1:6379> SET tutorial redis \nQUEUED \nredis 127.0.0.1:6379> GET tutorial \nQUEUED \nredis 127.0.0.1:6379> INCR visitors \nQUEUED \nredis 127.0.0.1:6379> EXEC \n1) OK \n2) \"redis\" \n3) (integer) 1 \n"
},
{
"code": null,
"e": 3468,
"s": 3395,
"text": "Following table shows some basic commands related to Redis transactions."
},
{
"code": null,
"e": 3509,
"s": 3468,
"text": "Discards all commands issued after MULTI"
},
{
"code": null,
"e": 3550,
"s": 3509,
"text": "Executes all commands issued after MULTI"
},
{
"code": null,
"e": 3589,
"s": 3550,
"text": "Marks the start of a transaction block"
},
{
"code": null,
"e": 3620,
"s": 3589,
"text": "Forgets about all watched keys"
},
{
"code": null,
"e": 3694,
"s": 3620,
"text": "Watches the given keys to determine the execution of the MULTI/EXEC block"
},
{
"code": null,
"e": 3726,
"s": 3694,
"text": "\n 22 Lectures \n 40 mins\n"
},
{
"code": null,
"e": 3746,
"s": 3726,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 3753,
"s": 3746,
"text": " Print"
},
{
"code": null,
"e": 3764,
"s": 3753,
"text": " Add Notes"
}
] |
How to Compare Large Files. Learn how to use Python to compare big... | by Costas Andreou | Towards Data Science
|
In this blog, we are going to learn how to compare two large files together while creating a quick and meaningful summary of the differences. I’ve structured this blog in such a way that you can follow a step by step guide in the end to end solution.
In general, comparing two data sets is not very difficult. The main difficulty comes from being able to gain quick, meaningful insights. Although the aforementioned difficulty can be solved quickly with the likes of a pre-existing comparison library such as dataComPy, the problem is amplified when the data becomes so large, that it cannot be held into memory.
towardsdatascience.com
To my disappointment, I could not find an existing data comparison library that would handle larger data sets. All the ones I found required all of the data to be in memory.
Seeing this as a problem to be solved, I began looking into the best way to solve this problem.
To help identify the solution, I started by clearly defining the problem. I wanted to be able to compare large files. The problem was that the data was so big that I couldn’t hold all of it in memory. I also wanted the solution to be a simple one.
A problem well stated is a problem half solved.
— Charles Kettering
One way I considered of solving this problem was to partially load things in memory. That would imply comparing data that was in memory; parking what was matched and what wasn’t (off-memory), and then moving onto more data. These types of operations are a complete logistical nightmare, with complex logic of keeping track of everything.
I was hoping that there would have been an easier way of doing things. Hold and behold; another idea came to me. What if I used a SQL database to carry out all my comparisons.
After all, isn’t that the primary purpose of databases? Hold data and carry out data-centric operations quickly?
I wanted the results of the comparison to be easy to digest and provide meaningful insights. That meant that I was more interested in a quick summary, and some example comparison breaks. I could always deep-dive into the data if I needed to.
towardsdatascience.com
So, how would it work?
Before we run the full comparison, we should quickly see if the files are 100% alike. To do that, we can do a checksum.
import hashlibdef sha1(fname): sha1hash = hashlib.sha1() with open(fname) as handle: #opening the file one line at a time for memory considerations for line in handle: sha1hash.update(line.encode('utf-8')) return(sha1hash.hexdigest()) def comparefiles(files,datakey): print('########################################') print('Checking the files\' hash.') if sha1(files[0]) == sha1(files[1]): print('100% Match') else: print('Hash not matched. Proceeding to detailed checks.')comparefiles(files, datakey)
Looking into the above script closely, we essentially load the files line by line and work out their SHA1 output. This is then compared between the two files.
To run the above script, we simply have to pass in:
comparefiles(['path2file1', 'path2file2'], '')
Assuming there are differences between the files, then we would like to know whether the differences are in the number of records or their values. Hence we can look into doing some quick counts.
medium.com
To begin with, we need to load the data into SQL without exceeding our available memory and create indexes to speed up our query operations.
From the below script, you can see that we first need to define our inputs:
files: A list of the file path to the two files we want to compare
colsep: A list of the delimiter of each of the two files
data key: A list of the keys of our data set
conn: The connection we will be using for the comparison; it can either be in memory or a physical DB
The only other thing to note from the below script is that we are loading the file chunk by chunk to avoid running out of memory, and we are replacing any column spaces with underscores.
import sqlite3, pandas as pd#################Set Up#############files = [r'C:\Temp\FL_insurance.csv', r'C:\temp\FL_insurance - Copy.csv']colsep = [',',',']datakey = ['policyID', 'statecode', 'county']conn = sqlite3.connect(':memory:')#conn = sqlite3.connect('meh.sqlite3')#####################################cur = conn.cursor()static = ['Table1','Table2']def loadDataToSQL(files, static): chunksize = 10000 i=0 createindexfortable = lambda a, b : f'CREATE INDEX {a} Index ON {b} ({a})' for file in files: i = i+1 for chunk in pd.read_csv(file, chunksize=chunksize, delimiter=colsep[i-1]): #load the file in chunks in case its too big chunk.columns = chunk.columns.str.replace(' ', '_') #replacing spaces with underscores for column names chunk.to_sql(name= static[i-1], con=conn, if_exists='append') for item in datakey: #create indexes so it runs faster createindexfortable(item, 'Table1') createindexfortable(item, 'Table2')
Given the data is now all loaded into the SQL DB, the next thing to do is carry out the counts. To control the execution and output of our commands, we can create a function we can call.
def returnSQLresults(statement, noprint = 0): cur.execute(statement) i=0 temp = [] for row in cur: if noprint == 0 and len(row) > 1: if i == 0: #if there are multiple records, only print the header once names = list(map(lambda x: x[0], cur.description)) #column names print(names) print(row) else: temp.append(row) i=i+1 if noprint == 1 and i != 0: return(temp) elif i==0: return(None)
Breaking down the above script:
We check if there are any results returned in our cursor and if noprint has been definednoprint essentially causes the function to return the data rather than printIf the cursor returns any results, we print the column names from the results before we print anything
We check if there are any results returned in our cursor and if noprint has been defined
noprint essentially causes the function to return the data rather than print
If the cursor returns any results, we print the column names from the results before we print anything
And with the above set up, we can now begin our comparison operations.
It is now time that we leverage all of the functions we have defined this far in our programme, to start building a data comparison summary. Let us then get a glimpse through the total counts by defining a new function that we can call.
def SQLComp(files, keys, compDegree): print('########################################') print('Checking Counts across the two data sets:') print('Total Counts') statement_counts = '''SELECT "Table1" AS "TABLE", COUNT(1) FROM Table1 UNION SELECT "Table2" AS "TABLE", COUNT(1) FROM Table2''' returnSQLresults(statement_counts)
At this point, we know the two files are not matching 100%, and we also know the counts of each file. We now need to look a bit deeper and understand if any of the entries are not matching on our pre-defined key.
That is, we need to do a FULL OUTER JOIN, and highlight records that are either not in one file or the other (as per our pre-defined key). Technically speaking, the SQL query to do this sort of join is not complex; however, as we want the query to be generated automagically from our inputs, we need to get creative.
To do so, I have employed a loop and f strings. Let us look at this in more detail.
def SQLComp(files, keys, compDegree): for key in keys: if key == keys[0]: joinstatement = f'x.{key} = y.{key}' wherestatement = f' WHERE y.{key} IS NULL' wherenotstatement = f' WHERE y.{key} IS NOT NULL' else: joinstatement += f' AND x.{key} = y.{key}' wherestatement += f' AND y.{key} IS NULL' wherenotstatement += f' AND y.{key} IS NOT NULL'print('########################################') print('Checking Rows based on data Key.') statement1 = f'''SELECT * FROM Table1 x LEFT JOIN Table2 y ON {joinstatement} {wherestatement}''' statement2 = f'''SELECT * FROM Table2 x LEFT JOIN Table1 y ON {joinstatement} {wherestatement}''' if returnSQLresults(statement1) is None and returnSQLresults(statement2) is None: print('No differences found.') else: print('Data in file 1, but not in file 2') returnSQLresults(statement1) print('Data in file 2, but not in file 1') returnSQLresults(statement2)
We achieve the full outer join, by doing a LEFT and RIGHT join, highlighting orphaned entries at each point.
Next up, is a columns check. We want to know if any of the files have differences in their headers.
We can retrieve headers in SQLite through PRAGMA command, so this is relatively straight forward.
def SQLComp(files, keys, compDegree): print('########################################') print('Checking Columns between the two files.') statement3 = lambda a : 'PRAGMA TABLE_INFO(' + a + ')' statement3Table1results = returnSQLresults(statement3('Table1'),1) statement3Table2results = returnSQLresults(statement3('Table2'),1) if (statement3Table1results == statement3Table2results): print('No differences found.') else: print('Columns in one but not the other.') print(set(statement3Table1results)-set(statement3Table2results))
The only thing worth highlighting here is the employment of the subtraction operation on Sets, which allows me to compare lists quickly.
Following the above checks, we now want to start exploring some of the value differences. To do so, we first want to determine the columns in common between the two files, which will then allow us to compare them.
def list2csv(l1): for i, item in enumerate(l1): if i == 0: csvlist = 'x.' + item else: csvlist += ', x.'+ item return(csvlist)def SQLComp(files, keys, compDegree): print('########################################') print('Differences identified in the following columns.') columnsInCommon1 = list(set(statement3Table1results).intersection(set(statement3Table2results))) columnsInCommon = [] for cols in columnsInCommon1: columnsInCommon.append(cols[1]) columnsInCommon.remove('index') cols2select = list2csv(datakey)for item in columnsInCommon: statement4 = f'''SELECT {cols2select}, x.{item}, y.{item} FROM Table1 x JOIN Table2 y ON {joinstatement} {wherenotstatement} AND x.{item} <> y.{item}''' returnSQLresults(statement4)
To help me test the above script and showcase the results, I have taken a sample data file, cloned it and made some changes. You can see the differences here:
You can see that I changed one value under the header construction, and removed one of the columns.
Running the script, returned the following:
########################################Checking the files' hash.Hash not matched. Proceeding to detailed checks.########################################Checking Counts across the two data sets:Total Counts['TABLE', 'COUNT(1)']('Table1', 36633)('Table2', 36633)########################################Checking Rows based on data Key.No differences found.########################################Checking Columns between the two files.Columns in one but not the other.{(18, 'point_granularity', 'INTEGER', 0, None, 0)}########################################Differences identified in the following columns.['policyID', 'statecode', 'county', 'construction', 'construction'](448094, 'FL', 'CLAY COUNTY', 'Masonry', 'wut')
In conclusion, the above script allows you to compare large data sets together that you wouldn’t be able to hold in memory while providing you with a nice summary view at the end.
It could easily be extended in the future in the following ways:
The Detailed value comparison can be extended to be a list per data key, rather than returning multiple lines of results
Include an Ignore flag for specific attributes
Have a tolerance introduced (absolute, relative)
Include a UI
I will endeavour to extend this if I continue to use it, but please feel free to extend it yourselves or comment your suggestions.
import hashlib, sqlite3, pandas as pdconn = sqlite3.connect(':memory:')#conn = sqlite3.connect('meh.sqlite3')cur = conn.cursor()files = [r'C:\Temp\FL_insurance.csv', r'C:\temp\FL_insurance - Copy.csv']colsep = [',',',']datakey = ['policyID', 'statecode', 'county']static = ['Table1','Table2']def list2csv(l1): for i, item in enumerate(l1): if i == 0: csvlist = 'x.' + item else: csvlist += ', x.'+ item return(csvlist)def sha1(fname): sha1hash = hashlib.sha1() with open(fname) as handle: #opening the file one line at a time for memory considerations for line in handle: sha1hash.update(line.encode('utf-8')) return(sha1hash.hexdigest())def loadDataToSQL(files, static): chunksize = 10000 i=0 createindexfortable = lambda a, b : f'CREATE INDEX {a} Index ON {b} ({a})' for file in files: i = i+1 for chunk in pd.read_csv(file, chunksize=chunksize, delimiter=colsep[i-1]): #load the file in chunks in case its too big chunk.columns = chunk.columns.str.replace(' ', '_') #replacing spaces with underscores for column names chunk.to_sql(name= static[i-1], con=conn, if_exists='append') for item in datakey: #create indexes so it runs faster createindexfortable(item, 'Table1') createindexfortable(item, 'Table2')def returnSQLresults(statement, noprint = 0): cur.execute(statement) i=0 temp = [] for row in cur: if noprint == 0 and len(row) > 1: if i == 0: #if there are multiple records, only print the header once names = list(map(lambda x: x[0], cur.description)) #column names print(names) print(row) else: temp.append(row) i=i+1 if noprint == 1 and i != 0: return(temp) elif i==0: return(None)def sha1(fname): sha1hash = hashlib.sha1() with open(fname) as handle: #opening the file one line at a time for memory considerations for line in handle: sha1hash.update(line.encode('utf-8')) return(sha1hash.hexdigest())def SQLComp(files, keys, compDegree): for key in keys: if key == keys[0]: joinstatement = f'x.{key} = y.{key}' wherestatement = f' WHERE y.{key} IS NULL' wherenotstatement = f' WHERE y.{key} IS NOT NULL' else: joinstatement += f' AND x.{key} = y.{key}' wherestatement += f' AND y.{key} IS NULL' wherenotstatement += f' AND y.{key} IS NOT NULL' print('########################################') print('Checking Counts across the two data sets:') print('Total Counts') statement_counts = '''SELECT "Table1" AS "TABLE", COUNT(1) FROM Table1 UNION SELECT "Table2" AS "TABLE", COUNT(1) FROM Table2''' returnSQLresults(statement_counts) print('########################################') print('Checking Rows based on data Key.') statement1 = f'''SELECT * FROM Table1 x LEFT JOIN Table2 y ON {joinstatement} {wherestatement}''' statement2 = f'''SELECT * FROM Table2 x LEFT JOIN Table1 y ON {joinstatement} {wherestatement}''' if returnSQLresults(statement1) is None and returnSQLresults(statement2) is None: print('No differences found.') else: print('Data in file 1, but not in file 2') returnSQLresults(statement1) print('Data in file 2, but not in file 1') returnSQLresults(statement2) print('########################################') print('Checking Columns between the two files.') #statement3 = 'PRAGMA table_info(Table1);' statement3 = lambda a : 'PRAGMA TABLE_INFO(' + a + ')' statement3Table1results = returnSQLresults(statement3('Table1'),1) statement3Table2results = returnSQLresults(statement3('Table2'),1) if (statement3Table1results == statement3Table2results): print('No differences found.') else: print('Columns in one but not the other.') print(set(statement3Table1results)-set(statement3Table2results)) print('########################################') print('Differences identified in the following columns.') columnsInCommon1 = list(set(statement3Table1results).intersection(set(statement3Table2results))) columnsInCommon = [] for cols in columnsInCommon1: columnsInCommon.append(cols[1]) columnsInCommon.remove('index') cols2select = list2csv(datakey) for item in columnsInCommon: statement4 = f'''SELECT {cols2select}, x.{item}, y.{item} FROM Table1 x JOIN Table2 y ON {joinstatement} {wherenotstatement} AND x.{item} <> y.{item}''' returnSQLresults(statement4) #print(statement4)def comparefiles(files,datakey): print('########################################') print('Checking the files\' hash.') if sha1(files[0]) == sha1(files[1]): print('100% Match') else: print('Hash not matched. Proceeding to detailed checks.') loadDataToSQL(files, static) SQLComp(files, datakey, [])comparefiles(files, datakey)
If you liked this story, you might also like:
|
[
{
"code": null,
"e": 423,
"s": 172,
"text": "In this blog, we are going to learn how to compare two large files together while creating a quick and meaningful summary of the differences. I’ve structured this blog in such a way that you can follow a step by step guide in the end to end solution."
},
{
"code": null,
"e": 785,
"s": 423,
"text": "In general, comparing two data sets is not very difficult. The main difficulty comes from being able to gain quick, meaningful insights. Although the aforementioned difficulty can be solved quickly with the likes of a pre-existing comparison library such as dataComPy, the problem is amplified when the data becomes so large, that it cannot be held into memory."
},
{
"code": null,
"e": 808,
"s": 785,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 982,
"s": 808,
"text": "To my disappointment, I could not find an existing data comparison library that would handle larger data sets. All the ones I found required all of the data to be in memory."
},
{
"code": null,
"e": 1078,
"s": 982,
"text": "Seeing this as a problem to be solved, I began looking into the best way to solve this problem."
},
{
"code": null,
"e": 1326,
"s": 1078,
"text": "To help identify the solution, I started by clearly defining the problem. I wanted to be able to compare large files. The problem was that the data was so big that I couldn’t hold all of it in memory. I also wanted the solution to be a simple one."
},
{
"code": null,
"e": 1374,
"s": 1326,
"text": "A problem well stated is a problem half solved."
},
{
"code": null,
"e": 1394,
"s": 1374,
"text": "— Charles Kettering"
},
{
"code": null,
"e": 1732,
"s": 1394,
"text": "One way I considered of solving this problem was to partially load things in memory. That would imply comparing data that was in memory; parking what was matched and what wasn’t (off-memory), and then moving onto more data. These types of operations are a complete logistical nightmare, with complex logic of keeping track of everything."
},
{
"code": null,
"e": 1908,
"s": 1732,
"text": "I was hoping that there would have been an easier way of doing things. Hold and behold; another idea came to me. What if I used a SQL database to carry out all my comparisons."
},
{
"code": null,
"e": 2021,
"s": 1908,
"text": "After all, isn’t that the primary purpose of databases? Hold data and carry out data-centric operations quickly?"
},
{
"code": null,
"e": 2263,
"s": 2021,
"text": "I wanted the results of the comparison to be easy to digest and provide meaningful insights. That meant that I was more interested in a quick summary, and some example comparison breaks. I could always deep-dive into the data if I needed to."
},
{
"code": null,
"e": 2286,
"s": 2263,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2309,
"s": 2286,
"text": "So, how would it work?"
},
{
"code": null,
"e": 2429,
"s": 2309,
"text": "Before we run the full comparison, we should quickly see if the files are 100% alike. To do that, we can do a checksum."
},
{
"code": null,
"e": 2988,
"s": 2429,
"text": "import hashlibdef sha1(fname): sha1hash = hashlib.sha1() with open(fname) as handle: #opening the file one line at a time for memory considerations for line in handle: sha1hash.update(line.encode('utf-8')) return(sha1hash.hexdigest()) def comparefiles(files,datakey): print('########################################') print('Checking the files\\' hash.') if sha1(files[0]) == sha1(files[1]): print('100% Match') else: print('Hash not matched. Proceeding to detailed checks.')comparefiles(files, datakey)"
},
{
"code": null,
"e": 3147,
"s": 2988,
"text": "Looking into the above script closely, we essentially load the files line by line and work out their SHA1 output. This is then compared between the two files."
},
{
"code": null,
"e": 3199,
"s": 3147,
"text": "To run the above script, we simply have to pass in:"
},
{
"code": null,
"e": 3246,
"s": 3199,
"text": "comparefiles(['path2file1', 'path2file2'], '')"
},
{
"code": null,
"e": 3441,
"s": 3246,
"text": "Assuming there are differences between the files, then we would like to know whether the differences are in the number of records or their values. Hence we can look into doing some quick counts."
},
{
"code": null,
"e": 3452,
"s": 3441,
"text": "medium.com"
},
{
"code": null,
"e": 3593,
"s": 3452,
"text": "To begin with, we need to load the data into SQL without exceeding our available memory and create indexes to speed up our query operations."
},
{
"code": null,
"e": 3669,
"s": 3593,
"text": "From the below script, you can see that we first need to define our inputs:"
},
{
"code": null,
"e": 3736,
"s": 3669,
"text": "files: A list of the file path to the two files we want to compare"
},
{
"code": null,
"e": 3793,
"s": 3736,
"text": "colsep: A list of the delimiter of each of the two files"
},
{
"code": null,
"e": 3838,
"s": 3793,
"text": "data key: A list of the keys of our data set"
},
{
"code": null,
"e": 3940,
"s": 3838,
"text": "conn: The connection we will be using for the comparison; it can either be in memory or a physical DB"
},
{
"code": null,
"e": 4127,
"s": 3940,
"text": "The only other thing to note from the below script is that we are loading the file chunk by chunk to avoid running out of memory, and we are replacing any column spaces with underscores."
},
{
"code": null,
"e": 5121,
"s": 4127,
"text": "import sqlite3, pandas as pd#################Set Up#############files = [r'C:\\Temp\\FL_insurance.csv', r'C:\\temp\\FL_insurance - Copy.csv']colsep = [',',',']datakey = ['policyID', 'statecode', 'county']conn = sqlite3.connect(':memory:')#conn = sqlite3.connect('meh.sqlite3')#####################################cur = conn.cursor()static = ['Table1','Table2']def loadDataToSQL(files, static): chunksize = 10000 i=0 createindexfortable = lambda a, b : f'CREATE INDEX {a} Index ON {b} ({a})' for file in files: i = i+1 for chunk in pd.read_csv(file, chunksize=chunksize, delimiter=colsep[i-1]): #load the file in chunks in case its too big chunk.columns = chunk.columns.str.replace(' ', '_') #replacing spaces with underscores for column names chunk.to_sql(name= static[i-1], con=conn, if_exists='append') for item in datakey: #create indexes so it runs faster createindexfortable(item, 'Table1') createindexfortable(item, 'Table2')"
},
{
"code": null,
"e": 5308,
"s": 5121,
"text": "Given the data is now all loaded into the SQL DB, the next thing to do is carry out the counts. To control the execution and output of our commands, we can create a function we can call."
},
{
"code": null,
"e": 5803,
"s": 5308,
"text": "def returnSQLresults(statement, noprint = 0): cur.execute(statement) i=0 temp = [] for row in cur: if noprint == 0 and len(row) > 1: if i == 0: #if there are multiple records, only print the header once names = list(map(lambda x: x[0], cur.description)) #column names print(names) print(row) else: temp.append(row) i=i+1 if noprint == 1 and i != 0: return(temp) elif i==0: return(None)"
},
{
"code": null,
"e": 5835,
"s": 5803,
"text": "Breaking down the above script:"
},
{
"code": null,
"e": 6102,
"s": 5835,
"text": "We check if there are any results returned in our cursor and if noprint has been definednoprint essentially causes the function to return the data rather than printIf the cursor returns any results, we print the column names from the results before we print anything"
},
{
"code": null,
"e": 6191,
"s": 6102,
"text": "We check if there are any results returned in our cursor and if noprint has been defined"
},
{
"code": null,
"e": 6268,
"s": 6191,
"text": "noprint essentially causes the function to return the data rather than print"
},
{
"code": null,
"e": 6371,
"s": 6268,
"text": "If the cursor returns any results, we print the column names from the results before we print anything"
},
{
"code": null,
"e": 6442,
"s": 6371,
"text": "And with the above set up, we can now begin our comparison operations."
},
{
"code": null,
"e": 6679,
"s": 6442,
"text": "It is now time that we leverage all of the functions we have defined this far in our programme, to start building a data comparison summary. Let us then get a glimpse through the total counts by defining a new function that we can call."
},
{
"code": null,
"e": 7173,
"s": 6679,
"text": "def SQLComp(files, keys, compDegree): print('########################################') print('Checking Counts across the two data sets:') print('Total Counts') statement_counts = '''SELECT \"Table1\" AS \"TABLE\", COUNT(1) FROM Table1 UNION SELECT \"Table2\" AS \"TABLE\", COUNT(1) FROM Table2''' returnSQLresults(statement_counts)"
},
{
"code": null,
"e": 7386,
"s": 7173,
"text": "At this point, we know the two files are not matching 100%, and we also know the counts of each file. We now need to look a bit deeper and understand if any of the entries are not matching on our pre-defined key."
},
{
"code": null,
"e": 7703,
"s": 7386,
"text": "That is, we need to do a FULL OUTER JOIN, and highlight records that are either not in one file or the other (as per our pre-defined key). Technically speaking, the SQL query to do this sort of join is not complex; however, as we want the query to be generated automagically from our inputs, we need to get creative."
},
{
"code": null,
"e": 7787,
"s": 7703,
"text": "To do so, I have employed a loop and f strings. Let us look at this in more detail."
},
{
"code": null,
"e": 8881,
"s": 7787,
"text": "def SQLComp(files, keys, compDegree): for key in keys: if key == keys[0]: joinstatement = f'x.{key} = y.{key}' wherestatement = f' WHERE y.{key} IS NULL' wherenotstatement = f' WHERE y.{key} IS NOT NULL' else: joinstatement += f' AND x.{key} = y.{key}' wherestatement += f' AND y.{key} IS NULL' wherenotstatement += f' AND y.{key} IS NOT NULL'print('########################################') print('Checking Rows based on data Key.') statement1 = f'''SELECT * FROM Table1 x LEFT JOIN Table2 y ON {joinstatement} {wherestatement}''' statement2 = f'''SELECT * FROM Table2 x LEFT JOIN Table1 y ON {joinstatement} {wherestatement}''' if returnSQLresults(statement1) is None and returnSQLresults(statement2) is None: print('No differences found.') else: print('Data in file 1, but not in file 2') returnSQLresults(statement1) print('Data in file 2, but not in file 1') returnSQLresults(statement2)"
},
{
"code": null,
"e": 8990,
"s": 8881,
"text": "We achieve the full outer join, by doing a LEFT and RIGHT join, highlighting orphaned entries at each point."
},
{
"code": null,
"e": 9090,
"s": 8990,
"text": "Next up, is a columns check. We want to know if any of the files have differences in their headers."
},
{
"code": null,
"e": 9188,
"s": 9090,
"text": "We can retrieve headers in SQLite through PRAGMA command, so this is relatively straight forward."
},
{
"code": null,
"e": 9758,
"s": 9188,
"text": "def SQLComp(files, keys, compDegree): print('########################################') print('Checking Columns between the two files.') statement3 = lambda a : 'PRAGMA TABLE_INFO(' + a + ')' statement3Table1results = returnSQLresults(statement3('Table1'),1) statement3Table2results = returnSQLresults(statement3('Table2'),1) if (statement3Table1results == statement3Table2results): print('No differences found.') else: print('Columns in one but not the other.') print(set(statement3Table1results)-set(statement3Table2results))"
},
{
"code": null,
"e": 9895,
"s": 9758,
"text": "The only thing worth highlighting here is the employment of the subtraction operation on Sets, which allows me to compare lists quickly."
},
{
"code": null,
"e": 10109,
"s": 9895,
"text": "Following the above checks, we now want to start exploring some of the value differences. To do so, we first want to determine the columns in common between the two files, which will then allow us to compare them."
},
{
"code": null,
"e": 10961,
"s": 10109,
"text": "def list2csv(l1): for i, item in enumerate(l1): if i == 0: csvlist = 'x.' + item else: csvlist += ', x.'+ item return(csvlist)def SQLComp(files, keys, compDegree): print('########################################') print('Differences identified in the following columns.') columnsInCommon1 = list(set(statement3Table1results).intersection(set(statement3Table2results))) columnsInCommon = [] for cols in columnsInCommon1: columnsInCommon.append(cols[1]) columnsInCommon.remove('index') cols2select = list2csv(datakey)for item in columnsInCommon: statement4 = f'''SELECT {cols2select}, x.{item}, y.{item} FROM Table1 x JOIN Table2 y ON {joinstatement} {wherenotstatement} AND x.{item} <> y.{item}''' returnSQLresults(statement4)"
},
{
"code": null,
"e": 11120,
"s": 10961,
"text": "To help me test the above script and showcase the results, I have taken a sample data file, cloned it and made some changes. You can see the differences here:"
},
{
"code": null,
"e": 11220,
"s": 11120,
"text": "You can see that I changed one value under the header construction, and removed one of the columns."
},
{
"code": null,
"e": 11264,
"s": 11220,
"text": "Running the script, returned the following:"
},
{
"code": null,
"e": 11983,
"s": 11264,
"text": "########################################Checking the files' hash.Hash not matched. Proceeding to detailed checks.########################################Checking Counts across the two data sets:Total Counts['TABLE', 'COUNT(1)']('Table1', 36633)('Table2', 36633)########################################Checking Rows based on data Key.No differences found.########################################Checking Columns between the two files.Columns in one but not the other.{(18, 'point_granularity', 'INTEGER', 0, None, 0)}########################################Differences identified in the following columns.['policyID', 'statecode', 'county', 'construction', 'construction'](448094, 'FL', 'CLAY COUNTY', 'Masonry', 'wut')"
},
{
"code": null,
"e": 12163,
"s": 11983,
"text": "In conclusion, the above script allows you to compare large data sets together that you wouldn’t be able to hold in memory while providing you with a nice summary view at the end."
},
{
"code": null,
"e": 12228,
"s": 12163,
"text": "It could easily be extended in the future in the following ways:"
},
{
"code": null,
"e": 12349,
"s": 12228,
"text": "The Detailed value comparison can be extended to be a list per data key, rather than returning multiple lines of results"
},
{
"code": null,
"e": 12396,
"s": 12349,
"text": "Include an Ignore flag for specific attributes"
},
{
"code": null,
"e": 12445,
"s": 12396,
"text": "Have a tolerance introduced (absolute, relative)"
},
{
"code": null,
"e": 12458,
"s": 12445,
"text": "Include a UI"
},
{
"code": null,
"e": 12589,
"s": 12458,
"text": "I will endeavour to extend this if I continue to use it, but please feel free to extend it yourselves or comment your suggestions."
},
{
"code": null,
"e": 17725,
"s": 12589,
"text": "import hashlib, sqlite3, pandas as pdconn = sqlite3.connect(':memory:')#conn = sqlite3.connect('meh.sqlite3')cur = conn.cursor()files = [r'C:\\Temp\\FL_insurance.csv', r'C:\\temp\\FL_insurance - Copy.csv']colsep = [',',',']datakey = ['policyID', 'statecode', 'county']static = ['Table1','Table2']def list2csv(l1): for i, item in enumerate(l1): if i == 0: csvlist = 'x.' + item else: csvlist += ', x.'+ item return(csvlist)def sha1(fname): sha1hash = hashlib.sha1() with open(fname) as handle: #opening the file one line at a time for memory considerations for line in handle: sha1hash.update(line.encode('utf-8')) return(sha1hash.hexdigest())def loadDataToSQL(files, static): chunksize = 10000 i=0 createindexfortable = lambda a, b : f'CREATE INDEX {a} Index ON {b} ({a})' for file in files: i = i+1 for chunk in pd.read_csv(file, chunksize=chunksize, delimiter=colsep[i-1]): #load the file in chunks in case its too big chunk.columns = chunk.columns.str.replace(' ', '_') #replacing spaces with underscores for column names chunk.to_sql(name= static[i-1], con=conn, if_exists='append') for item in datakey: #create indexes so it runs faster createindexfortable(item, 'Table1') createindexfortable(item, 'Table2')def returnSQLresults(statement, noprint = 0): cur.execute(statement) i=0 temp = [] for row in cur: if noprint == 0 and len(row) > 1: if i == 0: #if there are multiple records, only print the header once names = list(map(lambda x: x[0], cur.description)) #column names print(names) print(row) else: temp.append(row) i=i+1 if noprint == 1 and i != 0: return(temp) elif i==0: return(None)def sha1(fname): sha1hash = hashlib.sha1() with open(fname) as handle: #opening the file one line at a time for memory considerations for line in handle: sha1hash.update(line.encode('utf-8')) return(sha1hash.hexdigest())def SQLComp(files, keys, compDegree): for key in keys: if key == keys[0]: joinstatement = f'x.{key} = y.{key}' wherestatement = f' WHERE y.{key} IS NULL' wherenotstatement = f' WHERE y.{key} IS NOT NULL' else: joinstatement += f' AND x.{key} = y.{key}' wherestatement += f' AND y.{key} IS NULL' wherenotstatement += f' AND y.{key} IS NOT NULL' print('########################################') print('Checking Counts across the two data sets:') print('Total Counts') statement_counts = '''SELECT \"Table1\" AS \"TABLE\", COUNT(1) FROM Table1 UNION SELECT \"Table2\" AS \"TABLE\", COUNT(1) FROM Table2''' returnSQLresults(statement_counts) print('########################################') print('Checking Rows based on data Key.') statement1 = f'''SELECT * FROM Table1 x LEFT JOIN Table2 y ON {joinstatement} {wherestatement}''' statement2 = f'''SELECT * FROM Table2 x LEFT JOIN Table1 y ON {joinstatement} {wherestatement}''' if returnSQLresults(statement1) is None and returnSQLresults(statement2) is None: print('No differences found.') else: print('Data in file 1, but not in file 2') returnSQLresults(statement1) print('Data in file 2, but not in file 1') returnSQLresults(statement2) print('########################################') print('Checking Columns between the two files.') #statement3 = 'PRAGMA table_info(Table1);' statement3 = lambda a : 'PRAGMA TABLE_INFO(' + a + ')' statement3Table1results = returnSQLresults(statement3('Table1'),1) statement3Table2results = returnSQLresults(statement3('Table2'),1) if (statement3Table1results == statement3Table2results): print('No differences found.') else: print('Columns in one but not the other.') print(set(statement3Table1results)-set(statement3Table2results)) print('########################################') print('Differences identified in the following columns.') columnsInCommon1 = list(set(statement3Table1results).intersection(set(statement3Table2results))) columnsInCommon = [] for cols in columnsInCommon1: columnsInCommon.append(cols[1]) columnsInCommon.remove('index') cols2select = list2csv(datakey) for item in columnsInCommon: statement4 = f'''SELECT {cols2select}, x.{item}, y.{item} FROM Table1 x JOIN Table2 y ON {joinstatement} {wherenotstatement} AND x.{item} <> y.{item}''' returnSQLresults(statement4) #print(statement4)def comparefiles(files,datakey): print('########################################') print('Checking the files\\' hash.') if sha1(files[0]) == sha1(files[1]): print('100% Match') else: print('Hash not matched. Proceeding to detailed checks.') loadDataToSQL(files, static) SQLComp(files, datakey, [])comparefiles(files, datakey)"
}
] |
10 Minutes to Building a Machine Learning Pipeline with Apache Airflow | by Binh Phan | Towards Data Science
|
Often, when you think about Machine Learning, you tend to think about the great models that you can now create. If you want to take these amazing models and make them available to the world, you will have to move beyond just training the model and incorporating data collection, feature engineering, training, evaluating, and serving.
On top of all that, you will also have to remember that you’re putting a software application into production. That means you’ll have all the requirements that any production software has, including scalability, consistency, modularity, testability, and security.
A ML pipeline allows you to automatically run the steps of a Machine Learning system, from data collection to model serving (as shown in the photo above). It will also reduce the technical debt of a machine learning system, as this linked paper describes. This segues into the fields of MLOps, a fast-growing field that, similar to DevOps, (aims to automate and monitor all steps of the ML System.
This tutorial will show you how to build a simple ML pipeline that automates the workflow of a deep learning image classifier for dandelions and grass built using FastAI, and then served as a web app using Starlette. We’ll use Apache AirFlow, out of the many workflow tools like Luigi, MLFlow, and KubeFlow, because it provides an extensive set of features and a beautiful UI. AirFlow is open-source software that allows you to programmatically author and schedule your workflows using a directed acyclic graph (DAG) and monitor them via the built-in Airflow user interface. At the end of the tutorial, I’ll show you further steps you can take to make your pipeline production-ready.
Requirements: Since you will run this tutorial on a VM instance, all you will need is a computer running any OS, and a Google account.
This tutorial will be broken down into the following steps:
Sign up for Google Cloud Platform and create a compute instancePull tutorial contents from GithubOverview of ML pipeline in AirFlowInstall Docker & set up virtual hosts using nginxBuild and run a Docker containerOpen Airflow UI and run ML pipelineRun deployed web app
Sign up for Google Cloud Platform and create a compute instance
Pull tutorial contents from Github
Overview of ML pipeline in AirFlow
Install Docker & set up virtual hosts using nginx
Build and run a Docker container
Open Airflow UI and run ML pipeline
Run deployed web app
If you haven’t already, sign up for Google Cloud Platform through your Google account. You’ll have to enter your credit card, but you won’t be charged anything upon signing up. You’ll also get $300 worth of free credits that last for 12 months! If you’ve run out of credits, don’t worry — running this tutorial will cost pennies, provided you stop your VM instance afterward!
Once you’re in the console, go to Compute Engine and create an instance. Then:
name the instance greenr-airflowset the compute instance as n1-standard-8set the OS to Ubuntu 18.04ramp up the HDD memory to 30GBAllow cloud access to APIs and HTTP/HTTPS traffic
name the instance greenr-airflow
set the compute instance as n1-standard-8
set the OS to Ubuntu 18.04
ramp up the HDD memory to 30GB
Allow cloud access to APIs and HTTP/HTTPS traffic
When your instance has been created and is running, SSH into your instance by clicking on the SSH button located on the right side of the screen.
Let’s pull the tutorial contents from Github. Clone the repo from Github by typing this into the VM instance:
git clone https://github.com/btphan95/greenr-airflowcd greenr-airflow
Let’s explore the contents of this Git repository. First, let’s explore the AirFlow configuration file, /config/airflow.cfg. It sets all of the configuration options for your AirFlow pipeline, including the location of your airflow pipelines (in this case, we set this folder to be /dags/, and where we connect to our metadata database, sql_alchemy_conn. AirFlow uses a database to store metadata about DAGs, their runs, and other Airflow configurations like users, roles, and connections. Think of it like saving your progress in a video game.
Next, let’s explore the ML pipeline, which is defined in /dags/ml_pipeline.py.
What this Python script does is define our directed acyclic graph structure as code, including the tasks that we want to execute and their ordering.
Let’s break down the code in ml_pipeline.py:
default_args = ... default_args defines arguments that will be fed into our DAG function. This includes the owner name, owner, whether or not the DAG should run again after a failed instance, depends_on_past, and the start date, start_date. Note: AirFlow will start your DAG after start_date AND one instance of schedule_interval under the DAG definition. This means that in our case, we start at (31 days ago) + (30 day interval) = yesterday.dag = DAG ...DAG instantiates a directed acyclic graph along with default_args and the schedule_interval.download_images = BashOperator... Remember that Apache AirFlow defines our directed acyclic graph structure as code, and that DAGS consist of tasks. Tasks are defined using Operators, which execute code. Here, we use BashOperator to run the Python files for our tasks, located in scripts/. For example, in our download_images task, where we download images from Google Images, the BashOperator calls python3 /usr/local/airflow/scripts/download_images.py.download_images >> train >> serve Here, we set the ordering of the tasks in the DAG. The >> directs the 2nd task to run after the first has completed. That means in the pipeline, download_images will run before train, which will run before serve.
default_args = ... default_args defines arguments that will be fed into our DAG function. This includes the owner name, owner, whether or not the DAG should run again after a failed instance, depends_on_past, and the start date, start_date. Note: AirFlow will start your DAG after start_date AND one instance of schedule_interval under the DAG definition. This means that in our case, we start at (31 days ago) + (30 day interval) = yesterday.
dag = DAG ...DAG instantiates a directed acyclic graph along with default_args and the schedule_interval.
download_images = BashOperator... Remember that Apache AirFlow defines our directed acyclic graph structure as code, and that DAGS consist of tasks. Tasks are defined using Operators, which execute code. Here, we use BashOperator to run the Python files for our tasks, located in scripts/. For example, in our download_images task, where we download images from Google Images, the BashOperator calls python3 /usr/local/airflow/scripts/download_images.py.
download_images >> train >> serve Here, we set the ordering of the tasks in the DAG. The >> directs the 2nd task to run after the first has completed. That means in the pipeline, download_images will run before train, which will run before serve.
I encourage you to take a look at the python scripts for each of the tasks!
Docker allows you to run software in containers, which is virtual environments running their own OS, making it easy to bundle software and their required packages reliably and easily. That’s exactly why we’re going to run our tutorial using Docker. First, let’s install Docker on our VM by running a Bash script from the Docker website (or you can manually install Docker here):
bash <(curl -s https://get.docker.com/)
Then, you’ll need to set up virtual hosts using nginx, an open-source web server software. Since I’m planning on using two ports in the Docker container, one for the AirFlow UI, and one for the final web app, and only have 1 public IP address (the external address of our compute instance), you will use nginx to route HTTP requests to our external IP address. Route from AirFlow on port 8080 to our default port 80 using this script:
bash scripts/nginx-airflow.sh
Now, let’s build the Docker container using the following command:
sudo docker build -t greenr-airflow:latest .
This will run the Dockerfile in our directory and download and install the necessary libraries for our container.
Be patient — this will take around 10 minutes.
Then, run the Docker container:
sudo docker run -d -p 8080:8080 -p 8008:8008 greenr-airflow
After a few seconds, visit the external IP address of your machine, which you can find on Compute Engine in the GCP console. Make sure when you enter it in your browser, to prefix the IP address with http:// like this: http://34.68.160.231/
You should now see the AirFlow user interface:
Now, click the Off switch, and click the left-most button, Trigger DAG. The pipeline will now be running, and when you click ml_pipeline and go to the Tree section, you’ll see the directed acyclic graph and also the status of the pipeline:
After a few minutes, the last task, serve, will be running. Your ML pipeline has been successfully executed! Now, let’s have nginx route our app from port 8008 to our external IP address:
bash scripts/nginx-app.sh
At this point, go to your external IP address and add /app after, like this: http://34.68.160.231/app
You will now see the final web app, greenr, running! If you are interested in learning how to build and deploy greenr, check out my tutorial on deploying a deep learning model on Google Cloud Platform!
In this tutorial, you learned how to build a simple Machine Learning pipeline in Apache AirFlow consisting of three tasks: download images, train, and serve. Certainly, this can be improved to be more production-ready and scalable. Here are some suggestions on how to take your pipeline further:
Consider using KubernetesOperator to create tasks that run in Kubernetes, allowing for much more scalabilityConsider using another Executor like CeleryExecutor that allows for parallel and scaled-out workers (we used the rudimentary SequentialExecutor)Consider using KubeFlow, which allows for large-scale, production-ready ML pipelines that orchestrate tasks in Kubernetes, similar to 1.
Consider using KubernetesOperator to create tasks that run in Kubernetes, allowing for much more scalability
Consider using another Executor like CeleryExecutor that allows for parallel and scaled-out workers (we used the rudimentary SequentialExecutor)
Consider using KubeFlow, which allows for large-scale, production-ready ML pipelines that orchestrate tasks in Kubernetes, similar to 1.
I hope this gives you a gentle introduction to building ML pipelines on Apache AirFlow and that this can serve as a template for your work!
Don’t forget to turn off your compute instance to ensure that you don’t get charged for usage by Google Cloud!
|
[
{
"code": null,
"e": 382,
"s": 47,
"text": "Often, when you think about Machine Learning, you tend to think about the great models that you can now create. If you want to take these amazing models and make them available to the world, you will have to move beyond just training the model and incorporating data collection, feature engineering, training, evaluating, and serving."
},
{
"code": null,
"e": 646,
"s": 382,
"text": "On top of all that, you will also have to remember that you’re putting a software application into production. That means you’ll have all the requirements that any production software has, including scalability, consistency, modularity, testability, and security."
},
{
"code": null,
"e": 1044,
"s": 646,
"text": "A ML pipeline allows you to automatically run the steps of a Machine Learning system, from data collection to model serving (as shown in the photo above). It will also reduce the technical debt of a machine learning system, as this linked paper describes. This segues into the fields of MLOps, a fast-growing field that, similar to DevOps, (aims to automate and monitor all steps of the ML System."
},
{
"code": null,
"e": 1728,
"s": 1044,
"text": "This tutorial will show you how to build a simple ML pipeline that automates the workflow of a deep learning image classifier for dandelions and grass built using FastAI, and then served as a web app using Starlette. We’ll use Apache AirFlow, out of the many workflow tools like Luigi, MLFlow, and KubeFlow, because it provides an extensive set of features and a beautiful UI. AirFlow is open-source software that allows you to programmatically author and schedule your workflows using a directed acyclic graph (DAG) and monitor them via the built-in Airflow user interface. At the end of the tutorial, I’ll show you further steps you can take to make your pipeline production-ready."
},
{
"code": null,
"e": 1863,
"s": 1728,
"text": "Requirements: Since you will run this tutorial on a VM instance, all you will need is a computer running any OS, and a Google account."
},
{
"code": null,
"e": 1923,
"s": 1863,
"text": "This tutorial will be broken down into the following steps:"
},
{
"code": null,
"e": 2191,
"s": 1923,
"text": "Sign up for Google Cloud Platform and create a compute instancePull tutorial contents from GithubOverview of ML pipeline in AirFlowInstall Docker & set up virtual hosts using nginxBuild and run a Docker containerOpen Airflow UI and run ML pipelineRun deployed web app"
},
{
"code": null,
"e": 2255,
"s": 2191,
"text": "Sign up for Google Cloud Platform and create a compute instance"
},
{
"code": null,
"e": 2290,
"s": 2255,
"text": "Pull tutorial contents from Github"
},
{
"code": null,
"e": 2325,
"s": 2290,
"text": "Overview of ML pipeline in AirFlow"
},
{
"code": null,
"e": 2375,
"s": 2325,
"text": "Install Docker & set up virtual hosts using nginx"
},
{
"code": null,
"e": 2408,
"s": 2375,
"text": "Build and run a Docker container"
},
{
"code": null,
"e": 2444,
"s": 2408,
"text": "Open Airflow UI and run ML pipeline"
},
{
"code": null,
"e": 2465,
"s": 2444,
"text": "Run deployed web app"
},
{
"code": null,
"e": 2841,
"s": 2465,
"text": "If you haven’t already, sign up for Google Cloud Platform through your Google account. You’ll have to enter your credit card, but you won’t be charged anything upon signing up. You’ll also get $300 worth of free credits that last for 12 months! If you’ve run out of credits, don’t worry — running this tutorial will cost pennies, provided you stop your VM instance afterward!"
},
{
"code": null,
"e": 2920,
"s": 2841,
"text": "Once you’re in the console, go to Compute Engine and create an instance. Then:"
},
{
"code": null,
"e": 3099,
"s": 2920,
"text": "name the instance greenr-airflowset the compute instance as n1-standard-8set the OS to Ubuntu 18.04ramp up the HDD memory to 30GBAllow cloud access to APIs and HTTP/HTTPS traffic"
},
{
"code": null,
"e": 3132,
"s": 3099,
"text": "name the instance greenr-airflow"
},
{
"code": null,
"e": 3174,
"s": 3132,
"text": "set the compute instance as n1-standard-8"
},
{
"code": null,
"e": 3201,
"s": 3174,
"text": "set the OS to Ubuntu 18.04"
},
{
"code": null,
"e": 3232,
"s": 3201,
"text": "ramp up the HDD memory to 30GB"
},
{
"code": null,
"e": 3282,
"s": 3232,
"text": "Allow cloud access to APIs and HTTP/HTTPS traffic"
},
{
"code": null,
"e": 3428,
"s": 3282,
"text": "When your instance has been created and is running, SSH into your instance by clicking on the SSH button located on the right side of the screen."
},
{
"code": null,
"e": 3538,
"s": 3428,
"text": "Let’s pull the tutorial contents from Github. Clone the repo from Github by typing this into the VM instance:"
},
{
"code": null,
"e": 3608,
"s": 3538,
"text": "git clone https://github.com/btphan95/greenr-airflowcd greenr-airflow"
},
{
"code": null,
"e": 4153,
"s": 3608,
"text": "Let’s explore the contents of this Git repository. First, let’s explore the AirFlow configuration file, /config/airflow.cfg. It sets all of the configuration options for your AirFlow pipeline, including the location of your airflow pipelines (in this case, we set this folder to be /dags/, and where we connect to our metadata database, sql_alchemy_conn. AirFlow uses a database to store metadata about DAGs, their runs, and other Airflow configurations like users, roles, and connections. Think of it like saving your progress in a video game."
},
{
"code": null,
"e": 4232,
"s": 4153,
"text": "Next, let’s explore the ML pipeline, which is defined in /dags/ml_pipeline.py."
},
{
"code": null,
"e": 4381,
"s": 4232,
"text": "What this Python script does is define our directed acyclic graph structure as code, including the tasks that we want to execute and their ordering."
},
{
"code": null,
"e": 4426,
"s": 4381,
"text": "Let’s break down the code in ml_pipeline.py:"
},
{
"code": null,
"e": 5675,
"s": 4426,
"text": "default_args = ... default_args defines arguments that will be fed into our DAG function. This includes the owner name, owner, whether or not the DAG should run again after a failed instance, depends_on_past, and the start date, start_date. Note: AirFlow will start your DAG after start_date AND one instance of schedule_interval under the DAG definition. This means that in our case, we start at (31 days ago) + (30 day interval) = yesterday.dag = DAG ...DAG instantiates a directed acyclic graph along with default_args and the schedule_interval.download_images = BashOperator... Remember that Apache AirFlow defines our directed acyclic graph structure as code, and that DAGS consist of tasks. Tasks are defined using Operators, which execute code. Here, we use BashOperator to run the Python files for our tasks, located in scripts/. For example, in our download_images task, where we download images from Google Images, the BashOperator calls python3 /usr/local/airflow/scripts/download_images.py.download_images >> train >> serve Here, we set the ordering of the tasks in the DAG. The >> directs the 2nd task to run after the first has completed. That means in the pipeline, download_images will run before train, which will run before serve."
},
{
"code": null,
"e": 6119,
"s": 5675,
"text": "default_args = ... default_args defines arguments that will be fed into our DAG function. This includes the owner name, owner, whether or not the DAG should run again after a failed instance, depends_on_past, and the start date, start_date. Note: AirFlow will start your DAG after start_date AND one instance of schedule_interval under the DAG definition. This means that in our case, we start at (31 days ago) + (30 day interval) = yesterday."
},
{
"code": null,
"e": 6225,
"s": 6119,
"text": "dag = DAG ...DAG instantiates a directed acyclic graph along with default_args and the schedule_interval."
},
{
"code": null,
"e": 6680,
"s": 6225,
"text": "download_images = BashOperator... Remember that Apache AirFlow defines our directed acyclic graph structure as code, and that DAGS consist of tasks. Tasks are defined using Operators, which execute code. Here, we use BashOperator to run the Python files for our tasks, located in scripts/. For example, in our download_images task, where we download images from Google Images, the BashOperator calls python3 /usr/local/airflow/scripts/download_images.py."
},
{
"code": null,
"e": 6927,
"s": 6680,
"text": "download_images >> train >> serve Here, we set the ordering of the tasks in the DAG. The >> directs the 2nd task to run after the first has completed. That means in the pipeline, download_images will run before train, which will run before serve."
},
{
"code": null,
"e": 7003,
"s": 6927,
"text": "I encourage you to take a look at the python scripts for each of the tasks!"
},
{
"code": null,
"e": 7382,
"s": 7003,
"text": "Docker allows you to run software in containers, which is virtual environments running their own OS, making it easy to bundle software and their required packages reliably and easily. That’s exactly why we’re going to run our tutorial using Docker. First, let’s install Docker on our VM by running a Bash script from the Docker website (or you can manually install Docker here):"
},
{
"code": null,
"e": 7422,
"s": 7382,
"text": "bash <(curl -s https://get.docker.com/)"
},
{
"code": null,
"e": 7857,
"s": 7422,
"text": "Then, you’ll need to set up virtual hosts using nginx, an open-source web server software. Since I’m planning on using two ports in the Docker container, one for the AirFlow UI, and one for the final web app, and only have 1 public IP address (the external address of our compute instance), you will use nginx to route HTTP requests to our external IP address. Route from AirFlow on port 8080 to our default port 80 using this script:"
},
{
"code": null,
"e": 7887,
"s": 7857,
"text": "bash scripts/nginx-airflow.sh"
},
{
"code": null,
"e": 7954,
"s": 7887,
"text": "Now, let’s build the Docker container using the following command:"
},
{
"code": null,
"e": 7999,
"s": 7954,
"text": "sudo docker build -t greenr-airflow:latest ."
},
{
"code": null,
"e": 8113,
"s": 7999,
"text": "This will run the Dockerfile in our directory and download and install the necessary libraries for our container."
},
{
"code": null,
"e": 8160,
"s": 8113,
"text": "Be patient — this will take around 10 minutes."
},
{
"code": null,
"e": 8192,
"s": 8160,
"text": "Then, run the Docker container:"
},
{
"code": null,
"e": 8252,
"s": 8192,
"text": "sudo docker run -d -p 8080:8080 -p 8008:8008 greenr-airflow"
},
{
"code": null,
"e": 8493,
"s": 8252,
"text": "After a few seconds, visit the external IP address of your machine, which you can find on Compute Engine in the GCP console. Make sure when you enter it in your browser, to prefix the IP address with http:// like this: http://34.68.160.231/"
},
{
"code": null,
"e": 8540,
"s": 8493,
"text": "You should now see the AirFlow user interface:"
},
{
"code": null,
"e": 8780,
"s": 8540,
"text": "Now, click the Off switch, and click the left-most button, Trigger DAG. The pipeline will now be running, and when you click ml_pipeline and go to the Tree section, you’ll see the directed acyclic graph and also the status of the pipeline:"
},
{
"code": null,
"e": 8968,
"s": 8780,
"text": "After a few minutes, the last task, serve, will be running. Your ML pipeline has been successfully executed! Now, let’s have nginx route our app from port 8008 to our external IP address:"
},
{
"code": null,
"e": 8994,
"s": 8968,
"text": "bash scripts/nginx-app.sh"
},
{
"code": null,
"e": 9096,
"s": 8994,
"text": "At this point, go to your external IP address and add /app after, like this: http://34.68.160.231/app"
},
{
"code": null,
"e": 9298,
"s": 9096,
"text": "You will now see the final web app, greenr, running! If you are interested in learning how to build and deploy greenr, check out my tutorial on deploying a deep learning model on Google Cloud Platform!"
},
{
"code": null,
"e": 9594,
"s": 9298,
"text": "In this tutorial, you learned how to build a simple Machine Learning pipeline in Apache AirFlow consisting of three tasks: download images, train, and serve. Certainly, this can be improved to be more production-ready and scalable. Here are some suggestions on how to take your pipeline further:"
},
{
"code": null,
"e": 9983,
"s": 9594,
"text": "Consider using KubernetesOperator to create tasks that run in Kubernetes, allowing for much more scalabilityConsider using another Executor like CeleryExecutor that allows for parallel and scaled-out workers (we used the rudimentary SequentialExecutor)Consider using KubeFlow, which allows for large-scale, production-ready ML pipelines that orchestrate tasks in Kubernetes, similar to 1."
},
{
"code": null,
"e": 10092,
"s": 9983,
"text": "Consider using KubernetesOperator to create tasks that run in Kubernetes, allowing for much more scalability"
},
{
"code": null,
"e": 10237,
"s": 10092,
"text": "Consider using another Executor like CeleryExecutor that allows for parallel and scaled-out workers (we used the rudimentary SequentialExecutor)"
},
{
"code": null,
"e": 10374,
"s": 10237,
"text": "Consider using KubeFlow, which allows for large-scale, production-ready ML pipelines that orchestrate tasks in Kubernetes, similar to 1."
},
{
"code": null,
"e": 10514,
"s": 10374,
"text": "I hope this gives you a gentle introduction to building ML pipelines on Apache AirFlow and that this can serve as a template for your work!"
}
] |
ClipOval widget in Flutter - GeeksforGeeks
|
21 Oct, 2020
ClipOval widget clips the child widget in oval or circle shape. We can reshape the child widget by changing width and height. If width and height are equal the shape will be circular. If the width and height are given differently then the shape will be oval. Let’s understand this with the help of an example.
Syntax:
ClipOval({Key key,
CustomClipper<Rect> clipper,
Clip clipBehavior: Clip.antiAlias,
Widget child})
clipBehaviour: This property controls how flutter clips the object. By default, it is set to clip.none for most of the classes, but while implementing this property it must not be set to null. We can employ these three behaviors while implementing ClipOval.
Clip.hardEdge
Clip.antiAlias
Clip.antiAliasWithSaveLayer
clipper: If specified this property determines which clip to use among the five builtin clippers (ClipOval, ClipRect, ClipRRect, and ClipPath) or a custom clipper. The child class of the clipper describes the axis-aligned area of the oval. If this property is set to null then ClipOval by default takes the boundaries of the object as the area to be clipped.
Example:
The main.dart file.
Dart
import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is //the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'ClipOval', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePAGE(), debugShowCheckedModeBanner: false, ); }} class MyHomePAGE extends StatefulWidget { @override _MyHomePAGEState createState() => _MyHomePAGEState();} class _MyHomePAGEState extends State<MyHomePAGE> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Center( child: ClipOval( child: Image.network( 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRFU7U2h0umyF0P6E_yhTX45sGgPEQAbGaJ4g&usqp=CAU', fit: BoxFit.fill), clipper: MyClip(), ), ), backgroundColor: Colors.lightBlue[50], ); }} class MyClip extends CustomClipper<Rect> { Rect getClip(Size size) { return Rect.fromLTWH(0, 0, 100, 100); } bool shouldReclip(oldClipper) { return false; }}
Output:
If the properties are defined as below:
ClipOval(
child: Image.network(
'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRFU7U2h0umyF0P6E_yhTX45sGgPEQAbGaJ4g&usqp=CAU',
fit: BoxFit.fill),
),
The following design changes can be observed:
If the properties are defined as below:
ClipOval(
child: Image.network(
'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRFU7U2h0umyF0P6E_yhTX45sGgPEQAbGaJ4g&usqp=CAU',
fit: BoxFit.fill),
clipper: MyClip(),
),
The following design changes can be observed:
Explanation:
Create ClipOval widget and wrap it with Center widget.
Give a child of ClipOval widget as Image.network(src).
If you want to resize the child of ClipOval, then use clipper and perform getClip() and shouldReclip().
ankit_kumar_
android
Flutter
Flutter-widgets
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
ListView Class in Flutter
Android Studio Setup for Flutter Development
Flutter - Flexible Widget
What is widgets in Flutter?
Flutter - Custom Bottom Navigation Bar
Flutter Tutorial
Flutter - Flexible Widget
Flutter - Stack Widget
Flutter - BorderRadius Widget
|
[
{
"code": null,
"e": 24034,
"s": 24006,
"text": "\n21 Oct, 2020"
},
{
"code": null,
"e": 24344,
"s": 24034,
"text": "ClipOval widget clips the child widget in oval or circle shape. We can reshape the child widget by changing width and height. If width and height are equal the shape will be circular. If the width and height are given differently then the shape will be oval. Let’s understand this with the help of an example."
},
{
"code": null,
"e": 24452,
"s": 24344,
"text": "Syntax:\nClipOval({Key key,\nCustomClipper<Rect> clipper,\nClip clipBehavior: Clip.antiAlias,\nWidget child})\n\n"
},
{
"code": null,
"e": 24710,
"s": 24452,
"text": "clipBehaviour: This property controls how flutter clips the object. By default, it is set to clip.none for most of the classes, but while implementing this property it must not be set to null. We can employ these three behaviors while implementing ClipOval."
},
{
"code": null,
"e": 24769,
"s": 24710,
"text": "Clip.hardEdge\nClip.antiAlias\nClip.antiAliasWithSaveLayer\n\n"
},
{
"code": null,
"e": 25129,
"s": 24769,
"text": "clipper: If specified this property determines which clip to use among the five builtin clippers (ClipOval, ClipRect, ClipRRect, and ClipPath) or a custom clipper. The child class of the clipper describes the axis-aligned area of the oval. If this property is set to null then ClipOval by default takes the boundaries of the object as the area to be clipped."
},
{
"code": null,
"e": 25138,
"s": 25129,
"text": "Example:"
},
{
"code": null,
"e": 25158,
"s": 25138,
"text": "The main.dart file."
},
{
"code": null,
"e": 25163,
"s": 25158,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is //the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'ClipOval', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePAGE(), debugShowCheckedModeBanner: false, ); }} class MyHomePAGE extends StatefulWidget { @override _MyHomePAGEState createState() => _MyHomePAGEState();} class _MyHomePAGEState extends State<MyHomePAGE> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Center( child: ClipOval( child: Image.network( 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRFU7U2h0umyF0P6E_yhTX45sGgPEQAbGaJ4g&usqp=CAU', fit: BoxFit.fill), clipper: MyClip(), ), ), backgroundColor: Colors.lightBlue[50], ); }} class MyClip extends CustomClipper<Rect> { Rect getClip(Size size) { return Rect.fromLTWH(0, 0, 100, 100); } bool shouldReclip(oldClipper) { return false; }}",
"e": 26389,
"s": 25163,
"text": null
},
{
"code": null,
"e": 26397,
"s": 26389,
"text": "Output:"
},
{
"code": null,
"e": 26437,
"s": 26397,
"text": "If the properties are defined as below:"
},
{
"code": null,
"e": 26636,
"s": 26437,
"text": "ClipOval(\n child: Image.network(\n 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRFU7U2h0umyF0P6E_yhTX45sGgPEQAbGaJ4g&usqp=CAU',\n fit: BoxFit.fill),\n ),\n\n"
},
{
"code": null,
"e": 26682,
"s": 26636,
"text": "The following design changes can be observed:"
},
{
"code": null,
"e": 26722,
"s": 26682,
"text": "If the properties are defined as below:"
},
{
"code": null,
"e": 26958,
"s": 26722,
"text": "ClipOval(\n child: Image.network(\n 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRFU7U2h0umyF0P6E_yhTX45sGgPEQAbGaJ4g&usqp=CAU',\n fit: BoxFit.fill),\n clipper: MyClip(),\n ),\n\n"
},
{
"code": null,
"e": 27004,
"s": 26958,
"text": "The following design changes can be observed:"
},
{
"code": null,
"e": 27017,
"s": 27004,
"text": "Explanation:"
},
{
"code": null,
"e": 27072,
"s": 27017,
"text": "Create ClipOval widget and wrap it with Center widget."
},
{
"code": null,
"e": 27127,
"s": 27072,
"text": "Give a child of ClipOval widget as Image.network(src)."
},
{
"code": null,
"e": 27231,
"s": 27127,
"text": "If you want to resize the child of ClipOval, then use clipper and perform getClip() and shouldReclip()."
},
{
"code": null,
"e": 27244,
"s": 27231,
"text": "ankit_kumar_"
},
{
"code": null,
"e": 27252,
"s": 27244,
"text": "android"
},
{
"code": null,
"e": 27260,
"s": 27252,
"text": "Flutter"
},
{
"code": null,
"e": 27276,
"s": 27260,
"text": "Flutter-widgets"
},
{
"code": null,
"e": 27281,
"s": 27276,
"text": "Dart"
},
{
"code": null,
"e": 27289,
"s": 27281,
"text": "Flutter"
},
{
"code": null,
"e": 27387,
"s": 27289,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27396,
"s": 27387,
"text": "Comments"
},
{
"code": null,
"e": 27409,
"s": 27396,
"text": "Old Comments"
},
{
"code": null,
"e": 27448,
"s": 27409,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 27474,
"s": 27448,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 27519,
"s": 27474,
"text": "Android Studio Setup for Flutter Development"
},
{
"code": null,
"e": 27545,
"s": 27519,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 27573,
"s": 27545,
"text": "What is widgets in Flutter?"
},
{
"code": null,
"e": 27612,
"s": 27573,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 27629,
"s": 27612,
"text": "Flutter Tutorial"
},
{
"code": null,
"e": 27655,
"s": 27629,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 27678,
"s": 27655,
"text": "Flutter - Stack Widget"
}
] |
java.time.LocalDateTime.truncatedTo() Method Example
|
The java.time.LocalDateTime.truncatedTo(TemporalUnit unit) method returns a copy of this LocalDateTime with the time truncated.
Following is the declaration for java.time.LocalDateTime.truncatedTo(TemporalUnit unit) method.
public LocalDateTime truncatedTo(TemporalUnit unit)
unit − the unit to truncate to, not null.
a LocalDateTime based on this date-time with the time truncated, not null.
DateTimeException − if unable to truncate.
DateTimeException − if unable to truncate.
UnsupportedTemporalTypeException − if the unit is not supported.
UnsupportedTemporalTypeException − if the unit is not supported.
The following example shows the usage of java.time.LocalDateTime.truncatedTo(TemporalUnit unit) method.
package com.tutorialspoint;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
public class LocalDateTimeDemo {
public static void main(String[] args) {
LocalDateTime date = LocalDateTime.now();
System.out.println(date.truncatedTo(ChronoUnit.DAYS));
}
}
Let us compile and run the above program, this will produce the following result −
2017-03-17T00:00
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2043,
"s": 1915,
"text": "The java.time.LocalDateTime.truncatedTo(TemporalUnit unit) method returns a copy of this LocalDateTime with the time truncated."
},
{
"code": null,
"e": 2139,
"s": 2043,
"text": "Following is the declaration for java.time.LocalDateTime.truncatedTo(TemporalUnit unit) method."
},
{
"code": null,
"e": 2192,
"s": 2139,
"text": "public LocalDateTime truncatedTo(TemporalUnit unit)\n"
},
{
"code": null,
"e": 2234,
"s": 2192,
"text": "unit − the unit to truncate to, not null."
},
{
"code": null,
"e": 2309,
"s": 2234,
"text": "a LocalDateTime based on this date-time with the time truncated, not null."
},
{
"code": null,
"e": 2352,
"s": 2309,
"text": "DateTimeException − if unable to truncate."
},
{
"code": null,
"e": 2395,
"s": 2352,
"text": "DateTimeException − if unable to truncate."
},
{
"code": null,
"e": 2460,
"s": 2395,
"text": "UnsupportedTemporalTypeException − if the unit is not supported."
},
{
"code": null,
"e": 2525,
"s": 2460,
"text": "UnsupportedTemporalTypeException − if the unit is not supported."
},
{
"code": null,
"e": 2629,
"s": 2525,
"text": "The following example shows the usage of java.time.LocalDateTime.truncatedTo(TemporalUnit unit) method."
},
{
"code": null,
"e": 2926,
"s": 2629,
"text": "package com.tutorialspoint;\n\nimport java.time.LocalDateTime;\nimport java.time.temporal.ChronoUnit;\n\npublic class LocalDateTimeDemo {\n public static void main(String[] args) {\n \n LocalDateTime date = LocalDateTime.now();\n System.out.println(date.truncatedTo(ChronoUnit.DAYS)); \n }\n}"
},
{
"code": null,
"e": 3009,
"s": 2926,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3027,
"s": 3009,
"text": "2017-03-17T00:00\n"
},
{
"code": null,
"e": 3034,
"s": 3027,
"text": " Print"
},
{
"code": null,
"e": 3045,
"s": 3034,
"text": " Add Notes"
}
] |
Angular 4 - Environment Setup
|
In this chapter, we will discuss the Environment Setup required for Angular 4. To install Angular 4, we require the following −
Nodejs
Npm
Angular CLI
IDE for writing your code
Nodejs has to be greater than 4 and npm has to be greater than 3.
To check if nodejs is installed on your system, type node –v in the terminal. This will help you see the version of nodejs currently installed on your system.
C:\>node –v
v6.11.0
If it does not print anything, install nodejs on your system. To install nodejs, go the homepage https://nodejs.org/en/download/ of nodejs and install the package based on your OS.
The homepage of nodejs will look like the following −
Based on your OS, install the required package. Once nodejs is installed, npm will also get installed along with it. To check if npm is installed or not, type npm –v in the terminal. It should display the version of the npm.
C:\>npm –v
5.3.0
Angular 4 installations are very simple with the help of angular CLI. Visit the homepage https://cli.angular.io/ of angular to get the reference of the command.
Type npm install –g @angular/cli, to install angular cli on your system.
You will get the above installation in your terminal, once Angular CLI is installed. You can use any IDE of your choice, i.e., WebStorm, Atom, Visual Studio Code, etc.
The details of the project setup is explained in the next chapter.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2120,
"s": 1992,
"text": "In this chapter, we will discuss the Environment Setup required for Angular 4. To install Angular 4, we require the following −"
},
{
"code": null,
"e": 2127,
"s": 2120,
"text": "Nodejs"
},
{
"code": null,
"e": 2131,
"s": 2127,
"text": "Npm"
},
{
"code": null,
"e": 2143,
"s": 2131,
"text": "Angular CLI"
},
{
"code": null,
"e": 2169,
"s": 2143,
"text": "IDE for writing your code"
},
{
"code": null,
"e": 2235,
"s": 2169,
"text": "Nodejs has to be greater than 4 and npm has to be greater than 3."
},
{
"code": null,
"e": 2394,
"s": 2235,
"text": "To check if nodejs is installed on your system, type node –v in the terminal. This will help you see the version of nodejs currently installed on your system."
},
{
"code": null,
"e": 2415,
"s": 2394,
"text": "C:\\>node –v\nv6.11.0\n"
},
{
"code": null,
"e": 2596,
"s": 2415,
"text": "If it does not print anything, install nodejs on your system. To install nodejs, go the homepage https://nodejs.org/en/download/ of nodejs and install the package based on your OS."
},
{
"code": null,
"e": 2650,
"s": 2596,
"text": "The homepage of nodejs will look like the following −"
},
{
"code": null,
"e": 2875,
"s": 2650,
"text": "Based on your OS, install the required package. Once nodejs is installed, npm will also get installed along with it. To check if npm is installed or not, type npm –v in the terminal. It should display the version of the npm."
},
{
"code": null,
"e": 2893,
"s": 2875,
"text": "C:\\>npm –v\n5.3.0\n"
},
{
"code": null,
"e": 3054,
"s": 2893,
"text": "Angular 4 installations are very simple with the help of angular CLI. Visit the homepage https://cli.angular.io/ of angular to get the reference of the command."
},
{
"code": null,
"e": 3127,
"s": 3054,
"text": "Type npm install –g @angular/cli, to install angular cli on your system."
},
{
"code": null,
"e": 3295,
"s": 3127,
"text": "You will get the above installation in your terminal, once Angular CLI is installed. You can use any IDE of your choice, i.e., WebStorm, Atom, Visual Studio Code, etc."
},
{
"code": null,
"e": 3362,
"s": 3295,
"text": "The details of the project setup is explained in the next chapter."
},
{
"code": null,
"e": 3397,
"s": 3362,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3411,
"s": 3397,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3446,
"s": 3411,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3460,
"s": 3446,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3495,
"s": 3460,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 3515,
"s": 3495,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 3550,
"s": 3515,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3567,
"s": 3550,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3600,
"s": 3567,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3612,
"s": 3600,
"text": " Senol Atac"
},
{
"code": null,
"e": 3647,
"s": 3612,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3659,
"s": 3647,
"text": " Senol Atac"
},
{
"code": null,
"e": 3666,
"s": 3659,
"text": " Print"
},
{
"code": null,
"e": 3677,
"s": 3666,
"text": " Add Notes"
}
] |
Find sum of elements in list in Python program
|
In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given a list iterable, we need to compute the sum of the list
Here we will be discussing 3 approaches as discussed below
Live Demo
# sum
total = 0
# creating a list
list1 = [11, 22,33,44,55,66]
# iterating over the list
for ele in range(0, len(list1)):
total = total + list1[ele]
# printing total value
print("Sum of all elements in given list: ", total)
Sum of the array is 231
Live Demo
# Python program to find sum of elements in list
total = 0
ele = 0
# creating a list
list1 = [11,22,33,44,55,66]
# iterating using loop
while(ele < len(list1)):
total = total + list1[ele]
ele += 1
# printing total value
print("Sum of all elements in given list: ", total)
Sum of the array is 231
# list
list1 = [11,22,33,44,55,66]
# function following recursion
def sumOfList(list, size):
if (size == 0):
return 0
else:
return list[size - 1] + sumOfList(list, size - 1)
# main
total = sumOfList(list1, len(list1))
print("Sum of all elements in given list: ", total)
Sum of the array is 231
In this article, we have learned how to print the sum of elements in a list.
|
[
{
"code": null,
"e": 1150,
"s": 1062,
"text": "In this article, we will learn about the solution to the problem statement given below."
},
{
"code": null,
"e": 1239,
"s": 1150,
"text": "Problem statement − We are given a list iterable, we need to compute the sum of the list"
},
{
"code": null,
"e": 1298,
"s": 1239,
"text": "Here we will be discussing 3 approaches as discussed below"
},
{
"code": null,
"e": 1309,
"s": 1298,
"text": " Live Demo"
},
{
"code": null,
"e": 1536,
"s": 1309,
"text": "# sum\ntotal = 0\n# creating a list\nlist1 = [11, 22,33,44,55,66]\n# iterating over the list\nfor ele in range(0, len(list1)):\n total = total + list1[ele]\n# printing total value\nprint(\"Sum of all elements in given list: \", total)"
},
{
"code": null,
"e": 1560,
"s": 1536,
"text": "Sum of the array is 231"
},
{
"code": null,
"e": 1571,
"s": 1560,
"text": " Live Demo"
},
{
"code": null,
"e": 1849,
"s": 1571,
"text": "# Python program to find sum of elements in list\ntotal = 0\nele = 0\n# creating a list\nlist1 = [11,22,33,44,55,66]\n# iterating using loop\nwhile(ele < len(list1)):\n total = total + list1[ele]\n ele += 1\n# printing total value\nprint(\"Sum of all elements in given list: \", total)"
},
{
"code": null,
"e": 1873,
"s": 1849,
"text": "Sum of the array is 231"
},
{
"code": null,
"e": 2149,
"s": 1873,
"text": "# list\nlist1 = [11,22,33,44,55,66]\n# function following recursion\ndef sumOfList(list, size):\nif (size == 0):\n return 0\nelse:\n return list[size - 1] + sumOfList(list, size - 1)\n# main\ntotal = sumOfList(list1, len(list1))\nprint(\"Sum of all elements in given list: \", total)"
},
{
"code": null,
"e": 2173,
"s": 2149,
"text": "Sum of the array is 231"
},
{
"code": null,
"e": 2250,
"s": 2173,
"text": "In this article, we have learned how to print the sum of elements in a list."
}
] |
Spell Checker using Trie - GeeksforGeeks
|
31 Mar, 2021
Given an array of strings str[] and a string key, the task is to check if the spelling of the key is correct or not. If found to be true, then print “YES”. Otherwise, print the suggested correct spellings.
Examples:
Input:str[] = { “gee”, “geeks”, “ape”, “apple”, “geeksforgeeks” }, key = “geek” Output: geeks geeksforgeeks Explanation: The string “geek” not present in the array of strings. Therefore, the suggested words are { “geeks”, “geeksforgeeks” }.
Input: str[] = { “gee”, “geeks”, “ape”, “apple”, “arp” }, key = “geeks” Output: YES.
Approach:The problem can be solved using Trie. The idea is to traverse the array of string, str[] and insert the string into the Trie such that each node of the Trie contains the character of the string and a boolean value to check if the character is the last character of the string or not. Follow the steps below to solve the problem:
Initialize a Trie, say root, such that each node of the Trie consists of a character of a string and a boolean value to check if the character is the last character of the string or not.
Traverse the array of strings arr[], and insert all the strings into the Trie.
Finally, traverse the string key. For every ith character, check if the character is present in the Trie or not. If found to be true, then move to the next node of the Trie.
Otherwise, print all possible strings whose prefix is the string key.
Below is the implementation of the above approach:
C++
Java
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Structure of a Trie nodestruct TrieNode { // Store address of a character TrieNode* Trie[256]; // Check if the character is // last character of a string or not bool isEnd; // Constructor function TrieNode() { for (int i = 0; i < 256; i++) { Trie[i] = NULL; } isEnd = false; }}; // Function to insert a string into Trievoid InsertTrie(TrieNode* root, string s){ TrieNode* temp = root; // Traverse the string, s for (int i = 0; i < s.length(); i++) { if (temp->Trie[s[i]] == NULL) { // Initialize a node temp->Trie[s[i]] = new TrieNode(); } // Update temp temp = temp->Trie[s[i]]; } // Mark the last character of // the string to true temp->isEnd = true;} // Function to print suggestions of the stringvoid printSuggestions(TrieNode* root, string res){ // If current character is // the last character of a string if (root->isEnd == true) { cout << res << " "; } // Iterate over all possible // characters of the string for (int i = 0; i < 256; i++) { // If current character // present in the Trie if (root->Trie[i] != NULL) { // Insert current character // into Trie res.push_back(i); printSuggestions(root->Trie[i], res); res.pop_back(); } }} // Function to check if the string// is present in Trie or notbool checkPresent(TrieNode* root, string key){ // Traverse the string for (int i = 0; i < key.length(); i++) { // If current character not // present in the Trie if (root->Trie[key[i]] == NULL) { printSuggestions(root, key.substr(0, i)); return false; } // Update root root = root->Trie[key[i]]; } if (root->isEnd == true) { return true; } printSuggestions(root, key); return false;} // Driver Codeint main(){ // Given array of strings vector<string> str = { "gee", "geeks", "ape", "apple", "geeksforgeeks" }; string key = "geek"; // Initialize a Trie TrieNode* root = new TrieNode(); // Insert strings to trie for (int i = 0; i < str.size(); i++) { InsertTrie(root, str[i]); } if (checkPresent(root, key)) { cout << "YES"; } return 0;}
// Java program to implement// the above approachimport java.io.*; // Structure of a Trie nodeclass TrieNode{ // Store address of a character TrieNode Trie[]; // Check if the character is // last character of a string or not boolean isEnd; // Constructor function public TrieNode() { Trie = new TrieNode[256]; for(int i = 0; i < 256; i++) { Trie[i] = null; } isEnd = false; }} class GFG{ // Function to insert a string into Triestatic void InsertTrie(TrieNode root, String s){ TrieNode temp = root; // Traverse the string, s for(int i = 0; i < s.length(); i++) { if (temp.Trie[s.charAt(i)] == null) { // Initialize a node temp.Trie[s.charAt(i)] = new TrieNode(); } // Update temp temp = temp.Trie[s.charAt(i)]; } // Mark the last character of // the string to true temp.isEnd = true;} // Function to print suggestions of the stringstatic void printSuggestions(TrieNode root, String res){ // If current character is // the last character of a string if (root.isEnd == true) { System.out.print(res + " "); } // Iterate over all possible // characters of the string for(int i = 0; i < 256; i++) { // If current character // present in the Trie if (root.Trie[i] != null) { // Insert current character // into Trie res += (char)i; printSuggestions(root.Trie[i], res); res = res.substring(0, res.length() - 2); } }} // Function to check if the string// is present in Trie or notstatic boolean checkPresent(TrieNode root, String key){ // Traverse the string for(int i = 0; i < key.length(); i++) { // If current character not // present in the Trie if (root.Trie[key.charAt(i)] == null) { printSuggestions(root, key.substring(0, i)); return false; } // Update root root = root.Trie[key.charAt(i)]; } if (root.isEnd == true) { return true; } printSuggestions(root, key); return false;} // Driver Codepublic static void main(String[] args){ // Given array of strings String str[] = { "gee", "geeks", "ape", "apple", "geeksforgeeks" }; String key = "geek"; // Initialize a Trie TrieNode root = new TrieNode(); // Insert strings to trie for(int i = 0; i < str.length; i++) { InsertTrie(root, str[i]); } if (checkPresent(root, key)) { System.out.println("YES"); }}} // This code is contributed by Dharanendra L V.
geeks geeksforgeeks
Time Complexity: O(N * M), where M is the maximum length of the string Auxiliary Space: O(N * 256)
dharanendralv23
Google
interview-preparation
Technical Scripter 2020
Trie
Advanced Data Structure
Hash
Strings
Technical Scripter
Google
Hash
Strings
Trie
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extendible Hashing (Dynamic approach to DBMS)
Ternary Search Tree
Proof that Dominant Set of a Graph is NP-Complete
2-3 Trees | (Search, Insert and Deletion)
Quad Tree
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Hashing | Set 3 (Open Addressing)
|
[
{
"code": null,
"e": 24095,
"s": 24067,
"text": "\n31 Mar, 2021"
},
{
"code": null,
"e": 24301,
"s": 24095,
"text": "Given an array of strings str[] and a string key, the task is to check if the spelling of the key is correct or not. If found to be true, then print “YES”. Otherwise, print the suggested correct spellings."
},
{
"code": null,
"e": 24311,
"s": 24301,
"text": "Examples:"
},
{
"code": null,
"e": 24552,
"s": 24311,
"text": "Input:str[] = { “gee”, “geeks”, “ape”, “apple”, “geeksforgeeks” }, key = “geek” Output: geeks geeksforgeeks Explanation: The string “geek” not present in the array of strings. Therefore, the suggested words are { “geeks”, “geeksforgeeks” }."
},
{
"code": null,
"e": 24637,
"s": 24552,
"text": "Input: str[] = { “gee”, “geeks”, “ape”, “apple”, “arp” }, key = “geeks” Output: YES."
},
{
"code": null,
"e": 24975,
"s": 24637,
"text": "Approach:The problem can be solved using Trie. The idea is to traverse the array of string, str[] and insert the string into the Trie such that each node of the Trie contains the character of the string and a boolean value to check if the character is the last character of the string or not. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25162,
"s": 24975,
"text": "Initialize a Trie, say root, such that each node of the Trie consists of a character of a string and a boolean value to check if the character is the last character of the string or not."
},
{
"code": null,
"e": 25241,
"s": 25162,
"text": "Traverse the array of strings arr[], and insert all the strings into the Trie."
},
{
"code": null,
"e": 25415,
"s": 25241,
"text": "Finally, traverse the string key. For every ith character, check if the character is present in the Trie or not. If found to be true, then move to the next node of the Trie."
},
{
"code": null,
"e": 25485,
"s": 25415,
"text": "Otherwise, print all possible strings whose prefix is the string key."
},
{
"code": null,
"e": 25536,
"s": 25485,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25540,
"s": 25536,
"text": "C++"
},
{
"code": null,
"e": 25545,
"s": 25540,
"text": "Java"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Structure of a Trie nodestruct TrieNode { // Store address of a character TrieNode* Trie[256]; // Check if the character is // last character of a string or not bool isEnd; // Constructor function TrieNode() { for (int i = 0; i < 256; i++) { Trie[i] = NULL; } isEnd = false; }}; // Function to insert a string into Trievoid InsertTrie(TrieNode* root, string s){ TrieNode* temp = root; // Traverse the string, s for (int i = 0; i < s.length(); i++) { if (temp->Trie[s[i]] == NULL) { // Initialize a node temp->Trie[s[i]] = new TrieNode(); } // Update temp temp = temp->Trie[s[i]]; } // Mark the last character of // the string to true temp->isEnd = true;} // Function to print suggestions of the stringvoid printSuggestions(TrieNode* root, string res){ // If current character is // the last character of a string if (root->isEnd == true) { cout << res << \" \"; } // Iterate over all possible // characters of the string for (int i = 0; i < 256; i++) { // If current character // present in the Trie if (root->Trie[i] != NULL) { // Insert current character // into Trie res.push_back(i); printSuggestions(root->Trie[i], res); res.pop_back(); } }} // Function to check if the string// is present in Trie or notbool checkPresent(TrieNode* root, string key){ // Traverse the string for (int i = 0; i < key.length(); i++) { // If current character not // present in the Trie if (root->Trie[key[i]] == NULL) { printSuggestions(root, key.substr(0, i)); return false; } // Update root root = root->Trie[key[i]]; } if (root->isEnd == true) { return true; } printSuggestions(root, key); return false;} // Driver Codeint main(){ // Given array of strings vector<string> str = { \"gee\", \"geeks\", \"ape\", \"apple\", \"geeksforgeeks\" }; string key = \"geek\"; // Initialize a Trie TrieNode* root = new TrieNode(); // Insert strings to trie for (int i = 0; i < str.size(); i++) { InsertTrie(root, str[i]); } if (checkPresent(root, key)) { cout << \"YES\"; } return 0;}",
"e": 28023,
"s": 25545,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.io.*; // Structure of a Trie nodeclass TrieNode{ // Store address of a character TrieNode Trie[]; // Check if the character is // last character of a string or not boolean isEnd; // Constructor function public TrieNode() { Trie = new TrieNode[256]; for(int i = 0; i < 256; i++) { Trie[i] = null; } isEnd = false; }} class GFG{ // Function to insert a string into Triestatic void InsertTrie(TrieNode root, String s){ TrieNode temp = root; // Traverse the string, s for(int i = 0; i < s.length(); i++) { if (temp.Trie[s.charAt(i)] == null) { // Initialize a node temp.Trie[s.charAt(i)] = new TrieNode(); } // Update temp temp = temp.Trie[s.charAt(i)]; } // Mark the last character of // the string to true temp.isEnd = true;} // Function to print suggestions of the stringstatic void printSuggestions(TrieNode root, String res){ // If current character is // the last character of a string if (root.isEnd == true) { System.out.print(res + \" \"); } // Iterate over all possible // characters of the string for(int i = 0; i < 256; i++) { // If current character // present in the Trie if (root.Trie[i] != null) { // Insert current character // into Trie res += (char)i; printSuggestions(root.Trie[i], res); res = res.substring(0, res.length() - 2); } }} // Function to check if the string// is present in Trie or notstatic boolean checkPresent(TrieNode root, String key){ // Traverse the string for(int i = 0; i < key.length(); i++) { // If current character not // present in the Trie if (root.Trie[key.charAt(i)] == null) { printSuggestions(root, key.substring(0, i)); return false; } // Update root root = root.Trie[key.charAt(i)]; } if (root.isEnd == true) { return true; } printSuggestions(root, key); return false;} // Driver Codepublic static void main(String[] args){ // Given array of strings String str[] = { \"gee\", \"geeks\", \"ape\", \"apple\", \"geeksforgeeks\" }; String key = \"geek\"; // Initialize a Trie TrieNode root = new TrieNode(); // Insert strings to trie for(int i = 0; i < str.length; i++) { InsertTrie(root, str[i]); } if (checkPresent(root, key)) { System.out.println(\"YES\"); }}} // This code is contributed by Dharanendra L V.",
"e": 30749,
"s": 28023,
"text": null
},
{
"code": null,
"e": 30769,
"s": 30749,
"text": "geeks geeksforgeeks"
},
{
"code": null,
"e": 30870,
"s": 30771,
"text": "Time Complexity: O(N * M), where M is the maximum length of the string Auxiliary Space: O(N * 256)"
},
{
"code": null,
"e": 30886,
"s": 30870,
"text": "dharanendralv23"
},
{
"code": null,
"e": 30893,
"s": 30886,
"text": "Google"
},
{
"code": null,
"e": 30915,
"s": 30893,
"text": "interview-preparation"
},
{
"code": null,
"e": 30939,
"s": 30915,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 30944,
"s": 30939,
"text": "Trie"
},
{
"code": null,
"e": 30968,
"s": 30944,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 30973,
"s": 30968,
"text": "Hash"
},
{
"code": null,
"e": 30981,
"s": 30973,
"text": "Strings"
},
{
"code": null,
"e": 31000,
"s": 30981,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31007,
"s": 31000,
"text": "Google"
},
{
"code": null,
"e": 31012,
"s": 31007,
"text": "Hash"
},
{
"code": null,
"e": 31020,
"s": 31012,
"text": "Strings"
},
{
"code": null,
"e": 31025,
"s": 31020,
"text": "Trie"
},
{
"code": null,
"e": 31123,
"s": 31025,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31132,
"s": 31123,
"text": "Comments"
},
{
"code": null,
"e": 31145,
"s": 31132,
"text": "Old Comments"
},
{
"code": null,
"e": 31191,
"s": 31145,
"text": "Extendible Hashing (Dynamic approach to DBMS)"
},
{
"code": null,
"e": 31211,
"s": 31191,
"text": "Ternary Search Tree"
},
{
"code": null,
"e": 31261,
"s": 31211,
"text": "Proof that Dominant Set of a Graph is NP-Complete"
},
{
"code": null,
"e": 31303,
"s": 31261,
"text": "2-3 Trees | (Search, Insert and Deletion)"
},
{
"code": null,
"e": 31313,
"s": 31303,
"text": "Quad Tree"
},
{
"code": null,
"e": 31398,
"s": 31313,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 31434,
"s": 31398,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 31465,
"s": 31434,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 31492,
"s": 31465,
"text": "Count pairs with given sum"
}
] |
How to make a unique field in MongoDB?
|
To make a unique field in MongoDB, use unique − true. Let us create a collection with documents −
> db.demo82.createIndex({"EmployeeName":1},{unique:true});
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.demo82.insertOne({"EmployeeName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2bfb1b71bf0181ecc422a0")
}
> db.demo82.insertOne({"EmployeeName":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2bfb1f71bf0181ecc422a1")
}
> db.demo82.insertOne({"EmployeeName":"Chris"});
2020-01-25T13:54:00.410+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: test.demo82 index: EmployeeName_1 dup key: { : "Chris" } :
WriteError({
"index" : 0,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: test.demo82 index: EmployeeName_1 dup key: { : \"Chris\" }",
"op" : {
"_id" : ObjectId("5e2bfb2071bf0181ecc422a2"),
"EmployeeName" : "Chris"
}
})
WriteError@src/mongo/shell/bulk_api.js:461:48
Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49
Bulk/executeBatch@src/mongo/shell/bulk_api.js:906:13
Bulk/this.execute@src/mongo/shell/bulk_api.js:1150:21
DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9
@(shell):1:1
Display all documents from a collection with the help of find() method −
> db.demo82.find();
This will produce the following output. Since, we use unique − true above, therefore the duplicate values won’t get insert −
{ "_id" : ObjectId("5e2bfb1b71bf0181ecc422a0"), "EmployeeName" : "Chris" }
{ "_id" : ObjectId("5e2bfb1f71bf0181ecc422a1"), "EmployeeName" : "David" }
|
[
{
"code": null,
"e": 1160,
"s": 1062,
"text": "To make a unique field in MongoDB, use unique − true. Let us create a collection with documents −"
},
{
"code": null,
"e": 2358,
"s": 1160,
"text": "> db.demo82.createIndex({\"EmployeeName\":1},{unique:true});\n{\n \"createdCollectionAutomatically\" : true,\n \"numIndexesBefore\" : 1,\n \"numIndexesAfter\" : 2,\n \"ok\" : 1\n}\n> db.demo82.insertOne({\"EmployeeName\":\"Chris\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e2bfb1b71bf0181ecc422a0\")\n}\n> db.demo82.insertOne({\"EmployeeName\":\"David\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e2bfb1f71bf0181ecc422a1\")\n}\n> db.demo82.insertOne({\"EmployeeName\":\"Chris\"});\n2020-01-25T13:54:00.410+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: test.demo82 index: EmployeeName_1 dup key: { : \"Chris\" } :\nWriteError({\n \"index\" : 0,\n \"code\" : 11000,\n \"errmsg\" : \"E11000 duplicate key error collection: test.demo82 index: EmployeeName_1 dup key: { : \\\"Chris\\\" }\",\n \"op\" : {\n \"_id\" : ObjectId(\"5e2bfb2071bf0181ecc422a2\"),\n \"EmployeeName\" : \"Chris\"\n }\n})\nWriteError@src/mongo/shell/bulk_api.js:461:48\nBulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49\nBulk/executeBatch@src/mongo/shell/bulk_api.js:906:13\nBulk/this.execute@src/mongo/shell/bulk_api.js:1150:21\nDBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9\n@(shell):1:1"
},
{
"code": null,
"e": 2431,
"s": 2358,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 2451,
"s": 2431,
"text": "> db.demo82.find();"
},
{
"code": null,
"e": 2576,
"s": 2451,
"text": "This will produce the following output. Since, we use unique − true above, therefore the duplicate values won’t get insert −"
},
{
"code": null,
"e": 2726,
"s": 2576,
"text": "{ \"_id\" : ObjectId(\"5e2bfb1b71bf0181ecc422a0\"), \"EmployeeName\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5e2bfb1f71bf0181ecc422a1\"), \"EmployeeName\" : \"David\" }"
}
] |
Kafka No Longer Requires ZooKeeper | by Giorgos Myrianthous | Towards Data Science
|
Apache Kafka 2.8.0 is finally out and you can now have early-access to KIP-500 that removes the Apache Zookeeper dependency. Instead, Kafka now relies on an internal Raft quorum that can be activated through Kafka Raft metadata mode. The new feature simplifies cluster administration and infrastructure management and marks a new era for Kafka itself.
Zookeeper-less Kafka
In this article we are going to discuss why there was a need for removing ZooKeeper dependency in the first place. Additionally, we will discuss how ZooKeeper has been replaced by KRaft mode as of version 2.8.0 and also explore the impact of removing this dependency and how Kafka itself will benefit from this enhancement.
Until now, Apache ZooKeeper was used by Kafka as a metadata store. Metadata for partitions and brokers were stored to the ZooKeeper quorum that was also responsible for Kafka Controller election.
ZooKeeper is an external system to Kafka which means that it comes with its own configuration syntax, management tools and best practices. Therefore, if you wanted to deploy a Kafka cluster then you would also had to manage, deploy, and monitor Zookeeper as well. Since these two distributed systems require different configuration the level of complexity increases and thus it is much easier for system administrators to make mistakes. Having two systems also leads to duplication of work— for example, in order to enable security features you would have to apply the relevant configuration to both services.
Having an external metadata store is inefficient in terms of resources as you need to run additional processes. Furthermore, this limits the scalability of Kafka itself. Every time the cluster is starting up, the Kafka controller must load the state of the cluster from ZooKeeper.
The same happens when a new controller is being elected. Given that the amount of metadata gets bigger over time, this means that the loading of such metadata becomes more inefficient over time leading to high loading processes and thus it limits the number of partitions the cluster can store.
KPI stands for Kafka Improvement Proposals and KPI-500 introduces the fundamental architecture of ZooKeeper-less Kafka.
Version 2.8.0 introduces an early access to Zookeeper-Less Kafka as part of KPI-500. Note though that the implementation is partially complete and thus you should not use it in production environments.
In the latest release, ZooKeeper can be replaced by an internal Raft quorum of controllers. When Kafka Raft Metadata mode is enabled, Kafka will store its metadata and configurations into a topic called @metadata. This internal topic is managed by the internal quorum and replicated across the cluster. The nodes of the cluster can now serve as brokers, controllers or both (called combined nodes).
When KRaft mode is enabled, only a few selected servers can serve as controllers and these will compose the internal quorum. The controllers can either be in active or standby mode that will eventually take over if the current active controller server fails or is taken down.
Now every Kafka Server comes with an additional configuration parameter called process.roles. This parameter can take the following values:
broker: The Kafka Server will serve as a broker
controller: The Kafka Server will serve as a controller of the internal Raft quorum
broker,controller: The Kafka Server will serve as both a controller of the quorum and a broker
Note that when process.roles is not provided at all, it is assume that the cluster will run in ZooKeeper mode. Therefore, for time being process.roles configuration parameter is the only way you can activate KRaft mode.
Additionally, each node is now identified with its node.id and must now provide controller.quorum.voters configuration parameter which is the equivalent to zookeeper.connect in ZooKeeper mode. This parameter is used to identify the controller servers of the internal quorum and the format used for the values is serverID@host:port, serverID@host:port, ....
Now let’s assume that within our Kafka Cluster which is running in KRaft mode we have 7 brokers and 3 controllers. The snippet below demonstrates an example configuration for one of the controller servers in the Raft quorum.
process.roles=controllernode.id=1listeners=CONTROLLER://controller-1-host:9092controller.quorum.voters=1@controller-1-host:9092,2@controller-2-host:9092,3@controller-3-host:9092
Likewise, the below configuration demonstrates how to setup one of the brokers of the cluster:
process.roles=brokernode.id=4listeners=PLAINTEXT://:9092controller.quorum.voters=1@controller-1-host:9092,2@controller-2-host:9092,3@controller-3-host:9092
The removal of Apache ZooKeeper dependency is definitely a step forward for the platform. The whole community (and I’d say Confluent in particular) has been working towards this direction for the last few years. The earliest release has been a tremendous effort of the whole Kafka community that is still working on improvements so that ZooKeeper-Less Kafka mode is feature-complete within this year.
We’ve been headed this direction for years
— Jason Gustafson @ Kafka Summit San Francisco 2019
The removal of Apache ZooKeeper dependency simplifies the infrastructure management for Kafka deployments. Kafka and ZooKeeper are two distinct services — now that Kafka has been unified so that it is not dependent on external services to server as metadata stores, the learning curve will be shortened and this will eventually help broaden Kafka’s adoption.
Furthermore, this enhancement offers a more scalable and robust overall architecture. As discussed earlier, in ZooKeeper mode Kafka had to store its metadata into ZooKeeper nodes. Every time the cluster was starting up or a controller election was happening, Kafka Controllers had to read the metadata from an external service which was inefficient. By replacing ZooKeeper with this internal Raft quorum, deployments can now support more partitions.
Removing the ZooKeeper dependency also enables the support of clusters with single node. When you want test Kafka as part of a proof of concept you no longer have to start multiple processes.
The removal of Zookeeper dependency is a huge step forward for Kafka. In fact, the new KRaft mode feature will extend scalability capabilities of Apache Kafka and also shorten the learning curve since now teams won’t have to worry about ZooKeeper any longer. It will also make Kafka configuration and deployment way easier and more efficient.
In addition to KPI-500, Kafka 2.8.0 comes with numerous improvements and bug fixes so make sure to take a look at the release notes.
Finally, I want to highlight once again that this is currently an early-access which means it should not be used in production environments.
|
[
{
"code": null,
"e": 524,
"s": 172,
"text": "Apache Kafka 2.8.0 is finally out and you can now have early-access to KIP-500 that removes the Apache Zookeeper dependency. Instead, Kafka now relies on an internal Raft quorum that can be activated through Kafka Raft metadata mode. The new feature simplifies cluster administration and infrastructure management and marks a new era for Kafka itself."
},
{
"code": null,
"e": 545,
"s": 524,
"text": "Zookeeper-less Kafka"
},
{
"code": null,
"e": 869,
"s": 545,
"text": "In this article we are going to discuss why there was a need for removing ZooKeeper dependency in the first place. Additionally, we will discuss how ZooKeeper has been replaced by KRaft mode as of version 2.8.0 and also explore the impact of removing this dependency and how Kafka itself will benefit from this enhancement."
},
{
"code": null,
"e": 1065,
"s": 869,
"text": "Until now, Apache ZooKeeper was used by Kafka as a metadata store. Metadata for partitions and brokers were stored to the ZooKeeper quorum that was also responsible for Kafka Controller election."
},
{
"code": null,
"e": 1675,
"s": 1065,
"text": "ZooKeeper is an external system to Kafka which means that it comes with its own configuration syntax, management tools and best practices. Therefore, if you wanted to deploy a Kafka cluster then you would also had to manage, deploy, and monitor Zookeeper as well. Since these two distributed systems require different configuration the level of complexity increases and thus it is much easier for system administrators to make mistakes. Having two systems also leads to duplication of work— for example, in order to enable security features you would have to apply the relevant configuration to both services."
},
{
"code": null,
"e": 1956,
"s": 1675,
"text": "Having an external metadata store is inefficient in terms of resources as you need to run additional processes. Furthermore, this limits the scalability of Kafka itself. Every time the cluster is starting up, the Kafka controller must load the state of the cluster from ZooKeeper."
},
{
"code": null,
"e": 2251,
"s": 1956,
"text": "The same happens when a new controller is being elected. Given that the amount of metadata gets bigger over time, this means that the loading of such metadata becomes more inefficient over time leading to high loading processes and thus it limits the number of partitions the cluster can store."
},
{
"code": null,
"e": 2371,
"s": 2251,
"text": "KPI stands for Kafka Improvement Proposals and KPI-500 introduces the fundamental architecture of ZooKeeper-less Kafka."
},
{
"code": null,
"e": 2573,
"s": 2371,
"text": "Version 2.8.0 introduces an early access to Zookeeper-Less Kafka as part of KPI-500. Note though that the implementation is partially complete and thus you should not use it in production environments."
},
{
"code": null,
"e": 2972,
"s": 2573,
"text": "In the latest release, ZooKeeper can be replaced by an internal Raft quorum of controllers. When Kafka Raft Metadata mode is enabled, Kafka will store its metadata and configurations into a topic called @metadata. This internal topic is managed by the internal quorum and replicated across the cluster. The nodes of the cluster can now serve as brokers, controllers or both (called combined nodes)."
},
{
"code": null,
"e": 3248,
"s": 2972,
"text": "When KRaft mode is enabled, only a few selected servers can serve as controllers and these will compose the internal quorum. The controllers can either be in active or standby mode that will eventually take over if the current active controller server fails or is taken down."
},
{
"code": null,
"e": 3388,
"s": 3248,
"text": "Now every Kafka Server comes with an additional configuration parameter called process.roles. This parameter can take the following values:"
},
{
"code": null,
"e": 3436,
"s": 3388,
"text": "broker: The Kafka Server will serve as a broker"
},
{
"code": null,
"e": 3520,
"s": 3436,
"text": "controller: The Kafka Server will serve as a controller of the internal Raft quorum"
},
{
"code": null,
"e": 3615,
"s": 3520,
"text": "broker,controller: The Kafka Server will serve as both a controller of the quorum and a broker"
},
{
"code": null,
"e": 3835,
"s": 3615,
"text": "Note that when process.roles is not provided at all, it is assume that the cluster will run in ZooKeeper mode. Therefore, for time being process.roles configuration parameter is the only way you can activate KRaft mode."
},
{
"code": null,
"e": 4192,
"s": 3835,
"text": "Additionally, each node is now identified with its node.id and must now provide controller.quorum.voters configuration parameter which is the equivalent to zookeeper.connect in ZooKeeper mode. This parameter is used to identify the controller servers of the internal quorum and the format used for the values is serverID@host:port, serverID@host:port, ...."
},
{
"code": null,
"e": 4417,
"s": 4192,
"text": "Now let’s assume that within our Kafka Cluster which is running in KRaft mode we have 7 brokers and 3 controllers. The snippet below demonstrates an example configuration for one of the controller servers in the Raft quorum."
},
{
"code": null,
"e": 4595,
"s": 4417,
"text": "process.roles=controllernode.id=1listeners=CONTROLLER://controller-1-host:9092controller.quorum.voters=1@controller-1-host:9092,2@controller-2-host:9092,3@controller-3-host:9092"
},
{
"code": null,
"e": 4690,
"s": 4595,
"text": "Likewise, the below configuration demonstrates how to setup one of the brokers of the cluster:"
},
{
"code": null,
"e": 4846,
"s": 4690,
"text": "process.roles=brokernode.id=4listeners=PLAINTEXT://:9092controller.quorum.voters=1@controller-1-host:9092,2@controller-2-host:9092,3@controller-3-host:9092"
},
{
"code": null,
"e": 5247,
"s": 4846,
"text": "The removal of Apache ZooKeeper dependency is definitely a step forward for the platform. The whole community (and I’d say Confluent in particular) has been working towards this direction for the last few years. The earliest release has been a tremendous effort of the whole Kafka community that is still working on improvements so that ZooKeeper-Less Kafka mode is feature-complete within this year."
},
{
"code": null,
"e": 5290,
"s": 5247,
"text": "We’ve been headed this direction for years"
},
{
"code": null,
"e": 5342,
"s": 5290,
"text": "— Jason Gustafson @ Kafka Summit San Francisco 2019"
},
{
"code": null,
"e": 5701,
"s": 5342,
"text": "The removal of Apache ZooKeeper dependency simplifies the infrastructure management for Kafka deployments. Kafka and ZooKeeper are two distinct services — now that Kafka has been unified so that it is not dependent on external services to server as metadata stores, the learning curve will be shortened and this will eventually help broaden Kafka’s adoption."
},
{
"code": null,
"e": 6151,
"s": 5701,
"text": "Furthermore, this enhancement offers a more scalable and robust overall architecture. As discussed earlier, in ZooKeeper mode Kafka had to store its metadata into ZooKeeper nodes. Every time the cluster was starting up or a controller election was happening, Kafka Controllers had to read the metadata from an external service which was inefficient. By replacing ZooKeeper with this internal Raft quorum, deployments can now support more partitions."
},
{
"code": null,
"e": 6343,
"s": 6151,
"text": "Removing the ZooKeeper dependency also enables the support of clusters with single node. When you want test Kafka as part of a proof of concept you no longer have to start multiple processes."
},
{
"code": null,
"e": 6686,
"s": 6343,
"text": "The removal of Zookeeper dependency is a huge step forward for Kafka. In fact, the new KRaft mode feature will extend scalability capabilities of Apache Kafka and also shorten the learning curve since now teams won’t have to worry about ZooKeeper any longer. It will also make Kafka configuration and deployment way easier and more efficient."
},
{
"code": null,
"e": 6819,
"s": 6686,
"text": "In addition to KPI-500, Kafka 2.8.0 comes with numerous improvements and bug fixes so make sure to take a look at the release notes."
}
] |
Bootstrap 4 - Images
|
Bootstrap 4 provides support for images by using <img> tag. It provides three classes that can be used to apply some simple styles to images −
.img-rounded − You can make rounded corners to an image by using .rounded class.
.img-rounded − You can make rounded corners to an image by using .rounded class.
.img-circle − You can make image as circle by using .rounded-circle class.
.img-circle − You can make image as circle by using .rounded-circle class.
.img-thumbnail − You can make image as thumbnail (rounded 1 pixel border) by using .img-thumbnail class.
.img-thumbnail − You can make image as thumbnail (rounded 1 pixel border) by using .img-thumbnail class.
The following example demonstrates usage of above classes to style an image −
<html lang = "en">
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin = "anonymous">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h2>Rounded Corners Image</h2>
<img src = "https://www.tutorialspoint.com/bootstrap/images/64.jpg"
class = "rounded" alt = "Rounded Image" width = "200" height = "200">
<p></p>
<h2>Circle Image</h2>
<img src = "https://www.tutorialspoint.com/bootstrap/images/64.jpg"
class = "rounded-circle" alt = "Rounded Image" width = "200" height = "200">
<p></p>
<h2>Thumbnail Image</h2>
<img src = "https://www.tutorialspoint.com/bootstrap/images/64.jpg"
class = "img-thumbnail" alt = "Rounded Image" width = "200" height = "200">
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin = "anonymous">
</script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin = "anonymous">
</script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result −
Image can be moved to the left by using .float-left class and to right by using .float-right class.
The following example demonstrates alignment of images −
<html lang = "en">
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin = "anonymous">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h2>Aligning Images</h2>
<br>
<img src = "https://www.tutorialspoint.com/bootstrap/images/64.jpg"
class = "float-left" alt = "Left Image" width = "200" height = "200">
<img src = "https://www.tutorialspoint.com/bootstrap/images/64.jpg"
class = "float-right" alt = "Right Image" width = "200" height = "200">
<p></p>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin = "anonymous">
</script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin = "anonymous">
</script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result −
You can place an image in the center by using .mx-auto (margin:auto) and .d-block (display:block) classes.
The following example shows placing of an image in the center −
<html lang = "en">
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin = "anonymous">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h2>Centered Image</h2>
<img src = "https://www.tutorialspoint.com/bootstrap/images/64.jpg"
class = "mx-auto d-block" alt = "Center Image" width = "200" height = "200">
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin = "anonymous">
</script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin = "anonymous">
</script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result −
You can make the responsive images (automatically adjust to fit the size of the screen across devices) by using the .img-fluid class (provides max-width: 100%; and height: auto; to the image).
The following example demonstrates displaying of responsive in the document −
<html lang = "en">
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin = "anonymous">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class="container">
<h2>Responsive Image</h2>
<img src = "https://www.tutorialspoint.com/bootstrap/images/64.jpg"
class = "img-fluid" alt = "Responsive Image" width = "200" height = "200">
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin = "anonymous">
</script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin = "anonymous">
</script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result −
26 Lectures
2 hours
Anadi Sharma
54 Lectures
4.5 hours
Frahaan Hussain
161 Lectures
14.5 hours
Eduonix Learning Solutions
20 Lectures
4 hours
Azaz Patel
15 Lectures
1.5 hours
Muhammad Ismail
62 Lectures
8 hours
Yossef Ayman Zedan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1959,
"s": 1816,
"text": "Bootstrap 4 provides support for images by using <img> tag. It provides three classes that can be used to apply some simple styles to images −"
},
{
"code": null,
"e": 2040,
"s": 1959,
"text": ".img-rounded − You can make rounded corners to an image by using .rounded class."
},
{
"code": null,
"e": 2121,
"s": 2040,
"text": ".img-rounded − You can make rounded corners to an image by using .rounded class."
},
{
"code": null,
"e": 2196,
"s": 2121,
"text": ".img-circle − You can make image as circle by using .rounded-circle class."
},
{
"code": null,
"e": 2271,
"s": 2196,
"text": ".img-circle − You can make image as circle by using .rounded-circle class."
},
{
"code": null,
"e": 2377,
"s": 2271,
"text": ".img-thumbnail − You can make image as thumbnail (rounded 1 pixel border) by using .img-thumbnail class."
},
{
"code": null,
"e": 2483,
"s": 2377,
"text": ".img-thumbnail − You can make image as thumbnail (rounded 1 pixel border) by using .img-thumbnail class."
},
{
"code": null,
"e": 2561,
"s": 2483,
"text": "The following example demonstrates usage of above classes to style an image −"
},
{
"code": null,
"e": 4628,
"s": 2561,
"text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Rounded Corners Image</h2>\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/64.jpg\" \n class = \"rounded\" alt = \"Rounded Image\" width = \"200\" height = \"200\"> \n \n <p></p>\n <h2>Circle Image</h2>\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/64.jpg\" \n class = \"rounded-circle\" alt = \"Rounded Image\" width = \"200\" height = \"200\">\n \n <p></p>\n <h2>Thumbnail Image</h2>\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/64.jpg\"\n class = \"img-thumbnail\" alt = \"Rounded Image\" width = \"200\" height = \"200\">\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 4667,
"s": 4628,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 4767,
"s": 4667,
"text": "Image can be moved to the left by using .float-left class and to right by using .float-right class."
},
{
"code": null,
"e": 4824,
"s": 4767,
"text": "The following example demonstrates alignment of images −"
},
{
"code": null,
"e": 6650,
"s": 4824,
"text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Aligning Images</h2>\n <br>\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/64.jpg\" \n class = \"float-left\" alt = \"Left Image\" width = \"200\" height = \"200\"> \n \n <img src = \"https://www.tutorialspoint.com/bootstrap/images/64.jpg\" \n class = \"float-right\" alt = \"Right Image\" width = \"200\" height = \"200\">\n \n <p></p>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 6689,
"s": 6650,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 6796,
"s": 6689,
"text": "You can place an image in the center by using .mx-auto (margin:auto) and .d-block (display:block) classes."
},
{
"code": null,
"e": 6860,
"s": 6796,
"text": "The following example shows placing of an image in the center −"
},
{
"code": null,
"e": 8475,
"s": 6860,
"text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Centered Image</h2>\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/64.jpg\" \n class = \"mx-auto d-block\" alt = \"Center Image\" width = \"200\" height = \"200\">\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 8514,
"s": 8475,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 8707,
"s": 8514,
"text": "You can make the responsive images (automatically adjust to fit the size of the screen across devices) by using the .img-fluid class (provides max-width: 100%; and height: auto; to the image)."
},
{
"code": null,
"e": 8785,
"s": 8707,
"text": "The following example demonstrates displaying of responsive in the document −"
},
{
"code": null,
"e": 10394,
"s": 8785,
"text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n <body>\n <div class=\"container\">\n <h2>Responsive Image</h2>\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/64.jpg\" \n class = \"img-fluid\" alt = \"Responsive Image\" width = \"200\" height = \"200\">\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 10433,
"s": 10394,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 10466,
"s": 10433,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 10480,
"s": 10466,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 10515,
"s": 10480,
"text": "\n 54 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 10532,
"s": 10515,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 10569,
"s": 10532,
"text": "\n 161 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 10597,
"s": 10569,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 10630,
"s": 10597,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 10642,
"s": 10630,
"text": " Azaz Patel"
},
{
"code": null,
"e": 10677,
"s": 10642,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10694,
"s": 10677,
"text": " Muhammad Ismail"
},
{
"code": null,
"e": 10727,
"s": 10694,
"text": "\n 62 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 10747,
"s": 10727,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 10754,
"s": 10747,
"text": " Print"
},
{
"code": null,
"e": 10765,
"s": 10754,
"text": " Add Notes"
}
] |
Multiples of 3 or 7 - GeeksforGeeks
|
16 Aug, 2021
Given a positive integer n, find count of all multiples of 3 or 7 less than or equal to n.Examples :
Input : n = 10
Output : Count = 4
The multiples are 3, 6, 7 and 9
Input : n = 25
Output : Count = 10
The multiples are 3, 6, 7, 9, 12, 14, 15, 18, 21 and 24
A Simple Solution is to iterate over all numbers from 1 to n and increment count whenever a number is a multiple of 3 or 7 or both.
C++
Java
Python3
C#
PHP
Javascript
// A Simple C++ program to find count of all// numbers that multiples#include<iostream>using namespace std; // Returns count of all numbers smaller than// or equal to n and multiples of 3 or 7 or bothint countMultiples(int n){ int res = 0; for (int i=1; i<=n; i++) if (i%3==0 || i%7 == 0) res++; return res;} // Driver codeint main(){ cout << "Count = " << countMultiples(25);}
// A Simple Java program to// find count of all numbers// that multiplesimport java.io.*; class GFG{ // Returns count of all numbers// smaller than or equal to n// and multiples of 3 or 7 or bothstatic int countMultiples(int n){ int res = 0; for (int i = 1; i <= n; i++) if (i % 3 == 0 || i % 7 == 0) res++; return res;} // Driver Codepublic static void main (String[] args){ System.out.print("Count = "); System.out.println(countMultiples(25));}} // This code is contributed by m_kit
# A Simple Python3 program to# find count of all numbers# that multiples # Returns count of all numbers# smaller than or equal to n# and multiples of 3 or 7 or bothdef countMultiples(n): res = 0; for i in range(1, n + 1): if (i % 3 == 0 or i % 7 == 0): res += 1; return res; # Driver codeprint("Count =", countMultiples(25)); # This code is contributed by mits
// A Simple C# program to// find count of all numbers// that are multiples of 3 or 7using System; class GFG{ // Returns count of all // numbers smaller than// or equal to n and// are multiples of 3 or// 7 or bothstatic int countMultiples(int n){ int res = 0; for (int i = 1; i <= n; i++) if (i % 3 == 0 || i % 7 == 0) res++; return res;} // Driver Codestatic public void Main (){ Console.Write("Count = "); Console.WriteLine(countMultiples(25));}} // This code is contributed by ajit
<?php// A Simple PHP program to find count// of all numbers that multiples // Returns count of all numbers// smaller than or equal to n// and multiples of 3 or 7 or bothfunction countMultiples($n){ $res = 0; for ($i = 1; $i <= $n; $i++) if ($i % 3 == 0 || $i % 7 == 0) $res++; return $res;} // Driver codeecho "Count = " ,countMultiples(25); // This code is contributed by aj_36?>
<script> // A Simple JavaScript program to find count// of all numbers that multiples // Returns count of all numbers// smaller than or equal to n// and multiples of 3 or 7 or bothfunction countMultiples(n){ let res = 0; for (let i = 1; i <= n; i++) if (i % 3 == 0 || i % 7 == 0) res++; return res;} // Driver codedocument.write( "Count = " +countMultiples(25)); // This code is contributed by bobby </script>
Output :
Count = 10
Time Complexity : O(n)An efficient solution can solve the above problem in O(1) time. The idea is to count multiples of 3 and add multiples of 7, then subtract multiples of 21 because these are counted twice.
count = n/3 + n/7 - n/21
C++
Java
Python 3
C#
PHP
Javascript
// A better C++ program to find count of all// numbers that multiples#include<iostream>using namespace std; // Returns count of all numbers smaller than// or equal to n and multiples of 3 or 7 or bothint countMultiples(int n){ return n/3 + n/7 -n/21;} // Driver codeint main(){ cout << "Count = " << countMultiples(25);}
// A better Java program to// find count of all numbers// that multiplesimport java.io.*; class GFG{ // Returns count of all numbers// smaller than or equal to n// and multiples of 3 or 7 or bothstatic int countMultiples(int n){ return n / 3 + n / 7 - n / 21;} // Driver codepublic static void main (String args [] ){ System.out.println("Count = " + countMultiples(25));}} // This code is contributed by aj_36
# Python 3 program to find count of# all numbers that multiples # Returns count of all numbers# smaller than or equal to n and# multiples of 3 or 7 or bothdef countMultiples(n): return n / 3 + n / 7 - n / 21; # Driver coden = ((int)(countMultiples(25)));print("Count =", n); # This code is contributed# by Shivi_Aggarwal
// A better Java program to// find count of all numbers// that multiplesusing System; class GFG{ // Returns count of all numbers// smaller than or equal to n// and multiples of 3 or 7 or bothstatic int countMultiples(int n){ return n / 3 + n / 7 - n / 21;} // Driver Codestatic public void Main (){ Console.WriteLine("Count = " + countMultiples(25));}} // This code is contributed by m_kit
<?php// A better PHP program to find count// of all numbers that multiples // Returns count of all numbers// smaller than or equal to n// and multiples of 3 or 7 or bothfunction countMultiples($n){return floor($n / 3 + $n / 7 - $n / 21);} // Driver codeecho "Count = " , countMultiples(25); // This code is contributed by ajit?>
<script> // JavaScript program to find count// of all numbers that multiples // Returns count of all numbers// smaller than or equal to n// and multiples of 3 or 7 or bothfunction countMultiples(n){return Math.floor(n / 3 + n / 7 - n / 21);} // Driver codedocument.write( "Count = " +countMultiples(25)); // This code is contributed by bobby </script>
Output :
Count = 10
Time Complexity : O(1)Exercise: Now try the problem of finding sum of all numbers less than or equal to n and multiples of 3 or 7 or both in O(1) time.This article is contributed by Saurabh Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
jit_t
Mithun Kumar
Shivi_Aggarwal
gottumukkalabobby
surinderdawra388
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find sum of elements in a given array
The Knight's tour problem | Backtracking-1
Euclidean algorithms (Basic and Extended)
Program to convert a given number to words
Algorithm to solve Rubik's Cube
Modular multiplicative inverse
Print all possible combinations of r elements in a given array of size n
Find minimum number of coins that make a given value
Program to find LCM of two numbers
Program to count digits in an integer (4 Different Methods)
|
[
{
"code": null,
"e": 24622,
"s": 24594,
"text": "\n16 Aug, 2021"
},
{
"code": null,
"e": 24724,
"s": 24622,
"text": "Given a positive integer n, find count of all multiples of 3 or 7 less than or equal to n.Examples : "
},
{
"code": null,
"e": 24882,
"s": 24724,
"text": "Input : n = 10\nOutput : Count = 4\nThe multiples are 3, 6, 7 and 9\n\nInput : n = 25\nOutput : Count = 10\nThe multiples are 3, 6, 7, 9, 12, 14, 15, 18, 21 and 24"
},
{
"code": null,
"e": 25015,
"s": 24882,
"text": "A Simple Solution is to iterate over all numbers from 1 to n and increment count whenever a number is a multiple of 3 or 7 or both. "
},
{
"code": null,
"e": 25019,
"s": 25015,
"text": "C++"
},
{
"code": null,
"e": 25024,
"s": 25019,
"text": "Java"
},
{
"code": null,
"e": 25032,
"s": 25024,
"text": "Python3"
},
{
"code": null,
"e": 25035,
"s": 25032,
"text": "C#"
},
{
"code": null,
"e": 25039,
"s": 25035,
"text": "PHP"
},
{
"code": null,
"e": 25050,
"s": 25039,
"text": "Javascript"
},
{
"code": "// A Simple C++ program to find count of all// numbers that multiples#include<iostream>using namespace std; // Returns count of all numbers smaller than// or equal to n and multiples of 3 or 7 or bothint countMultiples(int n){ int res = 0; for (int i=1; i<=n; i++) if (i%3==0 || i%7 == 0) res++; return res;} // Driver codeint main(){ cout << \"Count = \" << countMultiples(25);}",
"e": 25456,
"s": 25050,
"text": null
},
{
"code": "// A Simple Java program to// find count of all numbers// that multiplesimport java.io.*; class GFG{ // Returns count of all numbers// smaller than or equal to n// and multiples of 3 or 7 or bothstatic int countMultiples(int n){ int res = 0; for (int i = 1; i <= n; i++) if (i % 3 == 0 || i % 7 == 0) res++; return res;} // Driver Codepublic static void main (String[] args){ System.out.print(\"Count = \"); System.out.println(countMultiples(25));}} // This code is contributed by m_kit",
"e": 25971,
"s": 25456,
"text": null
},
{
"code": "# A Simple Python3 program to# find count of all numbers# that multiples # Returns count of all numbers# smaller than or equal to n# and multiples of 3 or 7 or bothdef countMultiples(n): res = 0; for i in range(1, n + 1): if (i % 3 == 0 or i % 7 == 0): res += 1; return res; # Driver codeprint(\"Count =\", countMultiples(25)); # This code is contributed by mits",
"e": 26361,
"s": 25971,
"text": null
},
{
"code": "// A Simple C# program to// find count of all numbers// that are multiples of 3 or 7using System; class GFG{ // Returns count of all // numbers smaller than// or equal to n and// are multiples of 3 or// 7 or bothstatic int countMultiples(int n){ int res = 0; for (int i = 1; i <= n; i++) if (i % 3 == 0 || i % 7 == 0) res++; return res;} // Driver Codestatic public void Main (){ Console.Write(\"Count = \"); Console.WriteLine(countMultiples(25));}} // This code is contributed by ajit",
"e": 26876,
"s": 26361,
"text": null
},
{
"code": "<?php// A Simple PHP program to find count// of all numbers that multiples // Returns count of all numbers// smaller than or equal to n// and multiples of 3 or 7 or bothfunction countMultiples($n){ $res = 0; for ($i = 1; $i <= $n; $i++) if ($i % 3 == 0 || $i % 7 == 0) $res++; return $res;} // Driver codeecho \"Count = \" ,countMultiples(25); // This code is contributed by aj_36?>",
"e": 27277,
"s": 26876,
"text": null
},
{
"code": "<script> // A Simple JavaScript program to find count// of all numbers that multiples // Returns count of all numbers// smaller than or equal to n// and multiples of 3 or 7 or bothfunction countMultiples(n){ let res = 0; for (let i = 1; i <= n; i++) if (i % 3 == 0 || i % 7 == 0) res++; return res;} // Driver codedocument.write( \"Count = \" +countMultiples(25)); // This code is contributed by bobby </script>",
"e": 27707,
"s": 27277,
"text": null
},
{
"code": null,
"e": 27717,
"s": 27707,
"text": "Output : "
},
{
"code": null,
"e": 27728,
"s": 27717,
"text": "Count = 10"
},
{
"code": null,
"e": 27938,
"s": 27728,
"text": "Time Complexity : O(n)An efficient solution can solve the above problem in O(1) time. The idea is to count multiples of 3 and add multiples of 7, then subtract multiples of 21 because these are counted twice. "
},
{
"code": null,
"e": 27964,
"s": 27938,
"text": "count = n/3 + n/7 - n/21 "
},
{
"code": null,
"e": 27968,
"s": 27964,
"text": "C++"
},
{
"code": null,
"e": 27973,
"s": 27968,
"text": "Java"
},
{
"code": null,
"e": 27982,
"s": 27973,
"text": "Python 3"
},
{
"code": null,
"e": 27985,
"s": 27982,
"text": "C#"
},
{
"code": null,
"e": 27989,
"s": 27985,
"text": "PHP"
},
{
"code": null,
"e": 28000,
"s": 27989,
"text": "Javascript"
},
{
"code": "// A better C++ program to find count of all// numbers that multiples#include<iostream>using namespace std; // Returns count of all numbers smaller than// or equal to n and multiples of 3 or 7 or bothint countMultiples(int n){ return n/3 + n/7 -n/21;} // Driver codeint main(){ cout << \"Count = \" << countMultiples(25);}",
"e": 28325,
"s": 28000,
"text": null
},
{
"code": "// A better Java program to// find count of all numbers// that multiplesimport java.io.*; class GFG{ // Returns count of all numbers// smaller than or equal to n// and multiples of 3 or 7 or bothstatic int countMultiples(int n){ return n / 3 + n / 7 - n / 21;} // Driver codepublic static void main (String args [] ){ System.out.println(\"Count = \" + countMultiples(25));}} // This code is contributed by aj_36",
"e": 28768,
"s": 28325,
"text": null
},
{
"code": "# Python 3 program to find count of# all numbers that multiples # Returns count of all numbers# smaller than or equal to n and# multiples of 3 or 7 or bothdef countMultiples(n): return n / 3 + n / 7 - n / 21; # Driver coden = ((int)(countMultiples(25)));print(\"Count =\", n); # This code is contributed# by Shivi_Aggarwal",
"e": 29092,
"s": 28768,
"text": null
},
{
"code": "// A better Java program to// find count of all numbers// that multiplesusing System; class GFG{ // Returns count of all numbers// smaller than or equal to n// and multiples of 3 or 7 or bothstatic int countMultiples(int n){ return n / 3 + n / 7 - n / 21;} // Driver Codestatic public void Main (){ Console.WriteLine(\"Count = \" + countMultiples(25));}} // This code is contributed by m_kit",
"e": 29514,
"s": 29092,
"text": null
},
{
"code": "<?php// A better PHP program to find count// of all numbers that multiples // Returns count of all numbers// smaller than or equal to n// and multiples of 3 or 7 or bothfunction countMultiples($n){return floor($n / 3 + $n / 7 - $n / 21);} // Driver codeecho \"Count = \" , countMultiples(25); // This code is contributed by ajit?>",
"e": 29843,
"s": 29514,
"text": null
},
{
"code": "<script> // JavaScript program to find count// of all numbers that multiples // Returns count of all numbers// smaller than or equal to n// and multiples of 3 or 7 or bothfunction countMultiples(n){return Math.floor(n / 3 + n / 7 - n / 21);} // Driver codedocument.write( \"Count = \" +countMultiples(25)); // This code is contributed by bobby </script>",
"e": 30195,
"s": 29843,
"text": null
},
{
"code": null,
"e": 30205,
"s": 30195,
"text": "Output : "
},
{
"code": null,
"e": 30216,
"s": 30205,
"text": "Count = 10"
},
{
"code": null,
"e": 30759,
"s": 30216,
"text": "Time Complexity : O(1)Exercise: Now try the problem of finding sum of all numbers less than or equal to n and multiples of 3 or 7 or both in O(1) time.This article is contributed by Saurabh Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 30765,
"s": 30759,
"text": "jit_t"
},
{
"code": null,
"e": 30778,
"s": 30765,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 30793,
"s": 30778,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 30811,
"s": 30793,
"text": "gottumukkalabobby"
},
{
"code": null,
"e": 30828,
"s": 30811,
"text": "surinderdawra388"
},
{
"code": null,
"e": 30841,
"s": 30828,
"text": "Mathematical"
},
{
"code": null,
"e": 30854,
"s": 30841,
"text": "Mathematical"
},
{
"code": null,
"e": 30952,
"s": 30854,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30961,
"s": 30952,
"text": "Comments"
},
{
"code": null,
"e": 30974,
"s": 30961,
"text": "Old Comments"
},
{
"code": null,
"e": 31023,
"s": 30974,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 31066,
"s": 31023,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 31108,
"s": 31066,
"text": "Euclidean algorithms (Basic and Extended)"
},
{
"code": null,
"e": 31151,
"s": 31108,
"text": "Program to convert a given number to words"
},
{
"code": null,
"e": 31183,
"s": 31151,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 31214,
"s": 31183,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 31287,
"s": 31214,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 31340,
"s": 31287,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 31375,
"s": 31340,
"text": "Program to find LCM of two numbers"
}
] |
HTML - <p> Tag
|
The HTML <p> tag defines a paragraph of text.
<!DOCTYPE html>
<html>
<head>
<title>HTML p Tag</title>
</head>
<body>
<p>This paragraph is defined using the HTML p tag</p>
</body>
</html>
This will produce the following result −
This paragraph is defined using the HTML p tag
This tag supports all the global attributes described in − HTML Attribute Reference
The HTML <p> tag also supports the following additional attributes −
This tag supports all the event attributes described in − HTML Events Reference
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2420,
"s": 2374,
"text": "The HTML <p> tag defines a paragraph of text."
},
{
"code": null,
"e": 2588,
"s": 2420,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML p Tag</title>\n </head>\n\n <body>\n <p>This paragraph is defined using the HTML p tag</p>\n </body>\n\n</html>"
},
{
"code": null,
"e": 2629,
"s": 2588,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 2676,
"s": 2629,
"text": "This paragraph is defined using the HTML p tag"
},
{
"code": null,
"e": 2760,
"s": 2676,
"text": "This tag supports all the global attributes described in − HTML Attribute Reference"
},
{
"code": null,
"e": 2829,
"s": 2760,
"text": "The HTML <p> tag also supports the following additional attributes −"
},
{
"code": null,
"e": 2909,
"s": 2829,
"text": "This tag supports all the event attributes described in − HTML Events Reference"
},
{
"code": null,
"e": 2942,
"s": 2909,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2956,
"s": 2942,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 2991,
"s": 2956,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3005,
"s": 2991,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3040,
"s": 3005,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3057,
"s": 3040,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3092,
"s": 3057,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3123,
"s": 3092,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3156,
"s": 3123,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3187,
"s": 3156,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3222,
"s": 3187,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3253,
"s": 3222,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3260,
"s": 3253,
"text": " Print"
},
{
"code": null,
"e": 3271,
"s": 3260,
"text": " Add Notes"
}
] |
Different Ways to Create the Instances of Wrapper Classes in Java - GeeksforGeeks
|
17 Mar, 2021
Wrapper Class a class whose object wraps or contains primitive data types. When we create an object to a wrapper class, it contains a field and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object.
Methods:
We can use two ways to construct the instance of the Wrapper Classes
Using the constructor of the wrapper classUsing the valueOf() method provided by the Wrapper classesUsing concept of AutoBoxing
Using the constructor of the wrapper class
Using the valueOf() method provided by the Wrapper classes
Using concept of AutoBoxing
Let us discuss both ways individually in detail
Method 1: Using the constructor of the wrapper class
Syntax:
ClassName object = new ClassName(argument);
Illustration:
Integer number = new Integer(5);
Method 2: Using the valueOf() method provided by the Wrapper classes
Syntax:
ClassName object = ClassName.valueOf(argument);
Illustration:
Integer number = Integer.valueOf(5);
Now the question arises what is the difference between the two methods in the creation of instances of the Wrapper classes and which method is better for constructing instances. Let us implement both of the methods to get fair play among them.
Implementation:
Example
Java
// Importing input output classes import java.io.*; // Main classclass GFG { // Main driver method public static void main (String[] args) { // Creating and initializing two integer numbers // Value is passed as an argument to which it is initialized // Custom entries // Number 1 where N = 5 Integer num1 = new Integer(5); // Number 2 where N = 5 Integer num2 = new Integer(5); // Creating objects of Integer class // using valueOf() method // Again, creating and initializing two integer numbers // Value is passed as an argument to which it is initialized Integer num3 = Integer.valueOf(5); Integer num4 = Integer.valueOf(5); // Now by far, all the objects contain the same value // N = 5 // Boolean will return true if numbers are equal // else eturning false // Comparing two numbers boolean value1 = (num1 == num2); boolean value2 = (num3 == num4); // Print and display the bool results System.out.println(value1); System.out.println(value2); }}
Output:
false
true
Output explanation:
Note that, the instances of the classes point to the memory locations assigned in the heap and themselves do not hold the value. While we are creating objects with the help of the constructor of the wrapper class, each time a new memory is allocated in the heap and the objects point to the different memory locations. Hence, in the above example, In this case, both num1 and num2 are pointing to different memory locations, thus on the comparison, they return false.
Do note is not so in the case of the valueOf() method as the valueOf() method checks if any memory is allocated to the same value for that class in the heap. If it finds the value, then it provides the location of the previously allotted memory to the new instance and both start pointing to the same memory location in the heap. Hence, on the comparison, it returns true.
Since the wrapper class object’s values are immutable just like String and thus can not be changed once allotted, it does not affect how many instances are pointing to the same memory location. Hence, in the above example, the memory was allotted to value 5 and the num3 was pointing to that memory location, but when we created one more instance num4 with the same value, it also started pointing to the same memory location as pointed by num3.
Currently, the method using a constructor to create an instance is deprecated, and therefore it is always best to use the valueOf() method. So let us move ahead a bit discussing the new concept of autoboxing.
Method 3: Using the concept of AutoBoxing
AutoBoxing is to reduce the efforts to write the valueOf() method each time we are creating instances, AutoBoxing is implemented. The automatic conversion of primitive types to the object of their corresponding wrapper classes is known as AutoBoxing.
We were creating wrapper classes until now by using valueOf() method, but it seems quite lengthy when we can use AutoBoxing. In AutoBoxing, our work is done by the compiler, i.e. Java compiler in the background would perform the valueOf() operation and create the instance of it.
Instances created using autoboxing follow the process of valueOf() in the background and hence in this also, multiple instances with the same value point to the same memory location.
Illustration: In the above example, it can also be written as Integer.valueOf(15)) and put the reference of it in the object (i.e. a number).
Integer number = 15;
Syntax:
ClassName object = value;
// of primitive data type associated with the wrapper class.
Example:
Java
// Importing input output classesimport java.io.*; // Main class class GFG { // Main driver method public static void main (String[] args) { // Creating Instances using AutoBoxing Integer num1 = 5; Integer num2 = 5; boolean bool = (num1 == num2); System.out.println(bool); }}
true
Output explanation:
Both the num1 and num2 are pointing to the same memory location in the heap as we discussed in the valueOf() method.
java-wrapper-class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in Java
Stream In Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Internal Working of HashMap in Java
Checked vs Unchecked Exceptions in Java
Strings in Java
StringBuilder Class in Java with Examples
|
[
{
"code": null,
"e": 23894,
"s": 23866,
"text": "\n17 Mar, 2021"
},
{
"code": null,
"e": 24163,
"s": 23894,
"text": "Wrapper Class a class whose object wraps or contains primitive data types. When we create an object to a wrapper class, it contains a field and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object."
},
{
"code": null,
"e": 24172,
"s": 24163,
"text": "Methods:"
},
{
"code": null,
"e": 24241,
"s": 24172,
"text": "We can use two ways to construct the instance of the Wrapper Classes"
},
{
"code": null,
"e": 24369,
"s": 24241,
"text": "Using the constructor of the wrapper classUsing the valueOf() method provided by the Wrapper classesUsing concept of AutoBoxing"
},
{
"code": null,
"e": 24412,
"s": 24369,
"text": "Using the constructor of the wrapper class"
},
{
"code": null,
"e": 24471,
"s": 24412,
"text": "Using the valueOf() method provided by the Wrapper classes"
},
{
"code": null,
"e": 24499,
"s": 24471,
"text": "Using concept of AutoBoxing"
},
{
"code": null,
"e": 24547,
"s": 24499,
"text": "Let us discuss both ways individually in detail"
},
{
"code": null,
"e": 24600,
"s": 24547,
"text": "Method 1: Using the constructor of the wrapper class"
},
{
"code": null,
"e": 24608,
"s": 24600,
"text": "Syntax:"
},
{
"code": null,
"e": 24652,
"s": 24608,
"text": "ClassName object = new ClassName(argument);"
},
{
"code": null,
"e": 24666,
"s": 24652,
"text": "Illustration:"
},
{
"code": null,
"e": 24699,
"s": 24666,
"text": "Integer number = new Integer(5);"
},
{
"code": null,
"e": 24768,
"s": 24699,
"text": "Method 2: Using the valueOf() method provided by the Wrapper classes"
},
{
"code": null,
"e": 24776,
"s": 24768,
"text": "Syntax:"
},
{
"code": null,
"e": 24824,
"s": 24776,
"text": "ClassName object = ClassName.valueOf(argument);"
},
{
"code": null,
"e": 24838,
"s": 24824,
"text": "Illustration:"
},
{
"code": null,
"e": 24875,
"s": 24838,
"text": "Integer number = Integer.valueOf(5);"
},
{
"code": null,
"e": 25119,
"s": 24875,
"text": "Now the question arises what is the difference between the two methods in the creation of instances of the Wrapper classes and which method is better for constructing instances. Let us implement both of the methods to get fair play among them."
},
{
"code": null,
"e": 25135,
"s": 25119,
"text": "Implementation:"
},
{
"code": null,
"e": 25143,
"s": 25135,
"text": "Example"
},
{
"code": null,
"e": 25148,
"s": 25143,
"text": "Java"
},
{
"code": "// Importing input output classes import java.io.*; // Main classclass GFG { // Main driver method public static void main (String[] args) { // Creating and initializing two integer numbers // Value is passed as an argument to which it is initialized // Custom entries // Number 1 where N = 5 Integer num1 = new Integer(5); // Number 2 where N = 5 Integer num2 = new Integer(5); // Creating objects of Integer class // using valueOf() method // Again, creating and initializing two integer numbers // Value is passed as an argument to which it is initialized Integer num3 = Integer.valueOf(5); Integer num4 = Integer.valueOf(5); // Now by far, all the objects contain the same value // N = 5 // Boolean will return true if numbers are equal // else eturning false // Comparing two numbers boolean value1 = (num1 == num2); boolean value2 = (num3 == num4); // Print and display the bool results System.out.println(value1); System.out.println(value2); }}",
"e": 26340,
"s": 25148,
"text": null
},
{
"code": null,
"e": 26348,
"s": 26340,
"text": "Output:"
},
{
"code": null,
"e": 26359,
"s": 26348,
"text": "false\ntrue"
},
{
"code": null,
"e": 26379,
"s": 26359,
"text": "Output explanation:"
},
{
"code": null,
"e": 26847,
"s": 26379,
"text": "Note that, the instances of the classes point to the memory locations assigned in the heap and themselves do not hold the value. While we are creating objects with the help of the constructor of the wrapper class, each time a new memory is allocated in the heap and the objects point to the different memory locations. Hence, in the above example, In this case, both num1 and num2 are pointing to different memory locations, thus on the comparison, they return false."
},
{
"code": null,
"e": 27220,
"s": 26847,
"text": "Do note is not so in the case of the valueOf() method as the valueOf() method checks if any memory is allocated to the same value for that class in the heap. If it finds the value, then it provides the location of the previously allotted memory to the new instance and both start pointing to the same memory location in the heap. Hence, on the comparison, it returns true."
},
{
"code": null,
"e": 27666,
"s": 27220,
"text": "Since the wrapper class object’s values are immutable just like String and thus can not be changed once allotted, it does not affect how many instances are pointing to the same memory location. Hence, in the above example, the memory was allotted to value 5 and the num3 was pointing to that memory location, but when we created one more instance num4 with the same value, it also started pointing to the same memory location as pointed by num3."
},
{
"code": null,
"e": 27875,
"s": 27666,
"text": "Currently, the method using a constructor to create an instance is deprecated, and therefore it is always best to use the valueOf() method. So let us move ahead a bit discussing the new concept of autoboxing."
},
{
"code": null,
"e": 27917,
"s": 27875,
"text": "Method 3: Using the concept of AutoBoxing"
},
{
"code": null,
"e": 28168,
"s": 27917,
"text": "AutoBoxing is to reduce the efforts to write the valueOf() method each time we are creating instances, AutoBoxing is implemented. The automatic conversion of primitive types to the object of their corresponding wrapper classes is known as AutoBoxing."
},
{
"code": null,
"e": 28448,
"s": 28168,
"text": "We were creating wrapper classes until now by using valueOf() method, but it seems quite lengthy when we can use AutoBoxing. In AutoBoxing, our work is done by the compiler, i.e. Java compiler in the background would perform the valueOf() operation and create the instance of it."
},
{
"code": null,
"e": 28631,
"s": 28448,
"text": "Instances created using autoboxing follow the process of valueOf() in the background and hence in this also, multiple instances with the same value point to the same memory location."
},
{
"code": null,
"e": 28773,
"s": 28631,
"text": "Illustration: In the above example, it can also be written as Integer.valueOf(15)) and put the reference of it in the object (i.e. a number)."
},
{
"code": null,
"e": 28794,
"s": 28773,
"text": "Integer number = 15;"
},
{
"code": null,
"e": 28802,
"s": 28794,
"text": "Syntax:"
},
{
"code": null,
"e": 28906,
"s": 28802,
"text": "ClassName object = value; \n// of primitive data type associated with the wrapper class."
},
{
"code": null,
"e": 28915,
"s": 28906,
"text": "Example:"
},
{
"code": null,
"e": 28920,
"s": 28915,
"text": "Java"
},
{
"code": "// Importing input output classesimport java.io.*; // Main class class GFG { // Main driver method public static void main (String[] args) { // Creating Instances using AutoBoxing Integer num1 = 5; Integer num2 = 5; boolean bool = (num1 == num2); System.out.println(bool); }}",
"e": 29254,
"s": 28920,
"text": null
},
{
"code": null,
"e": 29259,
"s": 29254,
"text": "true"
},
{
"code": null,
"e": 29279,
"s": 29259,
"text": "Output explanation:"
},
{
"code": null,
"e": 29398,
"s": 29279,
"text": "Both the num1 and num2 are pointing to the same memory location in the heap as we discussed in the valueOf() method. "
},
{
"code": null,
"e": 29417,
"s": 29398,
"text": "java-wrapper-class"
},
{
"code": null,
"e": 29422,
"s": 29417,
"text": "Java"
},
{
"code": null,
"e": 29427,
"s": 29422,
"text": "Java"
},
{
"code": null,
"e": 29525,
"s": 29427,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29534,
"s": 29525,
"text": "Comments"
},
{
"code": null,
"e": 29547,
"s": 29534,
"text": "Old Comments"
},
{
"code": null,
"e": 29568,
"s": 29547,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29583,
"s": 29568,
"text": "Stream In Java"
},
{
"code": null,
"e": 29602,
"s": 29583,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29632,
"s": 29602,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29678,
"s": 29632,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29704,
"s": 29678,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 29740,
"s": 29704,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 29780,
"s": 29740,
"text": "Checked vs Unchecked Exceptions in Java"
},
{
"code": null,
"e": 29796,
"s": 29780,
"text": "Strings in Java"
}
] |
C library function - strerror()
|
The C library function char *strerror(int errnum) searches an internal array for the error number errnum and returns a pointer to an error message string. The error strings produced by strerror depend on the developing platform and compiler.
Following is the declaration for strerror() function.
char *strerror(int errnum)
errnum − This is the error number, usually errno.
errnum − This is the error number, usually errno.
This function returns a pointer to the error string describing error errnum.
The following example shows the usage of strerror() function.
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main () {
FILE *fp;
fp = fopen("file.txt","r");
if( fp == NULL ) {
printf("Error: %s\n", strerror(errno));
}
return(0);
}
Let us compile and run the above program that will produce the following result because we are trying to open a file which does not exist −
Error: No such file or directory
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2249,
"s": 2007,
"text": "The C library function char *strerror(int errnum) searches an internal array for the error number errnum and returns a pointer to an error message string. The error strings produced by strerror depend on the developing platform and compiler."
},
{
"code": null,
"e": 2303,
"s": 2249,
"text": "Following is the declaration for strerror() function."
},
{
"code": null,
"e": 2330,
"s": 2303,
"text": "char *strerror(int errnum)"
},
{
"code": null,
"e": 2380,
"s": 2330,
"text": "errnum − This is the error number, usually errno."
},
{
"code": null,
"e": 2430,
"s": 2380,
"text": "errnum − This is the error number, usually errno."
},
{
"code": null,
"e": 2507,
"s": 2430,
"text": "This function returns a pointer to the error string describing error errnum."
},
{
"code": null,
"e": 2569,
"s": 2507,
"text": "The following example shows the usage of strerror() function."
},
{
"code": null,
"e": 2780,
"s": 2569,
"text": "#include <stdio.h>\n#include <string.h>\n#include <errno.h>\n\nint main () {\n FILE *fp;\n\n fp = fopen(\"file.txt\",\"r\");\n if( fp == NULL ) {\n printf(\"Error: %s\\n\", strerror(errno));\n }\n \n return(0);\n}"
},
{
"code": null,
"e": 2920,
"s": 2780,
"text": "Let us compile and run the above program that will produce the following result because we are trying to open a file which does not exist −"
},
{
"code": null,
"e": 2954,
"s": 2920,
"text": "Error: No such file or directory\n"
},
{
"code": null,
"e": 2987,
"s": 2954,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3002,
"s": 2987,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3037,
"s": 3002,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3052,
"s": 3037,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3087,
"s": 3052,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3101,
"s": 3087,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3134,
"s": 3101,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3152,
"s": 3134,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 3187,
"s": 3152,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3206,
"s": 3187,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 3239,
"s": 3206,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3251,
"s": 3239,
"text": " Amit Diwan"
},
{
"code": null,
"e": 3258,
"s": 3251,
"text": " Print"
},
{
"code": null,
"e": 3269,
"s": 3258,
"text": " Add Notes"
}
] |
8085 program to convert a BCD number to binary - GeeksforGeeks
|
20 Nov, 2019
Problem – Write an assembly language program for converting a 2 digit BCD number to its binary equivalent using 8085 microprocessor.
Examples:
Input : 72H (0111 0010)2
Output : 48H (in hexadecimal) (0011 0000)2
((4x16)+(8x1))=72
Algorithm:
Load the BCD number in the accumulatorUnpack the 2 digit BCD number into two separate digits. Let the left digit be BCD1 and the right one BCD2Multiply BCD1 by 10 and add BCD2 to it
Load the BCD number in the accumulator
Unpack the 2 digit BCD number into two separate digits. Let the left digit be BCD1 and the right one BCD2
Multiply BCD1 by 10 and add BCD2 to it
If the 2 digit BCD number is 72, then its binary equivalent will be7 x OAH + 2 = 46H + 2 = 48H
Steps:
Load the BCD number from the memory location (201FH, arbitrary choice) into the accumulatorTemporarily store the accumulator’s value in BObtain BCD2 by ANDing the accumulator with 0FH and store it in CRestore the original value of the accumulator by moving the value in B to A. AND the accumulator with F0HIf the value in the accumulator equals 0, then BCD2 is the final answer and store it in the memory location, 2020H (arbitrary)Else, shift the accumulator to right 4 times to obtain BCD1. Next step is to multiply BCD1 by 0AHMultiplication: Move BCD1 to D and initialise E with 0AH as the counter. Clear the accumulator to 0 and add D to it E number of timesFinally, add C to the accumulator and store the result in 2020H
Load the BCD number from the memory location (201FH, arbitrary choice) into the accumulator
Temporarily store the accumulator’s value in B
Obtain BCD2 by ANDing the accumulator with 0FH and store it in C
Restore the original value of the accumulator by moving the value in B to A. AND the accumulator with F0H
If the value in the accumulator equals 0, then BCD2 is the final answer and store it in the memory location, 2020H (arbitrary)
Else, shift the accumulator to right 4 times to obtain BCD1. Next step is to multiply BCD1 by 0AH
Multiplication: Move BCD1 to D and initialise E with 0AH as the counter. Clear the accumulator to 0 and add D to it E number of times
Finally, add C to the accumulator and store the result in 2020H
2020H contains the result.
Store the BCD number in 201FH. 2020H contains its binary equivalent.
Akanksha_Rai
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Addressing modes in 8085 microprocessor
Logical and Physical Address in Operating System
Memory Hierarchy Design and its Characteristics
8085 program to add two 8 bit numbers
Architecture of 8085 microprocessor
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Pin diagram of 8086 microprocessor
Architecture of 8086
Memory mapped I/O and Isolated I/O
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
|
[
{
"code": null,
"e": 24784,
"s": 24756,
"text": "\n20 Nov, 2019"
},
{
"code": null,
"e": 24917,
"s": 24784,
"text": "Problem – Write an assembly language program for converting a 2 digit BCD number to its binary equivalent using 8085 microprocessor."
},
{
"code": null,
"e": 24927,
"s": 24917,
"text": "Examples:"
},
{
"code": null,
"e": 25014,
"s": 24927,
"text": "Input : 72H (0111 0010)2\nOutput : 48H (in hexadecimal) (0011 0000)2\n((4x16)+(8x1))=72\n"
},
{
"code": null,
"e": 25025,
"s": 25014,
"text": "Algorithm:"
},
{
"code": null,
"e": 25207,
"s": 25025,
"text": "Load the BCD number in the accumulatorUnpack the 2 digit BCD number into two separate digits. Let the left digit be BCD1 and the right one BCD2Multiply BCD1 by 10 and add BCD2 to it"
},
{
"code": null,
"e": 25246,
"s": 25207,
"text": "Load the BCD number in the accumulator"
},
{
"code": null,
"e": 25352,
"s": 25246,
"text": "Unpack the 2 digit BCD number into two separate digits. Let the left digit be BCD1 and the right one BCD2"
},
{
"code": null,
"e": 25391,
"s": 25352,
"text": "Multiply BCD1 by 10 and add BCD2 to it"
},
{
"code": null,
"e": 25486,
"s": 25391,
"text": "If the 2 digit BCD number is 72, then its binary equivalent will be7 x OAH + 2 = 46H + 2 = 48H"
},
{
"code": null,
"e": 25493,
"s": 25486,
"text": "Steps:"
},
{
"code": null,
"e": 26219,
"s": 25493,
"text": "Load the BCD number from the memory location (201FH, arbitrary choice) into the accumulatorTemporarily store the accumulator’s value in BObtain BCD2 by ANDing the accumulator with 0FH and store it in CRestore the original value of the accumulator by moving the value in B to A. AND the accumulator with F0HIf the value in the accumulator equals 0, then BCD2 is the final answer and store it in the memory location, 2020H (arbitrary)Else, shift the accumulator to right 4 times to obtain BCD1. Next step is to multiply BCD1 by 0AHMultiplication: Move BCD1 to D and initialise E with 0AH as the counter. Clear the accumulator to 0 and add D to it E number of timesFinally, add C to the accumulator and store the result in 2020H"
},
{
"code": null,
"e": 26311,
"s": 26219,
"text": "Load the BCD number from the memory location (201FH, arbitrary choice) into the accumulator"
},
{
"code": null,
"e": 26358,
"s": 26311,
"text": "Temporarily store the accumulator’s value in B"
},
{
"code": null,
"e": 26423,
"s": 26358,
"text": "Obtain BCD2 by ANDing the accumulator with 0FH and store it in C"
},
{
"code": null,
"e": 26529,
"s": 26423,
"text": "Restore the original value of the accumulator by moving the value in B to A. AND the accumulator with F0H"
},
{
"code": null,
"e": 26656,
"s": 26529,
"text": "If the value in the accumulator equals 0, then BCD2 is the final answer and store it in the memory location, 2020H (arbitrary)"
},
{
"code": null,
"e": 26754,
"s": 26656,
"text": "Else, shift the accumulator to right 4 times to obtain BCD1. Next step is to multiply BCD1 by 0AH"
},
{
"code": null,
"e": 26888,
"s": 26754,
"text": "Multiplication: Move BCD1 to D and initialise E with 0AH as the counter. Clear the accumulator to 0 and add D to it E number of times"
},
{
"code": null,
"e": 26952,
"s": 26888,
"text": "Finally, add C to the accumulator and store the result in 2020H"
},
{
"code": null,
"e": 26979,
"s": 26952,
"text": "2020H contains the result."
},
{
"code": null,
"e": 27048,
"s": 26979,
"text": "Store the BCD number in 201FH. 2020H contains its binary equivalent."
},
{
"code": null,
"e": 27061,
"s": 27048,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 27076,
"s": 27061,
"text": "microprocessor"
},
{
"code": null,
"e": 27095,
"s": 27076,
"text": "system-programming"
},
{
"code": null,
"e": 27132,
"s": 27095,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 27147,
"s": 27132,
"text": "microprocessor"
},
{
"code": null,
"e": 27245,
"s": 27147,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27254,
"s": 27245,
"text": "Comments"
},
{
"code": null,
"e": 27267,
"s": 27254,
"text": "Old Comments"
},
{
"code": null,
"e": 27307,
"s": 27267,
"text": "Addressing modes in 8085 microprocessor"
},
{
"code": null,
"e": 27356,
"s": 27307,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 27404,
"s": 27356,
"text": "Memory Hierarchy Design and its Characteristics"
},
{
"code": null,
"e": 27442,
"s": 27404,
"text": "8085 program to add two 8 bit numbers"
},
{
"code": null,
"e": 27478,
"s": 27442,
"text": "Architecture of 8085 microprocessor"
},
{
"code": null,
"e": 27573,
"s": 27478,
"text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)"
},
{
"code": null,
"e": 27608,
"s": 27573,
"text": "Pin diagram of 8086 microprocessor"
},
{
"code": null,
"e": 27629,
"s": 27608,
"text": "Architecture of 8086"
},
{
"code": null,
"e": 27664,
"s": 27629,
"text": "Memory mapped I/O and Isolated I/O"
}
] |
HTML | DOM Input Checkbox checked Property - GeeksforGeeks
|
08 Mar, 2019
The DOM Input Checkbox Property is used to set or return the checked status of a checkbox field. This property is used to reflect the HTML Checked attribute.
Syntax:
It is used to return the checked property.checkboxObject.checked
checkboxObject.checked
It is used to set the checked property.checkboxObject.checked = true|false
checkboxObject.checked = true|false
Property Values:
true: It defines that checkbox is in checked state.
false: It specify that the checkbox is not checked. It is false by default.
Return Value: It returns a boolean value which represents that whether the checkbox is checked or not.
Example: This example illustrates how to return the Checkbox Checked Property.
<!DOCTYPE html> <html> <head> <title>DOM Input Checkbox Checked Property</title> </head> <body style = "text-align: center;"> <h1 style = "color: green;">GeeksforGeeks</h1> <h2>DOM Input Checkbox checked Property</h2> <form > <!-- Below input elements have attribute "checked" --> <input type="checkbox" name="check" id="GFG" value="1" checked>Checked by default<br> <input type="checkbox" name="check" value="2"> Not checked by default<br> </form> <br><button onclick="myGeeks()">Submit</button> <p id="sudo" style="color:green;font-size:20px;"></p> <script>function myGeeks() { var g = document.getElementById("GFG").checked; document.getElementById("sudo").innerHTML = g;}</script> </body> </html>
Output:Before clicking on the button:
After clicking on the button:
Example-2: This example illustrates that how to check and uncheck the checkbox.
<!DOCTYPE html> <html> <head> <title>DOM Input Checkbox Checked Property</title> </head> <body style = "text-align: center;"> <h1 style = "color: green;">GeeksforGeeks</h1> <h2>DOM Input Checkbox checked Property</h2> <form > <!-- Below input elements have attribute "checked" --> <input type="checkbox" name="check" id="GFG" value="1">Checked by default<br> <input type="checkbox" name="check" value="2"> Not checked by default<br> </form> <br> <button onclick="myGeeks()">checkt</button> <button onclick="Geeks()">Uncheck</button> <script> function myGeeks() { var g = document.getElementById("GFG").checked = true; } function Geeks() { var w = document.getElementById("GFG").checked = false; } </script> </body> </html>
Output :
Before clicking on the button:
After clicking on the check button:
After clicking on the uncheck button:
Supported Browsers: The browser supported by DOM input Checkbox Checked Property are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
Form validation using HTML and JavaScript
Design a web page using HTML and CSS
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Angular Libraries For Web Developers
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24748,
"s": 24720,
"text": "\n08 Mar, 2019"
},
{
"code": null,
"e": 24906,
"s": 24748,
"text": "The DOM Input Checkbox Property is used to set or return the checked status of a checkbox field. This property is used to reflect the HTML Checked attribute."
},
{
"code": null,
"e": 24914,
"s": 24906,
"text": "Syntax:"
},
{
"code": null,
"e": 24979,
"s": 24914,
"text": "It is used to return the checked property.checkboxObject.checked"
},
{
"code": null,
"e": 25002,
"s": 24979,
"text": "checkboxObject.checked"
},
{
"code": null,
"e": 25077,
"s": 25002,
"text": "It is used to set the checked property.checkboxObject.checked = true|false"
},
{
"code": null,
"e": 25113,
"s": 25077,
"text": "checkboxObject.checked = true|false"
},
{
"code": null,
"e": 25130,
"s": 25113,
"text": "Property Values:"
},
{
"code": null,
"e": 25182,
"s": 25130,
"text": "true: It defines that checkbox is in checked state."
},
{
"code": null,
"e": 25258,
"s": 25182,
"text": "false: It specify that the checkbox is not checked. It is false by default."
},
{
"code": null,
"e": 25361,
"s": 25258,
"text": "Return Value: It returns a boolean value which represents that whether the checkbox is checked or not."
},
{
"code": null,
"e": 25440,
"s": 25361,
"text": "Example: This example illustrates how to return the Checkbox Checked Property."
},
{
"code": "<!DOCTYPE html> <html> <head> <title>DOM Input Checkbox Checked Property</title> </head> <body style = \"text-align: center;\"> <h1 style = \"color: green;\">GeeksforGeeks</h1> <h2>DOM Input Checkbox checked Property</h2> <form > <!-- Below input elements have attribute \"checked\" --> <input type=\"checkbox\" name=\"check\" id=\"GFG\" value=\"1\" checked>Checked by default<br> <input type=\"checkbox\" name=\"check\" value=\"2\"> Not checked by default<br> </form> <br><button onclick=\"myGeeks()\">Submit</button> <p id=\"sudo\" style=\"color:green;font-size:20px;\"></p> <script>function myGeeks() { var g = document.getElementById(\"GFG\").checked; document.getElementById(\"sudo\").innerHTML = g;}</script> </body> </html> ",
"e": 26357,
"s": 25440,
"text": null
},
{
"code": null,
"e": 26395,
"s": 26357,
"text": "Output:Before clicking on the button:"
},
{
"code": null,
"e": 26425,
"s": 26395,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 26505,
"s": 26425,
"text": "Example-2: This example illustrates that how to check and uncheck the checkbox."
},
{
"code": "<!DOCTYPE html> <html> <head> <title>DOM Input Checkbox Checked Property</title> </head> <body style = \"text-align: center;\"> <h1 style = \"color: green;\">GeeksforGeeks</h1> <h2>DOM Input Checkbox checked Property</h2> <form > <!-- Below input elements have attribute \"checked\" --> <input type=\"checkbox\" name=\"check\" id=\"GFG\" value=\"1\">Checked by default<br> <input type=\"checkbox\" name=\"check\" value=\"2\"> Not checked by default<br> </form> <br> <button onclick=\"myGeeks()\">checkt</button> <button onclick=\"Geeks()\">Uncheck</button> <script> function myGeeks() { var g = document.getElementById(\"GFG\").checked = true; } function Geeks() { var w = document.getElementById(\"GFG\").checked = false; } </script> </body> </html> ",
"e": 27517,
"s": 26505,
"text": null
},
{
"code": null,
"e": 27526,
"s": 27517,
"text": "Output :"
},
{
"code": null,
"e": 27557,
"s": 27526,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 27593,
"s": 27557,
"text": "After clicking on the check button:"
},
{
"code": null,
"e": 27631,
"s": 27593,
"text": "After clicking on the uncheck button:"
},
{
"code": null,
"e": 27730,
"s": 27631,
"text": "Supported Browsers: The browser supported by DOM input Checkbox Checked Property are listed below:"
},
{
"code": null,
"e": 27744,
"s": 27730,
"text": "Google Chrome"
},
{
"code": null,
"e": 27762,
"s": 27744,
"text": "Internet Explorer"
},
{
"code": null,
"e": 27770,
"s": 27762,
"text": "Firefox"
},
{
"code": null,
"e": 27776,
"s": 27770,
"text": "Opera"
},
{
"code": null,
"e": 27783,
"s": 27776,
"text": "Safari"
},
{
"code": null,
"e": 27920,
"s": 27783,
"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": 27929,
"s": 27920,
"text": "HTML-DOM"
},
{
"code": null,
"e": 27934,
"s": 27929,
"text": "HTML"
},
{
"code": null,
"e": 27951,
"s": 27934,
"text": "Web Technologies"
},
{
"code": null,
"e": 27956,
"s": 27951,
"text": "HTML"
},
{
"code": null,
"e": 28054,
"s": 27956,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28063,
"s": 28054,
"text": "Comments"
},
{
"code": null,
"e": 28076,
"s": 28063,
"text": "Old Comments"
},
{
"code": null,
"e": 28126,
"s": 28076,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 28150,
"s": 28126,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 28187,
"s": 28150,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 28229,
"s": 28187,
"text": "Form validation using HTML and JavaScript"
},
{
"code": null,
"e": 28266,
"s": 28229,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 28308,
"s": 28266,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28341,
"s": 28308,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28384,
"s": 28341,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28428,
"s": 28384,
"text": "Top 10 Angular Libraries For Web Developers"
}
] |
Laravel - Sending Email
|
Laravel uses free feature-rich library SwiftMailer to send emails. Using the library function, we can easily send emails without too many hassles. The e-mail templates are loaded in the same way as views, which means you can use the Blade syntax and inject data into your templates.
The following table shows the syntax and attributes of send function −
$view(string|array) − name of the view that contains email message
$view(string|array) − name of the view that contains email message
$data(array) − array of data to pass to view
$data(array) − array of data to pass to view
$callback − a Closure callback which receives a message instance, allowing you to customize the recipients, subject, and other aspects of the mail message
$callback − a Closure callback which receives a message instance, allowing you to customize the recipients, subject, and other aspects of the mail message
In the third argument, the $callback closure received message instance and with that instance we can also call the following functions and alter the message as shown below.
$message → subject('Welcome to the Tutorials Point');
$message → from('email@example.com', 'Mr. Example');
$message → to('email@example.com', 'Mr. Example');
Some of the less common methods include −
$message → sender('email@example.com', 'Mr. Example');
$message → returnPath('email@example.com');
$message → cc('email@example.com', 'Mr. Example');
$message → bcc('email@example.com', 'Mr. Example');
$message → replyTo('email@example.com', 'Mr. Example');
$message → priority(2);
To attach or embed files, you can use the following methods −
$message → attach('path/to/attachment.txt');
$message → embed('path/to/attachment.jpg');
Mail can be sent as HTML or text. You can indicate the type of mail that you want to send in the first argument by passing an array as shown below. The default type is HTML. If you want to send plain text mail then use the following syntax.
Mail::send([‘text’=>’text.view’], $data, $callback);
In this syntax, the first argument takes an array. Use text as the key name of the view as value of the key.
Step 1 − We will now send an email from Gmail account and for that you need to configure your Gmail account in Laravel environment file - .env file. Enable 2-step verification in your Gmail account and create an application specific password followed by changing the .env parameters as shown below.
MAIL_DRIVER = smtp
MAIL_HOST = smtp.gmail.com
MAIL_PORT = 587
MAIL_USERNAME = your-gmail-username
MAIL_PASSWORD = your-application-specific-password
MAIL_ENCRYPTION = tls
Step 2 − After changing the .env file execute the below two commands to clear the cache and restart the Laravel server.
php artisan config:cache
Step 3 − Create a controller called MailController by executing the following command.
php artisan make:controller MailController --plain
Step 4 − After successful execution, you will receive the following output −
Step 5 − Copy the following code in
app/Http/Controllers/MailController.php file.
app/Http/Controllers/MailController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Mail;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class MailController extends Controller {
public function basic_email() {
$data = array('name'=>"Virat Gandhi");
Mail::send(['text'=>'mail'], $data, function($message) {
$message->to('abc@gmail.com', 'Tutorials Point')->subject
('Laravel Basic Testing Mail');
$message->from('xyz@gmail.com','Virat Gandhi');
});
echo "Basic Email Sent. Check your inbox.";
}
public function html_email() {
$data = array('name'=>"Virat Gandhi");
Mail::send('mail', $data, function($message) {
$message->to('abc@gmail.com', 'Tutorials Point')->subject
('Laravel HTML Testing Mail');
$message->from('xyz@gmail.com','Virat Gandhi');
});
echo "HTML Email Sent. Check your inbox.";
}
public function attachment_email() {
$data = array('name'=>"Virat Gandhi");
Mail::send('mail', $data, function($message) {
$message->to('abc@gmail.com', 'Tutorials Point')->subject
('Laravel Testing Mail with Attachment');
$message->attach('C:\laravel-master\laravel\public\uploads\image.png');
$message->attach('C:\laravel-master\laravel\public\uploads\test.txt');
$message->from('xyz@gmail.com','Virat Gandhi');
});
echo "Email Sent with attachment. Check your inbox.";
}
}
Step 6 − Copy the following code in resources/views/mail.blade.php file.
resources/views/mail.blade.php
<h1>Hi, {{ $name }}</h1>
l<p>Sending Mail from Laravel.</p>
Step 7 − Add the following lines in app/Http/routes.php.
app/Http/routes.php
Route::get('sendbasicemail','MailController@basic_email');
Route::get('sendhtmlemail','MailController@html_email');
Route::get('sendattachmentemail','MailController@attachment_email');
Step 8 − Visit the following URL to test basic email.
http://localhost:8000/sendbasicemail
Step 9 − The output screen will look something like this. Check your inbox to see the basic email output.
Step 10 − Visit the following URL to test the HTML email.
http://localhost:8000/sendhtmlemail
Step 11 − The output screen will look something like this. Check your inbox to see the html email output.
Step 12 − Visit the following URL to test the HTML email with attachment.
http://localhost:8000/sendattachmentemail
Step 13 − You can see the following output
Note − In the MailController.php file the email address in the from method should be the email address from which you can send email address. Generally, it should be the email address configured on your server.
13 Lectures
3 hours
Sebastian Sulinski
35 Lectures
3.5 hours
Antonio Papa
7 Lectures
1.5 hours
Sebastian Sulinski
42 Lectures
1 hours
Skillbakerystudios
165 Lectures
13 hours
Paul Carlo Tordecilla
116 Lectures
13 hours
Hafizullah Masoudi
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2755,
"s": 2472,
"text": "Laravel uses free feature-rich library SwiftMailer to send emails. Using the library function, we can easily send emails without too many hassles. The e-mail templates are loaded in the same way as views, which means you can use the Blade syntax and inject data into your templates."
},
{
"code": null,
"e": 2826,
"s": 2755,
"text": "The following table shows the syntax and attributes of send function −"
},
{
"code": null,
"e": 2893,
"s": 2826,
"text": "$view(string|array) − name of the view that contains email message"
},
{
"code": null,
"e": 2960,
"s": 2893,
"text": "$view(string|array) − name of the view that contains email message"
},
{
"code": null,
"e": 3005,
"s": 2960,
"text": "$data(array) − array of data to pass to view"
},
{
"code": null,
"e": 3050,
"s": 3005,
"text": "$data(array) − array of data to pass to view"
},
{
"code": null,
"e": 3205,
"s": 3050,
"text": "$callback − a Closure callback which receives a message instance, allowing you to customize the recipients, subject, and other aspects of the mail message"
},
{
"code": null,
"e": 3360,
"s": 3205,
"text": "$callback − a Closure callback which receives a message instance, allowing you to customize the recipients, subject, and other aspects of the mail message"
},
{
"code": null,
"e": 3533,
"s": 3360,
"text": "In the third argument, the $callback closure received message instance and with that instance we can also call the following functions and alter the message as shown below."
},
{
"code": null,
"e": 3587,
"s": 3533,
"text": "$message → subject('Welcome to the Tutorials Point');"
},
{
"code": null,
"e": 3640,
"s": 3587,
"text": "$message → from('email@example.com', 'Mr. Example');"
},
{
"code": null,
"e": 3691,
"s": 3640,
"text": "$message → to('email@example.com', 'Mr. Example');"
},
{
"code": null,
"e": 3733,
"s": 3691,
"text": "Some of the less common methods include −"
},
{
"code": null,
"e": 3788,
"s": 3733,
"text": "$message → sender('email@example.com', 'Mr. Example');"
},
{
"code": null,
"e": 3832,
"s": 3788,
"text": "$message → returnPath('email@example.com');"
},
{
"code": null,
"e": 3883,
"s": 3832,
"text": "$message → cc('email@example.com', 'Mr. Example');"
},
{
"code": null,
"e": 3935,
"s": 3883,
"text": "$message → bcc('email@example.com', 'Mr. Example');"
},
{
"code": null,
"e": 3991,
"s": 3935,
"text": "$message → replyTo('email@example.com', 'Mr. Example');"
},
{
"code": null,
"e": 4015,
"s": 3991,
"text": "$message → priority(2);"
},
{
"code": null,
"e": 4077,
"s": 4015,
"text": "To attach or embed files, you can use the following methods −"
},
{
"code": null,
"e": 4122,
"s": 4077,
"text": "$message → attach('path/to/attachment.txt');"
},
{
"code": null,
"e": 4166,
"s": 4122,
"text": "$message → embed('path/to/attachment.jpg');"
},
{
"code": null,
"e": 4407,
"s": 4166,
"text": "Mail can be sent as HTML or text. You can indicate the type of mail that you want to send in the first argument by passing an array as shown below. The default type is HTML. If you want to send plain text mail then use the following syntax."
},
{
"code": null,
"e": 4461,
"s": 4407,
"text": "Mail::send([‘text’=>’text.view’], $data, $callback);\n"
},
{
"code": null,
"e": 4570,
"s": 4461,
"text": "In this syntax, the first argument takes an array. Use text as the key name of the view as value of the key."
},
{
"code": null,
"e": 4869,
"s": 4570,
"text": "Step 1 − We will now send an email from Gmail account and for that you need to configure your Gmail account in Laravel environment file - .env file. Enable 2-step verification in your Gmail account and create an application specific password followed by changing the .env parameters as shown below."
},
{
"code": null,
"e": 5041,
"s": 4869,
"text": "MAIL_DRIVER = smtp\nMAIL_HOST = smtp.gmail.com\nMAIL_PORT = 587\nMAIL_USERNAME = your-gmail-username\nMAIL_PASSWORD = your-application-specific-password\nMAIL_ENCRYPTION = tls\n"
},
{
"code": null,
"e": 5161,
"s": 5041,
"text": "Step 2 − After changing the .env file execute the below two commands to clear the cache and restart the Laravel server."
},
{
"code": null,
"e": 5187,
"s": 5161,
"text": "php artisan config:cache\n"
},
{
"code": null,
"e": 5274,
"s": 5187,
"text": "Step 3 − Create a controller called MailController by executing the following command."
},
{
"code": null,
"e": 5326,
"s": 5274,
"text": "php artisan make:controller MailController --plain\n"
},
{
"code": null,
"e": 5403,
"s": 5326,
"text": "Step 4 − After successful execution, you will receive the following output −"
},
{
"code": null,
"e": 5439,
"s": 5403,
"text": "Step 5 − Copy the following code in"
},
{
"code": null,
"e": 5485,
"s": 5439,
"text": "app/Http/Controllers/MailController.php file."
},
{
"code": null,
"e": 5525,
"s": 5485,
"text": "app/Http/Controllers/MailController.php"
},
{
"code": null,
"e": 7004,
"s": 5525,
"text": "<?php\n\nnamespace App\\Http\\Controllers;\nuse Illuminate\\Http\\Request;\nuse Mail;\n\nuse App\\Http\\Requests;\nuse App\\Http\\Controllers\\Controller;\n\nclass MailController extends Controller {\n public function basic_email() {\n $data = array('name'=>\"Virat Gandhi\");\n \n Mail::send(['text'=>'mail'], $data, function($message) {\n $message->to('abc@gmail.com', 'Tutorials Point')->subject\n ('Laravel Basic Testing Mail');\n $message->from('xyz@gmail.com','Virat Gandhi');\n });\n echo \"Basic Email Sent. Check your inbox.\";\n }\n public function html_email() {\n $data = array('name'=>\"Virat Gandhi\");\n Mail::send('mail', $data, function($message) {\n $message->to('abc@gmail.com', 'Tutorials Point')->subject\n ('Laravel HTML Testing Mail');\n $message->from('xyz@gmail.com','Virat Gandhi');\n });\n echo \"HTML Email Sent. Check your inbox.\";\n }\n public function attachment_email() {\n $data = array('name'=>\"Virat Gandhi\");\n Mail::send('mail', $data, function($message) {\n $message->to('abc@gmail.com', 'Tutorials Point')->subject\n ('Laravel Testing Mail with Attachment');\n $message->attach('C:\\laravel-master\\laravel\\public\\uploads\\image.png');\n $message->attach('C:\\laravel-master\\laravel\\public\\uploads\\test.txt');\n $message->from('xyz@gmail.com','Virat Gandhi');\n });\n echo \"Email Sent with attachment. Check your inbox.\";\n }\n}"
},
{
"code": null,
"e": 7077,
"s": 7004,
"text": "Step 6 − Copy the following code in resources/views/mail.blade.php file."
},
{
"code": null,
"e": 7108,
"s": 7077,
"text": "resources/views/mail.blade.php"
},
{
"code": null,
"e": 7169,
"s": 7108,
"text": "<h1>Hi, {{ $name }}</h1>\nl<p>Sending Mail from Laravel.</p>\n"
},
{
"code": null,
"e": 7226,
"s": 7169,
"text": "Step 7 − Add the following lines in app/Http/routes.php."
},
{
"code": null,
"e": 7246,
"s": 7226,
"text": "app/Http/routes.php"
},
{
"code": null,
"e": 7432,
"s": 7246,
"text": "Route::get('sendbasicemail','MailController@basic_email');\nRoute::get('sendhtmlemail','MailController@html_email');\nRoute::get('sendattachmentemail','MailController@attachment_email');\n"
},
{
"code": null,
"e": 7486,
"s": 7432,
"text": "Step 8 − Visit the following URL to test basic email."
},
{
"code": null,
"e": 7524,
"s": 7486,
"text": "http://localhost:8000/sendbasicemail\n"
},
{
"code": null,
"e": 7630,
"s": 7524,
"text": "Step 9 − The output screen will look something like this. Check your inbox to see the basic email output."
},
{
"code": null,
"e": 7688,
"s": 7630,
"text": "Step 10 − Visit the following URL to test the HTML email."
},
{
"code": null,
"e": 7725,
"s": 7688,
"text": "http://localhost:8000/sendhtmlemail\n"
},
{
"code": null,
"e": 7831,
"s": 7725,
"text": "Step 11 − The output screen will look something like this. Check your inbox to see the html email output."
},
{
"code": null,
"e": 7905,
"s": 7831,
"text": "Step 12 − Visit the following URL to test the HTML email with attachment."
},
{
"code": null,
"e": 7948,
"s": 7905,
"text": "http://localhost:8000/sendattachmentemail\n"
},
{
"code": null,
"e": 7991,
"s": 7948,
"text": "Step 13 − You can see the following output"
},
{
"code": null,
"e": 8202,
"s": 7991,
"text": "Note − In the MailController.php file the email address in the from method should be the email address from which you can send email address. Generally, it should be the email address configured on your server."
},
{
"code": null,
"e": 8235,
"s": 8202,
"text": "\n 13 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 8255,
"s": 8235,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 8290,
"s": 8255,
"text": "\n 35 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8304,
"s": 8290,
"text": " Antonio Papa"
},
{
"code": null,
"e": 8338,
"s": 8304,
"text": "\n 7 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8358,
"s": 8338,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 8391,
"s": 8358,
"text": "\n 42 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8411,
"s": 8391,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 8446,
"s": 8411,
"text": "\n 165 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 8469,
"s": 8446,
"text": " Paul Carlo Tordecilla"
},
{
"code": null,
"e": 8504,
"s": 8469,
"text": "\n 116 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 8524,
"s": 8504,
"text": " Hafizullah Masoudi"
},
{
"code": null,
"e": 8531,
"s": 8524,
"text": " Print"
},
{
"code": null,
"e": 8542,
"s": 8531,
"text": " Add Notes"
}
] |
Auto-deploy FastAPI App to Heroku via Git in these 5 Easy Steps | by Mandy Gu | Towards Data Science
|
If you are not working with an existing app, you can refer to my Iris Classifier FastAPI App for reference. I wrote an article about how to set that up (the Docker component is optional).
Note: I put the Iris app together really quickly to demonstrate how to set up FastAPI — it certainly does not adhere to best practices when it comes to serving model predictions
towardsdatascience.com
This is my GitHub repo for the Iris Classifier app. We will be using this as an example in this tutorial. Make sure that the FastAPI project you are working with is also hosted as a GitHub repository.
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
The FastAPI website provides more detail on how FastAPI works and the advantages of using FastAPI.
Heroku is a platform as a service (PaaS) that enables developers to build, run, and operate applications entirely in the cloud.
I really like using Heroku to showcase my side projects because it’s easy to set up and the free tier is usually enough for most purposes.
In this article, I’m going to use Heroku to deploy my FastAPI app to the public internet and sync the master branch with the production app. Any time I push changes to the master branch, they will sync on the web app.
The Procfile specifies the commands that are executed by the app upon startup. Create a new file called Procfile (no extensions, make sure you are using the same casing).
This is the Procfile for the Iris classifier:
web: uvicorn iris.app:app --host=0.0.0.0 --port=${PORT:-5000}
If you are using your own FastAPI project, change the path iris.app:app accordingly. This is the path to the instantiated FastAPI() object.
Here is mine for reference.
Follow the instructions on the Heroku website to download the CLI:
devcenter.heroku.com
Although we aren’t actually using the CLI at all here, the CLI makes it easy to manage the app through the terminal.
Go to https://www.heroku.com/ and create an account. Navigate to the dashboard to create a new app.
I named my app irisclassifierfastapi. The name determines the default URL — this project will be hosted at www.irisclassifierfastapi.herokuapp.com. Custom domains can be added to the app on the app’sSettings page.
Navigate to the deploy tab and click on the GitHub logo to authenticate and authorize Heroku to deploy code from your GitHub account.
Once connected, select the repository to connect to the app. From there, choose a branch and hit Enable Automatic Deploys. If you are using a CI tool, you can check the checkbox to ensure that CI passes before changes are deployed.
The next time you push changes to your master branch, the app will be deployed. Since we haven’t deployed our app yet (and have made no changes so far), we can trigger a manual deployment by scrolling to the bottom of the deployment tab.
If you installed the CLI, manual deploys can also be executed through the command line.
devcenter.heroku.com
It takes close to a minute for changes to be deployed. You can find the Swagger UI for the Iris Classifier on https://irisclassifierfastapi.herokuapp.com/docs
As long as my application is running, this CURL request allows me to fetch predictions from the classifier.
curl 'http://irisclassifierfastapi.herokuapp.com/iris/classify_iris' -X POST -H 'Content-Type: application/json' -d '{"sepal_l": 5, "sepal_w": 2, "petal_l": 3, "petal_w": 4}'
The classifier predicts that this iris is a Virginica with 91% probability.
Here are some tools you can leverage to debug bad deployments and to monitor your app in general.
In the app page, click More and select View logs from the drop down menu to see application logs. Each log is an event that occurred within the app. Logs can be used to provide information (for instance, you can log user attributes), warnings and errors.
You can use the Python logging library to add more logs that will make it easier to debug your application.
In case of a bad deployment, you may want to rollback your changes. While you can do this in Git by reverting to a previous commit, Heroku also provides the option of doing it through the UI.
Navigate to the Activity tab to see previous builds and click Roll back to here to revert to a previous build.
Metrics are not available for the free tier. The metrics charts capture information related to system health and performance, such as memory usage and event occurrence.
This is what the metrics tab look like for one of my apps under the Hobby tier:
If you are interested in learning more about app development, check out this course.
click.linksynergy.com
If you enjoyed this article, consider buying me a coffee — every small contribution helps me find more time to work on this blog. Follow me on Medium for the latest updates. 😃
I am also building a comprehensive set of free Data Science lessons and practice problems at www.dscrashcourse.com as a hobby project.
Thank you again for reading! 📕
|
[
{
"code": null,
"e": 360,
"s": 172,
"text": "If you are not working with an existing app, you can refer to my Iris Classifier FastAPI App for reference. I wrote an article about how to set that up (the Docker component is optional)."
},
{
"code": null,
"e": 538,
"s": 360,
"text": "Note: I put the Iris app together really quickly to demonstrate how to set up FastAPI — it certainly does not adhere to best practices when it comes to serving model predictions"
},
{
"code": null,
"e": 561,
"s": 538,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 762,
"s": 561,
"text": "This is my GitHub repo for the Iris Classifier app. We will be using this as an example in this tutorial. Make sure that the FastAPI project you are working with is also hosted as a GitHub repository."
},
{
"code": null,
"e": 894,
"s": 762,
"text": "FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints."
},
{
"code": null,
"e": 993,
"s": 894,
"text": "The FastAPI website provides more detail on how FastAPI works and the advantages of using FastAPI."
},
{
"code": null,
"e": 1121,
"s": 993,
"text": "Heroku is a platform as a service (PaaS) that enables developers to build, run, and operate applications entirely in the cloud."
},
{
"code": null,
"e": 1260,
"s": 1121,
"text": "I really like using Heroku to showcase my side projects because it’s easy to set up and the free tier is usually enough for most purposes."
},
{
"code": null,
"e": 1478,
"s": 1260,
"text": "In this article, I’m going to use Heroku to deploy my FastAPI app to the public internet and sync the master branch with the production app. Any time I push changes to the master branch, they will sync on the web app."
},
{
"code": null,
"e": 1649,
"s": 1478,
"text": "The Procfile specifies the commands that are executed by the app upon startup. Create a new file called Procfile (no extensions, make sure you are using the same casing)."
},
{
"code": null,
"e": 1695,
"s": 1649,
"text": "This is the Procfile for the Iris classifier:"
},
{
"code": null,
"e": 1757,
"s": 1695,
"text": "web: uvicorn iris.app:app --host=0.0.0.0 --port=${PORT:-5000}"
},
{
"code": null,
"e": 1897,
"s": 1757,
"text": "If you are using your own FastAPI project, change the path iris.app:app accordingly. This is the path to the instantiated FastAPI() object."
},
{
"code": null,
"e": 1925,
"s": 1897,
"text": "Here is mine for reference."
},
{
"code": null,
"e": 1992,
"s": 1925,
"text": "Follow the instructions on the Heroku website to download the CLI:"
},
{
"code": null,
"e": 2013,
"s": 1992,
"text": "devcenter.heroku.com"
},
{
"code": null,
"e": 2130,
"s": 2013,
"text": "Although we aren’t actually using the CLI at all here, the CLI makes it easy to manage the app through the terminal."
},
{
"code": null,
"e": 2230,
"s": 2130,
"text": "Go to https://www.heroku.com/ and create an account. Navigate to the dashboard to create a new app."
},
{
"code": null,
"e": 2444,
"s": 2230,
"text": "I named my app irisclassifierfastapi. The name determines the default URL — this project will be hosted at www.irisclassifierfastapi.herokuapp.com. Custom domains can be added to the app on the app’sSettings page."
},
{
"code": null,
"e": 2578,
"s": 2444,
"text": "Navigate to the deploy tab and click on the GitHub logo to authenticate and authorize Heroku to deploy code from your GitHub account."
},
{
"code": null,
"e": 2810,
"s": 2578,
"text": "Once connected, select the repository to connect to the app. From there, choose a branch and hit Enable Automatic Deploys. If you are using a CI tool, you can check the checkbox to ensure that CI passes before changes are deployed."
},
{
"code": null,
"e": 3048,
"s": 2810,
"text": "The next time you push changes to your master branch, the app will be deployed. Since we haven’t deployed our app yet (and have made no changes so far), we can trigger a manual deployment by scrolling to the bottom of the deployment tab."
},
{
"code": null,
"e": 3136,
"s": 3048,
"text": "If you installed the CLI, manual deploys can also be executed through the command line."
},
{
"code": null,
"e": 3157,
"s": 3136,
"text": "devcenter.heroku.com"
},
{
"code": null,
"e": 3316,
"s": 3157,
"text": "It takes close to a minute for changes to be deployed. You can find the Swagger UI for the Iris Classifier on https://irisclassifierfastapi.herokuapp.com/docs"
},
{
"code": null,
"e": 3424,
"s": 3316,
"text": "As long as my application is running, this CURL request allows me to fetch predictions from the classifier."
},
{
"code": null,
"e": 3599,
"s": 3424,
"text": "curl 'http://irisclassifierfastapi.herokuapp.com/iris/classify_iris' -X POST -H 'Content-Type: application/json' -d '{\"sepal_l\": 5, \"sepal_w\": 2, \"petal_l\": 3, \"petal_w\": 4}'"
},
{
"code": null,
"e": 3675,
"s": 3599,
"text": "The classifier predicts that this iris is a Virginica with 91% probability."
},
{
"code": null,
"e": 3773,
"s": 3675,
"text": "Here are some tools you can leverage to debug bad deployments and to monitor your app in general."
},
{
"code": null,
"e": 4028,
"s": 3773,
"text": "In the app page, click More and select View logs from the drop down menu to see application logs. Each log is an event that occurred within the app. Logs can be used to provide information (for instance, you can log user attributes), warnings and errors."
},
{
"code": null,
"e": 4136,
"s": 4028,
"text": "You can use the Python logging library to add more logs that will make it easier to debug your application."
},
{
"code": null,
"e": 4328,
"s": 4136,
"text": "In case of a bad deployment, you may want to rollback your changes. While you can do this in Git by reverting to a previous commit, Heroku also provides the option of doing it through the UI."
},
{
"code": null,
"e": 4439,
"s": 4328,
"text": "Navigate to the Activity tab to see previous builds and click Roll back to here to revert to a previous build."
},
{
"code": null,
"e": 4608,
"s": 4439,
"text": "Metrics are not available for the free tier. The metrics charts capture information related to system health and performance, such as memory usage and event occurrence."
},
{
"code": null,
"e": 4688,
"s": 4608,
"text": "This is what the metrics tab look like for one of my apps under the Hobby tier:"
},
{
"code": null,
"e": 4773,
"s": 4688,
"text": "If you are interested in learning more about app development, check out this course."
},
{
"code": null,
"e": 4795,
"s": 4773,
"text": "click.linksynergy.com"
},
{
"code": null,
"e": 4971,
"s": 4795,
"text": "If you enjoyed this article, consider buying me a coffee — every small contribution helps me find more time to work on this blog. Follow me on Medium for the latest updates. 😃"
},
{
"code": null,
"e": 5106,
"s": 4971,
"text": "I am also building a comprehensive set of free Data Science lessons and practice problems at www.dscrashcourse.com as a hobby project."
}
] |
JavaScript - Quick Guide
|
JavaScript is a dynamic computer programming language. It is lightweight and most commonly used as a part of web pages, whose implementations allow client-side script to interact with the user and make dynamic pages. It is an interpreted programming language with object-oriented capabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because of the excitement being generated by Java. JavaScript made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers.
The ECMA-262 Specification defined a standard version of the core JavaScript language.
JavaScript is a lightweight, interpreted programming language.
Designed for creating network-centric applications.
Complementary to and integrated with Java.
Complementary to and integrated with HTML.
Open and cross-platform
Client-side JavaScript is the most common form of the language. The script should be included in or referenced by an HTML document for the code to be interpreted by the browser.
It means that a web page need not be a static HTML, but can include programs that interact with the user, control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI server-side scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail address in a form field.
The JavaScript code is executed when the user submits the form, and only if all the entries are valid, they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other actions that the user initiates explicitly or implicitly.
The merits of using JavaScript are −
Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server.
Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server.
Immediate feedback to the visitors − They don't have to wait for a page reload to see if they have forgotten to enter something.
Immediate feedback to the visitors − They don't have to wait for a page reload to see if they have forgotten to enter something.
Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard.
Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard.
Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.
Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.
We cannot treat JavaScript as a full-fledged programming language. It lacks the following important features −
Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason.
Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason.
JavaScript cannot be used for networking applications because there is no such support available.
JavaScript cannot be used for networking applications because there is no such support available.
JavaScript doesn't have any multi-threading or multiprocessor capabilities.
JavaScript doesn't have any multi-threading or multiprocessor capabilities.
Once again, JavaScript is a lightweight, interpreted programming language that allows you to build interactivity into otherwise static HTML pages.
One of major strengths of JavaScript is that it does not require expensive development tools. You can start with a simple text editor such as Notepad. Since it is an interpreted language inside the context of a web browser, you don't even need to buy a compiler.
To make our life simpler, various vendors have come up with very nice JavaScript editing tools. Some of them are listed here −
Microsoft FrontPage − Microsoft has developed a popular HTML editor called FrontPage. FrontPage also provides web developers with a number of JavaScript tools to assist in the creation of interactive websites.
Microsoft FrontPage − Microsoft has developed a popular HTML editor called FrontPage. FrontPage also provides web developers with a number of JavaScript tools to assist in the creation of interactive websites.
Macromedia Dreamweaver MX − Macromedia Dreamweaver MX is a very popular HTML and JavaScript editor in the professional web development crowd. It provides several handy prebuilt JavaScript components, integrates well with databases, and conforms to new standards such as XHTML and XML.
Macromedia Dreamweaver MX − Macromedia Dreamweaver MX is a very popular HTML and JavaScript editor in the professional web development crowd. It provides several handy prebuilt JavaScript components, integrates well with databases, and conforms to new standards such as XHTML and XML.
Macromedia HomeSite 5 − HomeSite 5 is a well-liked HTML and JavaScript editor from Macromedia that can be used to manage personal websites effectively.
Macromedia HomeSite 5 − HomeSite 5 is a well-liked HTML and JavaScript editor from Macromedia that can be used to manage personal websites effectively.
The ECMAScript Edition 5 standard will be the first update to be released in over four years. JavaScript 2.0 conforms to Edition 5 of the ECMAScript standard, and the difference between the two is extremely minor.
The specification for JavaScript 2.0 can be found on the following site: http://www.ecmascript.org/
Today, Netscape's JavaScript and Microsoft's JScript conform to the ECMAScript standard, although both the languages still support the features that are not a part of the standard.
JavaScript can be implemented using JavaScript statements that are placed within the <script>... </script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is normally recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between these tags as a script. A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>
The script tag takes two important attributes −
Language − This attribute specifies what scripting language you are using. Typically, its value will be javascript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute.
Language − This attribute specifies what scripting language you are using. Typically, its value will be javascript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute.
Type − This attribute is what is now recommended to indicate the scripting language in use and its value should be set to "text/javascript".
Type − This attribute is what is now recommended to indicate the scripting language in use and its value should be set to "text/javascript".
So your JavaScript segment will look like −
<script language = "javascript" type = "text/javascript">
JavaScript code
</script>
Let us take a sample example to print out "Hello World". We added an optional HTML comment that surrounds our JavaScript code. This is to save our code from a browser that does not support JavaScript. The comment ends with a "//-->". Here "//" signifies a comment in JavaScript, so we add that to prevent a browser from reading the end of the HTML comment as a piece of JavaScript code. Next, we call a function document.write which writes a string into our HTML document.
This function can be used to write text, HTML, or both. Take a look at the following code.
<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
This code will produce the following result −
Hello World!
JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. You can use spaces, tabs, and newlines freely in your program and you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand.
Simple statements in JavaScript are generally followed by a semicolon character, just as they are in C, C++, and Java. JavaScript, however, allows you to omit this semicolon if each of your statements are placed on a separate line. For example, the following code could be written without semicolons.
<script language = "javascript" type = "text/javascript">
<!--
var1 = 10
var2 = 20
//-->
</script>
But when formatted in a single line as follows, you must use semicolons −
<script language = "javascript" type = "text/javascript">
<!--
var1 = 10; var2 = 20;
//-->
</script>
Note − It is a good programming practice to use semicolons.
JavaScript is a case-sensitive language. This means that the language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.
So the identifiers Time and TIME will convey different meanings in JavaScript.
NOTE − Care should be taken while writing variable and function names in JavaScript.
JavaScript supports both C-style and C++-style comments, Thus −
Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.
Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.
Any text between the characters /* and */ is treated as a comment. This may span multiple lines.
Any text between the characters /* and */ is treated as a comment. This may span multiple lines.
JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a single-line comment, just as it does the // comment.
JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a single-line comment, just as it does the // comment.
The HTML comment closing sequence --> is not recognized by JavaScript so it should be written as //-->.
The HTML comment closing sequence --> is not recognized by JavaScript so it should be written as //-->.
The following example shows how to use comments in JavaScript.
<script language = "javascript" type = "text/javascript">
<!--
// This is a comment. It is similar to comments in C++
/*
* This is a multi-line comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>
All the modern browsers come with built-in support for JavaScript. Frequently, you may need to enable or disable this support manually. This chapter explains the procedure of enabling and disabling JavaScript support in your browsers: Internet Explorer, Firefox, chrome, and Opera.
Here are simple steps to turn on or turn off JavaScript in your Internet Explorer −
Follow Tools → Internet Options from the menu.
Follow Tools → Internet Options from the menu.
Select Security tab from the dialog box.
Select Security tab from the dialog box.
Click the Custom Level button.
Click the Custom Level button.
Scroll down till you find Scripting option.
Scroll down till you find Scripting option.
Select Enable radio button under Active scripting.
Select Enable radio button under Active scripting.
Finally click OK and come out
Finally click OK and come out
To disable JavaScript support in your Internet Explorer, you need to select Disable radio button under Active scripting.
Here are the steps to turn on or turn off JavaScript in Firefox −
Open a new tab → type about: config in the address bar.
Open a new tab → type about: config in the address bar.
Then you will find the warning dialog. Select I’ll be careful, I promise!
Then you will find the warning dialog. Select I’ll be careful, I promise!
Then you will find the list of configure options in the browser.
Then you will find the list of configure options in the browser.
In the search bar, type javascript.enabled.
In the search bar, type javascript.enabled.
There you will find the option to enable or disable javascript by right-clicking on the value of that option → select toggle.
There you will find the option to enable or disable javascript by right-clicking on the value of that option → select toggle.
If javascript.enabled is true; it converts to false upon clicking toogle. If javascript is disabled; it gets enabled upon clicking toggle.
Here are the steps to turn on or turn off JavaScript in Chrome −
Click the Chrome menu at the top right hand corner of your browser.
Click the Chrome menu at the top right hand corner of your browser.
Select Settings.
Select Settings.
Click Show advanced settings at the end of the page.
Click Show advanced settings at the end of the page.
Under the Privacy section, click the Content settings button.
Under the Privacy section, click the Content settings button.
In the "Javascript" section, select "Do not allow any site to run JavaScript" or "Allow all sites to run JavaScript (recommended)".
In the "Javascript" section, select "Do not allow any site to run JavaScript" or "Allow all sites to run JavaScript (recommended)".
Here are the steps to turn on or turn off JavaScript in Opera −
Follow Tools → Preferences from the menu.
Follow Tools → Preferences from the menu.
Select Advanced option from the dialog box.
Select Advanced option from the dialog box.
Select Content from the listed items.
Select Content from the listed items.
Select Enable JavaScript checkbox.
Select Enable JavaScript checkbox.
Finally click OK and come out.
Finally click OK and come out.
To disable JavaScript support in your Opera, you should not select the Enable JavaScript checkbox.
If you have to do something important using JavaScript, then you can display a warning message to the user using <noscript> tags.
You can add a noscript block immediately after the script block as follows −
<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
<noscript>
Sorry...JavaScript is needed to go ahead.
</noscript>
</body>
</html>
Now, if the user's browser does not support JavaScript or JavaScript is not enabled, then the message from </noscript> will be displayed on the screen.
There is a flexibility given to include JavaScript code anywhere in an HTML document. However the most preferred ways to include JavaScript in an HTML file are as follows −
Script in <head>...</head> section.
Script in <head>...</head> section.
Script in <body>...</body> section.
Script in <body>...</body> section.
Script in <body>...</body> and <head>...</head> sections.
Script in <body>...</body> and <head>...</head> sections.
Script in an external file and then include in <head>...</head> section.
Script in an external file and then include in <head>...</head> section.
In the following section, we will see how we can place JavaScript in an HTML file in different ways.
If you want to have a script run on some event, such as when a user clicks somewhere, then you will place that script in the head as follows −
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>
This code will produce the following results −
Click here for the result
If you need a script to run as the page loads so that the script generates content in the page, then the script goes in the <body> portion of the document. In this case, you would not have any function defined using JavaScript. Take a look at the following code.
<html>
<head>
</head>
<body>
<script type = "text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
This code will produce the following results −
This is web page body
You can put your JavaScript code in <head> and <body> section altogether as follows −
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type = "text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>
This code will produce the following result −
Hello World
As you begin to work more extensively with JavaScript, you will be likely to find that there are cases where you are reusing identical JavaScript code on multiple pages of a site.
You are not restricted to be maintaining identical code in multiple HTML files. The script tag provides a mechanism to allow you to store JavaScript in an external file and then include it into your HTML files.
Here is an example to show how you can include an external JavaScript file in your HTML code using script tag and its src attribute.
<html>
<head>
<script type = "text/javascript" src = "filename.js" ></script>
</head>
<body>
.......
</body>
</html>
To use JavaScript from an external file source, you need to write all your JavaScript source code in a simple text file with the extension ".js" and then include that file as shown above.
For example, you can keep the following content in filename.js file and then you can use sayHello function in your HTML file after including the filename.js file.
function sayHello() {
alert("Hello World")
}
One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language.
JavaScript allows you to work with three primitive data types −
Numbers, eg. 123, 120.50 etc.
Numbers, eg. 123, 120.50 etc.
Strings of text e.g. "This text string" etc.
Strings of text e.g. "This text string" etc.
Boolean e.g. true or false.
Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which defines only a single value. In addition to these primitive data types, JavaScript supports a composite data type known as object. We will cover objects in detail in a separate chapter.
Note − JavaScript does not make a distinction between integer values and floating-point values. All numbers in JavaScript are represented as floating-point values. JavaScript represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard.
Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows.
<script type = "text/javascript">
<!--
var money;
var name;
//-->
</script>
You can also declare multiple variables with the same var keyword as follows −
<script type = "text/javascript">
<!--
var money, name;
//-->
</script>
Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or at a later point in time when you need that variable.
For instance, you might create a variable named money and assign the value 2000.50 to it later. For another variable, you can assign a value at the time of initialization as follows.
<script type = "text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
Note − Use the var keyword only for declaration or initialization, once for the life of any variable name in a document. You should not re-declare same variable twice.
JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don't have to tell JavaScript during variable declaration what type of value the variable will hold. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically.
The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes.
Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code.
Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code.
Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. Take a look into the following example.
<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
</body>
</html>
This produces the following result −
local
While naming your variables in JavaScript, keep the following rules in mind.
You should not use any of the JavaScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid.
You should not use any of the JavaScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid.
JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one.
JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one.
JavaScript variable names are case-sensitive. For example, Name and name are two different variables.
JavaScript variable names are case-sensitive. For example, Name and name are two different variables.
A list of all the reserved words in JavaScript are given in the following table. They cannot be used as JavaScript variables, functions, methods, loop labels, or any object names.
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is called the operator. JavaScript supports the following types of operators.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Lets have a look on all operators one by one.
JavaScript supports the following arithmetic operators −
Assume variable A holds 10 and variable B holds 20, then −
+ (Addition)
Adds two operands
Ex: A + B will give 30
- (Subtraction)
Subtracts the second operand from the first
Ex: A - B will give -10
* (Multiplication)
Multiply both operands
Ex: A * B will give 200
/ (Division)
Divide the numerator by the denominator
Ex: B / A will give 2
% (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0
++ (Increment)
Increases an integer value by one
Ex: A++ will give 11
-- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9
Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".
The following code shows how to use arithmetic operators in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);
a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);
b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
//-->
</script>
Set the variables to different values and then try...
</body>
</html>
a + b = 43
a - b = 23
a / b = 3.3
a % b = 3
a + b + c = 43Test
++a = 35
--b = 8
Set the variables to different values and then try...
JavaScript supports the following comparison operators −
Assume variable A holds 10 and variable B holds 20, then −
= = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition becomes true.
Ex: (A == B) is not true.
!= (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal, then the condition becomes true.
Ex: (A != B) is true.
> (Greater than)
Checks if the value of the left operand is greater than the value of the right operand, if yes, then the condition becomes true.
Ex: (A > B) is not true.
< (Less than)
Checks if the value of the left operand is less than the value of the right operand, if yes, then the condition becomes true.
Ex: (A < B) is true.
>= (Greater than or Equal to)
Checks if the value of the left operand is greater than or equal to the value of the right operand, if yes, then the condition becomes true.
Ex: (A >= B) is not true.
<= (Less than or Equal to)
Checks if the value of the left operand is less than or equal to the value of the right operand, if yes, then the condition becomes true.
Ex: (A <= B) is true.
The following code shows how to use comparison operators in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
document.write("(a == b) => ");
result = (a == b);
document.write(result);
document.write(linebreak);
document.write("(a < b) => ");
result = (a < b);
document.write(result);
document.write(linebreak);
document.write("(a > b) => ");
result = (a > b);
document.write(result);
document.write(linebreak);
document.write("(a != b) => ");
result = (a != b);
document.write(result);
document.write(linebreak);
document.write("(a >= b) => ");
result = (a >= b);
document.write(result);
document.write(linebreak);
document.write("(a <= b) => ");
result = (a <= b);
document.write(result);
document.write(linebreak);
//-->
</script>
Set the variables to different values and different operators and then try...
</body>
</html>
(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false
a <= b) => true
Set the variables to different values and different operators and then try...
JavaScript supports the following logical operators −
Assume variable A holds 10 and variable B holds 20, then −
&& (Logical AND)
If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.
|| (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical NOT operator will make it false.
Ex: ! (A && B) is false.
Try the following code to learn how to implement Logical Operators in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";
document.write("(a && b) => ");
result = (a && b);
document.write(result);
document.write(linebreak);
document.write("(a || b) => ");
result = (a || b);
document.write(result);
document.write(linebreak);
document.write("!(a && b) => ");
result = (!(a && b));
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
(a && b) => false
(a || b) => true
!(a && b) => true
Set the variables to different values and different operators and then try...
JavaScript supports the following bitwise operators −
Assume variable A holds 2 and variable B holds 3, then −
& (Bitwise AND)
It performs a Boolean AND operation on each bit of its integer arguments.
Ex: (A & B) is 2.
| (BitWise OR)
It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.
^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both.
Ex: (A ^ B) is 1.
~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand.
Ex: (~B) is -4.
<< (Left Shift)
It moves all the bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying by 4, and so on.
Ex: (A << 1) is 4.
>> (Right Shift)
Binary Right Shift Operator. The left operand’s value is moved right by the number of bits specified by the right operand.
Ex: (A >> 1) is 1.
>>> (Right shift with Zero)
This operator is just like the >> operator, except that the bits shifted in on the left are always zero.
Ex: (A >>> 1) is 1.
Try the following code to implement Bitwise operator in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";
document.write("(a & b) => ");
result = (a & b);
document.write(result);
document.write(linebreak);
document.write("(a | b) => ");
result = (a | b);
document.write(result);
document.write(linebreak);
document.write("(a ^ b) => ");
result = (a ^ b);
document.write(result);
document.write(linebreak);
document.write("(~b) => ");
result = (~b);
document.write(result);
document.write(linebreak);
document.write("(a << b) => ");
result = (a << b);
document.write(result);
document.write(linebreak);
document.write("(a >> b) => ");
result = (a >> b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0
Set the variables to different values and different operators and then try...
JavaScript supports the following assignment operators −
= (Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C
+= (Add and Assignment)
It adds the right operand to the left operand and assigns the result to the left operand.
Ex: C += A is equivalent to C = C + A
−= (Subtract and Assignment)
It subtracts the right operand from the left operand and assigns the result to the left operand.
Ex: C -= A is equivalent to C = C - A
*= (Multiply and Assignment)
It multiplies the right operand with the left operand and assigns the result to the left operand.
Ex: C *= A is equivalent to C = C * A
/= (Divide and Assignment)
It divides the left operand with the right operand and assigns the result to the left operand.
Ex: C /= A is equivalent to C = C / A
%= (Modules and Assignment)
It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A
Note − Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=, |= and ^=.
Try the following code to implement assignment operator in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";
document.write("Value of a => (a = b) => ");
result = (a = b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a += b) => ");
result = (a += b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a -= b) => ");
result = (a -= b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a *= b) => ");
result = (a *= b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a /= b) => ");
result = (a /= b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a %= b) => ");
result = (a %= b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Value of a => (a = b) => 10
Value of a => (a += b) => 20
Value of a => (a -= b) => 10
Value of a => (a *= b) => 100
Value of a => (a /= b) => 10
Value of a => (a %= b) => 0
Set the variables to different values and different operators and then try...
We will discuss two operators here that are quite useful in JavaScript: the conditional operator (? :) and the typeof operator.
The conditional operator first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation.
? : (Conditional )
If Condition is true? Then value X : Otherwise value Y
Try the following code to understand how the Conditional Operator works in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
document.write ("((a > b) ? 100 : 200) => ");
result = (a > b) ? 100 : 200;
document.write(result);
document.write(linebreak);
document.write ("((a < b) ? 100 : 200) => ");
result = (a < b) ? 100 : 200;
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
Set the variables to different values and different operators and then try...
The typeof operator is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or boolean value and returns true or false based on the evaluation.
Here is a list of the return values for the typeof Operator.
The following code shows how to implement typeof operator.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";
result = (typeof b == "string" ? "B is String" : "B is Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
result = (typeof a == "string" ? "A is String" : "A is Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Result => B is String
Result => A is Numeric
Set the variables to different values and different operators and then try...
While writing a program, there may be a situation when you need to adopt one out of a given set of paths. In such cases, you need to use conditional statements that allow your program to make correct decisions and perform right actions.
JavaScript supports conditional statements which are used to perform different actions based on different conditions. Here we will explain the if..else statement.
The following flow chart shows how the if-else statement works.
JavaScript supports the following forms of if..else statement −
if statement
if statement
if...else statement
if...else statement
if...else if... statement.
if...else if... statement.
The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally.
The syntax for a basic if statement is as follows −
if (expression) {
Statement(s) to be executed if expression is true
}
Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s) are executed. If the expression is false, then no statement would be not executed. Most of the times, you will use comparison operators while making decisions.
Try the following example to understand how the if statement works.
<html>
<body>
<script type = "text/javascript">
<!--
var age = 20;
if( age > 18 ) {
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Qualifies for driving
Set the variable to different value and then try...
The 'if...else' statement is the next form of control statement that allows JavaScript to execute statements in a more controlled way.
if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}
Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else block are executed.
Try the following code to learn how to implement an if-else statement in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var age = 15;
if( age > 18 ) {
document.write("<b>Qualifies for driving</b>");
} else {
document.write("<b>Does not qualify for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Does not qualify for driving
Set the variable to different value and then try...
The if...else if... statement is an advanced form of if...else that allows JavaScript to make a correct decision out of several conditions.
The syntax of an if-else-if statement is as follows −
if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}
There is nothing special about this code. It is just a series of if statements, where each if is a part of the else clause of the previous statement. Statement(s) are executed based on the true condition, if none of the conditions is true, then the else block is executed.
Try the following code to learn how to implement an if-else-if statement in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var book = "maths";
if( book == "history" ) {
document.write("<b>History Book</b>");
} else if( book == "maths" ) {
document.write("<b>Maths Book</b>");
} else if( book == "economics" ) {
document.write("<b>Economics Book</b>");
} else {
document.write("<b>Unknown Book</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
<html>
Maths Book
Set the variable to different value and then try...
You can use multiple if...else...if statements, as in the previous chapter, to perform a multiway branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable.
Starting with JavaScript 1.2, you can use a switch statement which handles exactly this situation, and it does so more efficiently than repeated if...else if statements.
The following flow chart explains a switch-case statement works.
The objective of a switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used.
switch (expression) {
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
The break statements indicate the end of a particular case. If they were omitted, the interpreter would continue executing each statement in each of the following cases.
We will explain break statement in Loop Control chapter.
Try the following example to implement switch-case statement.
<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />");
break;
case 'B': document.write("Pretty good<br />");
break;
case 'C': document.write("Passed<br />");
break;
case 'D': document.write("Not so good<br />");
break;
case 'F': document.write("Failed<br />");
break;
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Entering switch block
Good job
Exiting switch block
Set the variable to different value and then try...
Break statements play a major role in switch-case statements. Try the following code that uses switch-case statement without any break statement.
<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />");
case 'B': document.write("Pretty good<br />");
case 'C': document.write("Passed<br />");
case 'D': document.write("Not so good<br />");
case 'F': document.write("Failed<br />");
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Entering switch block
Good job
Pretty good
Passed
Not so good
Failed
Unknown grade
Exiting switch block
Set the variable to different value and then try...
While writing a program, you may encounter a situation where you need to perform an action over and over again. In such situations, you would need to write loop statements to reduce the number of lines.
JavaScript supports all the necessary loops to ease down the pressure of programming.
The most basic loop in JavaScript is the while loop which would be discussed in this chapter. The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the loop terminates.
The flow chart of while loop looks as follows −
The syntax of while loop in JavaScript is as follows −
while (expression) {
Statement(s) to be executed if expression is true
}
Try the following example to implement while loop.
<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;
document.write("Starting Loop ");
while (count < 10) {
document.write("Current Count : " + count + "<br />");
count++;
}
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...
The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false.
The flow chart of a do-while loop would be as follows −
The syntax for do-while loop in JavaScript is as follows −
do {
Statement(s) to be executed;
} while (expression);
Note − Don’t miss the semicolon used at the end of the do...while loop.
Try the following example to learn how to implement a do-while loop in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br />");
do {
document.write("Current Count : " + count + "<br />");
count++;
}
while (count < 5);
document.write ("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Loop Stopped!
Set the variable to different value and then try...
The 'for' loop is the most compact form of looping. It includes the following three important parts −
The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.
The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.
The iteration statement where you can increase or decrease your counter.
The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
The flow chart of a for loop in JavaScript would be as follows −
The syntax of for loop is JavaScript is as follows −
for (initialization; test condition; iteration statement) {
Statement(s) to be executed if test condition is true
}
Try the following example to learn how a for loop works in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++) {
document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...
The for...in loop is used to loop through an object's properties. As we have not discussed Objects yet, you may not feel comfortable with this loop. But once you understand how objects behave in JavaScript, you will find this loop very useful.
for (variablename in object) {
statement or block to execute
}
In each iteration, one property from object is assigned to variablename and this loop continues till all the properties of the object are exhausted.
Try the following example to implement ‘for-in’ loop. It prints the web browser’s Navigator object.
<html>
<body>
<script type = "text/javascript">
<!--
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator) {
document.write(aProperty);
document.write("<br />");
}
document.write ("Exiting from the loop!");
//-->
</script>
<p>Set the variable to different object and then try...</p>
</body>
</html>
Navigator Object Properties
serviceWorker
webkitPersistentStorage
webkitTemporaryStorage
geolocation
doNotTrack
onLine
languages
language
userAgent
product
platform
appVersion
appName
appCodeName
hardwareConcurrency
maxTouchPoints
vendorSub
vendor
productSub
cookieEnabled
mimeTypes
plugins
javaEnabled
getStorageUpdates
getGamepads
webkitGetUserMedia
vibrate
getBattery
sendBeacon
registerProtocolHandler
unregisterProtocolHandler
Exiting from the loop!
Set the variable to different object and then try...
JavaScript provides full control to handle loops and switch statements. There may be a situation when you need to come out of a loop without reaching its bottom. There may also be a situation when you want to skip a part of your code block and start the next iteration of the loop.
To handle all such situations, JavaScript provides break and continue statements. These statements are used to immediately come out of any loop or to start the next iteration of any loop respectively.
The break statement, which was briefly introduced with the switch statement, is used to exit a loop early, breaking out of the enclosing curly braces.
The flow chart of a break statement would look as follows −
The following example illustrates the use of a break statement with a while loop. Notice how the loop breaks out early once x reaches 5 and reaches to document.write (..) statement just below to the closing curly brace −
<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20) {
if (x == 5) {
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Entering the loop
2
3
4
5
Exiting the loop!
Set the variable to different value and then try...
We already have seen the usage of break statement inside a switch statement.
The continue statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block. When a continue statement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise the control comes out of the loop.
This example illustrates the use of a continue statement with a while loop. Notice how the continue statement is used to skip printing when the index held in variable x reaches 5 −
<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 10) {
x = x + 1;
if (x == 5) {
continue; // skip rest of the loop body
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Entering the loop
2
3
4
6
7
8
9
10
Exiting the loop!
Set the variable to different value and then try...
Starting from JavaScript 1.2, a label can be used with break and continue to control the flow more precisely. A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. We will see two different examples to understand how to use labels with break and continue.
Note − Line breaks are not allowed between the ‘continue’ or ‘break’ statement and its label name. Also, there should not be any other statement in between a label name and associated loop.
Try the following two examples for a better understanding of Labels.
The following example shows how to implement Label with a break statement.
<html>
<body>
<script type = "text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 5; i++) {
document.write("Outerloop: " + i + "<br />");
innerloop:
for (var j = 0; j < 5; j++) {
if (j > 3 ) break ; // Quit the innermost loop
if (i == 2) break innerloop; // Do the same thing
if (i == 4) break outerloop; // Quit the outer loop
document.write("Innerloop: " + j + " <br />");
}
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
</body>
</html>
Entering the loop!
Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 2
Outerloop: 3
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 4
Exiting the loop!
<html>
<body>
<script type = "text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 3; i++) {
document.write("Outerloop: " + i + "<br />");
for (var j = 0; j < 5; j++) {
if (j == 3) {
continue outerloop;
}
document.write("Innerloop: " + j + "<br />");
}
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
</body>
</html>
Entering the loop!
Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 2
Innerloop: 0
Innerloop: 1
Innerloop: 2
Exiting the loop!
A function is a group of reusable code which can be called anywhere in your program. This eliminates the need of writing the same code again and again. It helps programmers in writing modular codes. Functions allow a programmer to divide a big program into a number of small and manageable functions.
Like any other advanced programming language, JavaScript also supports all the features necessary to write modular code using functions. You must have seen functions like alert() and write() in the earlier chapters. We were using these functions again and again, but they had been written in core JavaScript only once.
JavaScript allows us to write our own functions as well. This section explains how to write your own functions in JavaScript.
Before we use a function, we need to define it. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces.
The basic syntax is shown here.
<script type = "text/javascript">
<!--
function functionname(parameter-list) {
statements
}
//-->
</script>
Try the following example. It defines a function called sayHello that takes no parameters −
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello there");
}
//-->
</script>
To invoke a function somewhere later in the script, you would simply need to write the name of that function as shown in the following code.
<html>
<head>
<script type = "text/javascript">
function sayHello() {
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>
Click the following button to call the function
Use different text in write method and then try...
Till now, we have seen functions without parameters. But there is a facility to pass different parameters while calling a function. These passed parameters can be captured inside the function and any manipulation can be done over those parameters. A function can take multiple parameters separated by comma.
Try the following example. We have modified our sayHello function here. Now it takes two parameters.
<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello('Zara', 7)" value = "Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
Click the following button to call the function
Use different parameters inside the function and then try...
A JavaScript function can have an optional return statement. This is required if you want to return a value from a function. This statement should be the last statement in a function.
For example, you can pass two numbers in a function and then you can expect the function to return their multiplication in your calling program.
Try the following example. It defines a function that takes two parameters and concatenates them before returning the resultant in the calling program.
<html>
<head>
<script type = "text/javascript">
function concatenate(first, last) {
var full;
full = first + last;
return full;
}
function secondFunction() {
var result;
result = concatenate('Zara', 'Ali');
document.write (result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "secondFunction()" value = "Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
Click the following button to call the function
Use different parameters inside the function and then try...
There is a lot to learn about JavaScript functions, however we have covered the most important concepts in this tutorial.
JavaScript Nested Functions
JavaScript Nested Functions
JavaScript Function( ) Constructor
JavaScript Function( ) Constructor
JavaScript Function Literals
JavaScript Function Literals
JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other examples include events like pressing any key, closing a window, resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons to close windows, messages to be displayed to users, data to be validated, and virtually any other type of response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of events which can trigger JavaScript Code.
Please go through this small tutorial for a better understanding HTML Event Reference. Here we will see a few examples to understand a relation between Event and JavaScript −
This is the most frequently used event type which occurs when a user clicks the left button of his mouse. You can put your validation, warning etc., against this event type.
Try the following example.
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>
Click the following button and see result
onsubmit is an event that occurs when you try to submit a form. You can put your form validation against this event type.
The following example shows how to use onsubmit. Here we are calling a validate() function before submitting a form data to the webserver. If validate() function returns true, the form will be submitted, otherwise it will not submit the data.
Try the following example.
<html>
<head>
<script type = "text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>
<body>
<form method = "POST" action = "t.cgi" onsubmit = "return validate()">
.......
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
These two event types will help you create nice effects with images or even with text as well. The onmouseover event triggers when you bring your mouse over any element and the onmouseout triggers when you move your mouse out from that element. Try the following example.
<html>
<head>
<script type = "text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover = "over()" onmouseout = "out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>
Bring your mouse inside the division to see the result:
The standard HTML 5 events are listed here for your reference. Here script indicates a Javascript function to be executed against that event.
Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website, it is required to maintain session information among different pages. For example, one user registration ends after completing many pages. But how to maintain users' session information across all the web pages.
In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.
Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the browser sends the same cookie to the server for retrieval. Once retrieved, your server knows/remembers what was stored earlier.
Cookies are a plain text data record of 5 variable-length fields −
Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
Domain − The domain name of your site.
Domain − The domain name of your site.
Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.
Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.
Secure − If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.
Secure − If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.
Name=Value − Cookies are set and retrieved in the form of key-value pairs
Name=Value − Cookies are set and retrieved in the form of key-value pairs
Cookies were originally designed for CGI programming. The data contained in a cookie is automatically transmitted between the web browser and the web server, so CGI scripts on the server can read and write cookie values that are stored on the client.
JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookies that apply to the current web page.
The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this.
document.cookie = "key1 = value1;key2 = value2;expires = date";
Here the expires attribute is optional. If you provide this attribute with a valid date or time, then the cookie will expire on a given date or time and thereafter, the cookies' value will not be accessible.
Note − Cookie values may not include semicolons, commas, or whitespace. For this reason, you may want to use the JavaScript escape() function to encode the value before storing it in the cookie. If you do this, you will also have to use the corresponding unescape() function when you read the cookie value.
Try the following. It sets a customer name in an input cookie.
<html>
<head>
<script type = "text/javascript">
<!--
function WriteCookie() {
if( document.myform.customer.value == "" ) {
alert("Enter some value!");
return;
}
cookievalue = escape(document.myform.customer.value) + ";";
document.cookie = "name=" + cookievalue;
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/>
</form>
</body>
</html>
Now your machine has a cookie called name. You can set multiple cookies using multiple key = value pairs separated by comma.
Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name=value pairs separated by semicolons, where name is the name of a cookie and value is its string value.
You can use strings' split() function to break a string into key and values as follows −
Try the following example to get all the cookies.
<html>
<head>
<script type = "text/javascript">
<!--
function ReadCookie() {
var allcookies = document.cookie;
document.write ("All Cookies : " + allcookies );
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++) {
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
document.write ("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script>
</head>
<body>
<form name = "myform" action = "">
<p> click the following button and see the result:</p>
<input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/>
</form>
</body>
</html>
Note − Here length is a method of Array class which returns the length of an array. We will discuss Arrays in a separate chapter. By that time, please try to digest it.
click the following button and see the result:
Note − There may be some other cookies already set on your machine. The above code will display all the cookies set on your machine.
You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiry date within the cookie. This can be done by setting the ‘expires’ attribute to a date and time.
Try the following example. It illustrates how to extend the expiry date of a cookie by 1 Month.
<html>
<head>
<script type = "text/javascript">
<!--
function WriteCookie() {
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie = "name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
</form>
</body>
</html>
Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiry date to a time in the past.
Try the following example. It illustrates how to delete a cookie by setting its expiry date to one month behind the current date.
<html>
<head>
<script type = "text/javascript">
<!--
function WriteCookie() {
var now = new Date();
now.setMonth( now.getMonth() - 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie = "name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
</form>
</body>
</html>
You might have encountered a situation where you clicked a URL to reach a page X but internally you were directed to another page Y. It happens due to page redirection. This concept is different from JavaScript Page Refresh.
There could be various reasons why you would like to redirect a user from the original page. We are listing down a few of the reasons −
You did not like the name of your domain and you are moving to a new one. In such a scenario, you may want to direct all your visitors to the new site. Here you can maintain your old domain but put a single page with a page redirection such that all your old domain visitors can come to your new domain.
You did not like the name of your domain and you are moving to a new one. In such a scenario, you may want to direct all your visitors to the new site. Here you can maintain your old domain but put a single page with a page redirection such that all your old domain visitors can come to your new domain.
You have built-up various pages based on browser versions or their names or may be based on different countries, then instead of using your server-side page redirection, you can use client-side page redirection to land your users on the appropriate page.
You have built-up various pages based on browser versions or their names or may be based on different countries, then instead of using your server-side page redirection, you can use client-side page redirection to land your users on the appropriate page.
The Search Engines may have already indexed your pages. But while moving to another domain, you would not like to lose your visitors coming through search engines. So you can use client-side page redirection. But keep in mind this should not be done to fool the search engine, it could lead your site to get banned.
The Search Engines may have already indexed your pages. But while moving to another domain, you would not like to lose your visitors coming through search engines. So you can use client-side page redirection. But keep in mind this should not be done to fool the search engine, it could lead your site to get banned.
The implementations of Page-Redirection are as follows.
It is quite simple to do a page redirect using JavaScript at client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows.
<html>
<head>
<script type = "text/javascript">
<!--
function Redirect() {
window.location = "https://www.tutorialspoint.com";
}
//-->
</script>
</head>
<body>
<p>Click the following button, you will be redirected to home page.</p>
<form>
<input type = "button" value = "Redirect Me" onclick = "Redirect();" />
</form>
</body>
</html>
Click the following button, you will be redirected to home page.
You can show an appropriate message to your site visitors before redirecting them to a new page. This would need a bit time delay to load a new page. The following example shows how to implement the same. Here setTimeout() is a built-in JavaScript function which can be used to execute another function after a given time interval.
<html>
<head>
<script type = "text/javascript">
<!--
function Redirect() {
window.location = "https://www.tutorialspoint.com";
}
document.write("You will be redirected to main page in 10 sec.");
setTimeout('Redirect()', 10000);
//-->
</script>
</head>
<body>
</body>
</html>
You will be redirected to tutorialspoint.com main page in 10 seconds!
The following example shows how to redirect your site visitors onto a different page based on their browsers.
<html>
<head>
<script type = "text/javascript">
<!--
var browsername = navigator.appName;
if( browsername == "Netscape" ) {
window.location = "http://www.location.com/ns.htm";
} else if ( browsername =="Microsoft Internet Explorer") {
window.location = "http://www.location.com/ie.htm";
} else {
window.location = "http://www.location.com/other.htm";
}
//-->
</script>
</head>
<body>
</body>
</html>
JavaScript supports three important types of dialog boxes. These dialog boxes can be used to raise and alert, or to get confirmation on any input or to have a kind of input from the users. Here we will discuss each dialog box one by one.
An alert dialog box is mostly used to give a warning message to the users. For example, if one input field requires to enter some text but the user does not provide any input, then as a part of validation, you can use an alert box to give a warning message.
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one button "OK" to select and proceed.
<html>
<head>
<script type = "text/javascript">
<!--
function Warn() {
alert ("This is a warning message!");
document.write ("This is a warning message!");
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "Warn();" />
</form>
</body>
</html>
Click the following button to see the result:
A confirmation dialog box is mostly used to take user's consent on any option. It displays a dialog box with two buttons: OK and Cancel.
If the user clicks on the OK button, the window method confirm() will return true. If the user clicks on the Cancel button, then confirm() returns false. You can use a confirmation dialog box as follows.
<html>
<head>
<script type = "text/javascript">
<!--
function getConfirmation() {
var retVal = confirm("Do you want to continue ?");
if( retVal == true ) {
document.write ("User wants to continue!");
return true;
} else {
document.write ("User does not want to continue!");
return false;
}
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "getConfirmation();" />
</form>
</body>
</html>
Click the following button to see the result:
The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus, it enables you to interact with the user. The user needs to fill in the field and then click OK.
This dialog box is displayed using a method called prompt() which takes two parameters: (i) a label which you want to display in the text box and (ii) a default string to display in the text box.
This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window method prompt() will return the entered value from the text box. If the user clicks the Cancel button, the window method prompt() returns null.
The following example shows how to use a prompt dialog box −
<html>
<head>
<script type = "text/javascript">
<!--
function getValue() {
var retVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + retVal);
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "getValue();" />
</form>
</body>
</html>
Click the following button to see the result:
void is an important keyword in JavaScript which can be used as a unary operator that appears before its single operand, which may be of any type. This operator specifies an expression to be evaluated without returning a value.
The syntax of void can be either of the following two −
<head>
<script type = "text/javascript">
<!--
void func()
javascript:void func()
or:
void(func())
javascript:void(func())
//-->
</script>
</head>
The most common use of this operator is in a client-side javascript: URL, where it allows you to evaluate an expression for its side-effects without the browser displaying the value of the evaluated expression.
Here the expression alert ('Warning!!!') is evaluated but it is not loaded back into the current document −
<html>
<head>
<script type = "text/javascript">
<!--
//-->
</script>
</head>
<body>
<p>Click the following, This won't react at all...</p>
<a href = "javascript:void(alert('Warning!!!'))">Click me!</a>
</body>
</html>
Click the following, This won't react at all...
Take a look at the following example. The following link does nothing because the expression "0" has no effect in JavaScript. Here the expression "0" is evaluated, but it is not loaded back into the current document.
<html>
<head>
<script type = "text/javascript">
<!--
//-->
</script>
</head>
<body>
<p>Click the following, This won't react at all...</p>
<a href = "javascript:void(0)">Click me!</a>
</body>
</html>
Click the following, This won't react at all...
Another use of void is to purposely generate the undefined value as follows.
<html>
<head>
<script type = "text/javascript">
<!--
function getValue() {
var a,b,c;
a = void ( b = 5, c = 7 );
document.write('a = ' + a + ' b = ' + b +' c = ' + c );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "getValue();" />
</form>
</body>
</html>
Click the following to see the result:
Many times you would like to place a button on your webpage to print the content of that web page via an actual printer. JavaScript helps you to implement this functionality using the print function of window object.
The JavaScript print function window.print() prints the current web page when executed. You can call this function directly using the onclick event as shown in the following example.
Try the following example.
<html>
<head>
<script type = "text/javascript">
<!--
//-->
</script>
</head>
<body>
<form>
<input type = "button" value = "Print" onclick = "window.print()" />
</form>
</body>
<html>
Although it serves the purpose of getting a printout, it is not a recommended way. A printer friendly page is really just a page with text, no images, graphics, or advertising.
You can make a page printer friendly in the following ways −
Make a copy of the page and leave out unwanted text and graphics, then link to that printer friendly page from the original. Check Example.
Make a copy of the page and leave out unwanted text and graphics, then link to that printer friendly page from the original. Check Example.
If you do not want to keep an extra copy of a page, then you can mark your printable text using proper comments like <!-- PRINT STARTS HERE -->..... <!-- PRINT ENDS HERE --> and then you can use PERL or any other script in the background to purge printable text and display for final printing. We at Tutorialspoint use this method to provide print facility to our site visitors.
If you do not want to keep an extra copy of a page, then you can mark your printable text using proper comments like <!-- PRINT STARTS HERE -->..... <!-- PRINT ENDS HERE --> and then you can use PERL or any other script in the background to purge printable text and display for final printing. We at Tutorialspoint use this method to provide print facility to our site visitors.
If you don’t find the above facilities on a web page, then you can use the browser's standard toolbar to get print the web page. Follow the link as follows.
File → Print → Click OK button.
JavaScript is an Object Oriented Programming (OOP) language. A programming language can be called object-oriented if it provides four basic capabilities to developers −
Encapsulation − the capability to store related information, whether data or methods, together in an object.
Encapsulation − the capability to store related information, whether data or methods, together in an object.
Aggregation − the capability to store one object inside another object.
Aggregation − the capability to store one object inside another object.
Inheritance − the capability of a class to rely upon another class (or number of classes) for some of its properties and methods.
Inheritance − the capability of a class to rely upon another class (or number of classes) for some of its properties and methods.
Polymorphism − the capability to write one function or method that works in a variety of different ways.
Polymorphism − the capability to write one function or method that works in a variety of different ways.
Objects are composed of attributes. If an attribute contains a function, it is considered to be a method of the object, otherwise the attribute is considered a property.
Object properties can be any of the three primitive data types, or any of the abstract data types, such as another object. Object properties are usually variables that are used internally in the object's methods, but can also be globally visible variables that are used throughout the page.
The syntax for adding a property to an object is −
objectName.objectProperty = propertyValue;
For example − The following code gets the document title using the "title" property of the document object.
var str = document.title;
Methods are the functions that let the object do something or let something be done to it. There is a small difference between a function and a method – at a function is a standalone unit of statements and a method is attached to an object and can be referenced by the this keyword.
Methods are useful for everything from displaying the contents of the object to the screen to performing complex mathematical operations on a group of local properties and parameters.
For example − Following is a simple example to show how to use the write() method of document object to write any content on the document.
document.write("This is test");
All user-defined objects and built-in objects are descendants of an object called Object.
The new operator is used to create an instance of an object. To create an object, the new operator is followed by the constructor method.
In the following example, the constructor methods are Object(), Array(), and Date(). These constructors are built-in JavaScript functions.
var employee = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("August 15, 1947");
A constructor is a function that creates and initializes an object. JavaScript provides a special constructor function called Object() to build the object. The return value of the Object() constructor is assigned to a variable.
The variable contains a reference to the new object. The properties assigned to the object are not variables and are not defined with the var keyword.
Try the following example; it demonstrates how to create an Object.
<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
var book = new Object(); // Create the object
book.subject = "Perl"; // Assign properties to the object
book.author = "Mohtashim";
</script>
</head>
<body>
<script type = "text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>
Book name is : Perl
Book author is : Mohtashim
This example demonstrates how to create an object with a User-Defined Function. Here this keyword is used to refer to the object that has been passed to a function.
<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
function book(title, author) {
this.title = title;
this.author = author;
}
</script>
</head>
<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
</script>
</body>
</html>
Book title is : Perl
Book author is : Mohtashim
The previous examples demonstrate how the constructor creates the object and assigns properties. But we need to complete the definition of an object by assigning methods to it.
Try the following example; it shows how to add a function along with an object.
<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
// Define a function which will work as a method
function addPrice(amount) {
this.price = amount;
}
function book(title, author) {
this.title = title;
this.author = author;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
Book title is : Perl
Book author is : Mohtashim
Book price is : 100
The ‘with’ keyword is used as a kind of shorthand for referencing an object's properties or methods.
The object specified as an argument to with becomes the default object for the duration of the block that follows. The properties and methods for the object can be used without naming the object.
The syntax for with object is as follows −
with (object) {
properties used without the object name and dot
}
Try the following example.
<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
// Define a function which will work as a method
function addPrice(amount) {
with(this) {
price = amount;
}
}
function book(title, author) {
this.title = title;
this.author = author;
this.price = 0;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
Book title is : Perl
Book author is : Mohtashim
Book price is : 100
JavaScript has several built-in or native objects. These objects are accessible anywhere in your program and will work the same way in any browser running in any operating system.
Here is the list of all important JavaScript Native Objects −
JavaScript Number Object
JavaScript Number Object
JavaScript Boolean Object
JavaScript Boolean Object
JavaScript String Object
JavaScript String Object
JavaScript Array Object
JavaScript Array Object
JavaScript Date Object
JavaScript Date Object
JavaScript Math Object
JavaScript Math Object
JavaScript RegExp Object
JavaScript RegExp Object
The Number object represents numerical date, either integers or floating-point numbers. In general, you do not need to worry about Number objects because the browser automatically converts number literals to instances of the number class.
The syntax for creating a number object is as follows −
var val = new Number(number);
In the place of number, if you provide any non-number argument, then the argument cannot be converted into a number, it returns NaN (Not-a-Number).
Here is a list of each property and their description.
The largest possible value a number in JavaScript can have 1.7976931348623157E+308
The smallest possible value a number in JavaScript can have 5E-324
Equal to a value that is not a number.
A value that is less than MIN_VALUE.
A value that is greater than MAX_VALUE
A static property of the Number object. Use the prototype property to assign new properties and methods to the Number object in the current document
Returns the function that created this object's instance. By default this is the Number object.
In the following sections, we will take a few examples to demonstrate the properties of Number.
The Number object contains only the default methods that are a part of every object's definition.
Forces a number to display in exponential notation, even if the number is in the range in which JavaScript normally uses standard notation.
Formats a number with a specific number of digits to the right of the decimal.
Returns a string value version of the current number in a format that may vary according to a browser's local settings.
Defines how many total digits (including digits to the left and right of the decimal) to display of a number.
Returns the string representation of the number's value.
Returns the number's value.
In the following sections, we will have a few examples to explain the methods of Number.
The Boolean object represents two values, either "true" or "false". If value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.
Use the following syntax to create a boolean object.
var val = new Boolean(value);
Here is a list of the properties of Boolean object −
Returns a reference to the Boolean function that created the object.
The prototype property allows you to add properties and methods to an object.
In the following sections, we will have a few examples to illustrate the properties of Boolean object.
Here is a list of the methods of Boolean object and their description.
Returns a string containing the source of the Boolean object; you can use this string to create an equivalent object.
Returns a string of either "true" or "false" depending upon the value of the object.
Returns the primitive value of the Boolean object.
In the following sections, we will have a few examples to demonstrate the usage of the Boolean methods.
The String object lets you work with a series of characters; it wraps Javascript's string primitive data type with a number of helper methods.
As JavaScript automatically converts between string primitives and String objects, you can call any of the helper methods of the String object on a string primitive.
Use the following syntax to create a String object −
var val = new String(string);
The String parameter is a series of characters that has been properly encoded.
Here is a list of the properties of String object and their description.
Returns a reference to the String function that created the object.
Returns the length of the string.
The prototype property allows you to add properties and methods to an object.
In the following sections, we will have a few examples to demonstrate the usage of String properties.
Here is a list of the methods available in String object along with their description.
Returns the character at the specified index.
Returns a number indicating the Unicode value of the character at the given index.
Combines the text of two strings and returns a new string.
Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.
Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
Used to match a regular expression against a string.
Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
Executes the search for a match between a regular expression and a specified string.
Extracts a section of a string and returns a new string.
Splits a String object into an array of strings by separating the string into substrings.
Returns the characters in a string beginning at the specified location through the specified number of characters.
Returns the characters in a string between two indexes into the string.
The characters within a string are converted to lower case while respecting the current locale.
The characters within a string are converted to upper case while respecting the current locale.
Returns the calling string value converted to lower case.
Returns a string representing the specified object.
Returns the calling string value converted to uppercase.
Returns the primitive value of the specified object.
Here is a list of the methods that return a copy of the string wrapped inside an appropriate HTML tag.
Creates an HTML anchor that is used as a hypertext target.
Creates a string to be displayed in a big font as if it were in a <big> tag.
Creates a string to blink as if it were in a <blink> tag.
Creates a string to be displayed as bold as if it were in a <b> tag.
Causes a string to be displayed in fixed-pitch font as if it were in a <tt> tag
Causes a string to be displayed in the specified color as if it were in a <font color="color"> tag.
Causes a string to be displayed in the specified font size as if it were in a <font size="size"> tag.
Causes a string to be italic, as if it were in an <i> tag.
Creates an HTML hypertext link that requests another URL.
Causes a string to be displayed in a small font, as if it were in a <small> tag.
Causes a string to be displayed as struck-out text, as if it were in a <strike> tag.
Causes a string to be displayed as a subscript, as if it were in a <sub> tag
Causes a string to be displayed as a superscript, as if it were in a <sup> tag
In the following sections, we will have a few examples to demonstrate the usage of String methods.
The Array object lets you store multiple values in a single variable. It stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Use the following syntax to create an Array object −
var fruits = new Array( "apple", "orange", "mango" );
The Array parameter is a list of strings or integers. When you specify a single numeric parameter with the Array constructor, you specify the initial length of the array. The maximum length allowed for an array is 4,294,967,295.
You can create array by simply assigning values as follows −
var fruits = [ "apple", "orange", "mango" ];
You will use ordinal numbers to access and to set values inside an array as follows.
fruits[0] is the first element
fruits[1] is the second element
fruits[2] is the third element
Here is a list of the properties of the Array object along with their description.
Returns a reference to the array function that created the object.
index
The property represents the zero-based index of the match in the string
input
This property is only present in arrays created by regular expression matches.
Reflects the number of elements in an array.
The prototype property allows you to add properties and methods to an object.
In the following sections, we will have a few examples to illustrate the usage of Array properties.
Here is a list of the methods of the Array object along with their description.
Returns a new array comprised of this array joined with other array(s) and/or value(s).
Returns true if every element in this array satisfies the provided testing function.
Creates a new array with all of the elements of this array for which the provided filtering function returns true.
Calls a function for each element in the array.
Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
Joins all elements of an array into a string.
Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
Creates a new array with the results of calling a provided function on every element in this array.
Removes the last element from an array and returns that element.
Adds one or more elements to the end of an array and returns the new length of the array.
Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.
Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.
Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.
Removes the first element from an array and returns that element.
Extracts a section of an array and returns a new array.
Returns true if at least one element in this array satisfies the provided testing function.
Represents the source code of an object
Sorts the elements of an array
Adds and/or removes elements from an array.
Returns a string representing the array and its elements.
Adds one or more elements to the front of an array and returns the new length of the array.
In the following sections, we will have a few examples to demonstrate the usage of Array methods.
The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date( ) as shown below.
Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time.
The ECMAScript standard requires the Date object to be able to represent any date and time, to millisecond precision, within 100 million days before or after 1/1/1970. This is a range of plus or minus 273,785 years, so JavaScript can represent date and time till the year 275755.
You can use any of the following syntaxes to create a Date object using Date() constructor.
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])
Note − Parameters in the brackets are always optional.
Here is a description of the parameters −
No Argument − With no arguments, the Date() constructor creates a Date object set to the current date and time.
No Argument − With no arguments, the Date() constructor creates a Date object set to the current date and time.
milliseconds − When one numeric argument is passed, it is taken as the internal numeric representation of the date in milliseconds, as returned by the getTime() method. For example, passing the argument 5000 creates a date that represents five seconds past midnight on 1/1/70.
milliseconds − When one numeric argument is passed, it is taken as the internal numeric representation of the date in milliseconds, as returned by the getTime() method. For example, passing the argument 5000 creates a date that represents five seconds past midnight on 1/1/70.
datestring − When one string argument is passed, it is a string representation of a date, in the format accepted by the Date.parse() method.
datestring − When one string argument is passed, it is a string representation of a date, in the format accepted by the Date.parse() method.
7 agruments − To use the last form of the constructor shown above. Here is a description of each argument −
7 agruments − To use the last form of the constructor shown above. Here is a description of each argument −
year − Integer value representing the year. For compatibility (in order to avoid the Y2K problem), you should always specify the year in full; use 1998, rather than 98.
year − Integer value representing the year. For compatibility (in order to avoid the Y2K problem), you should always specify the year in full; use 1998, rather than 98.
month − Integer value representing the month, beginning with 0 for January to 11 for December.
month − Integer value representing the month, beginning with 0 for January to 11 for December.
date − Integer value representing the day of the month.
date − Integer value representing the day of the month.
hour − Integer value representing the hour of the day (24-hour scale).
hour − Integer value representing the hour of the day (24-hour scale).
minute − Integer value representing the minute segment of a time reading.
minute − Integer value representing the minute segment of a time reading.
second − Integer value representing the second segment of a time reading.
second − Integer value representing the second segment of a time reading.
millisecond − Integer value representing the millisecond segment of a time reading.
millisecond − Integer value representing the millisecond segment of a time reading.
Here is a list of the properties of the Date object along with their description.
Specifies the function that creates an object's prototype.
The prototype property allows you to add properties and methods to an object
In the following sections, we will have a few examples to demonstrate the usage of different Date properties.
Here is a list of the methods used with Date and their description.
Returns today's date and time
Returns the day of the month for the specified date according to local time.
Returns the day of the week for the specified date according to local time.
Returns the year of the specified date according to local time.
Returns the hour in the specified date according to local time.
Returns the milliseconds in the specified date according to local time.
Returns the minutes in the specified date according to local time.
Returns the month in the specified date according to local time.
Returns the seconds in the specified date according to local time.
Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC.
Returns the time-zone offset in minutes for the current locale.
Returns the day (date) of the month in the specified date according to universal time.
Returns the day of the week in the specified date according to universal time.
Returns the year in the specified date according to universal time.
Returns the hours in the specified date according to universal time.
Returns the milliseconds in the specified date according to universal time.
Returns the minutes in the specified date according to universal time.
Returns the month in the specified date according to universal time.
Returns the seconds in the specified date according to universal time.
Deprecated - Returns the year in the specified date according to local time. Use getFullYear instead.
Sets the day of the month for a specified date according to local time.
Sets the full year for a specified date according to local time.
Sets the hours for a specified date according to local time.
Sets the milliseconds for a specified date according to local time.
Sets the minutes for a specified date according to local time.
Sets the month for a specified date according to local time.
Sets the seconds for a specified date according to local time.
Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC.
Sets the day of the month for a specified date according to universal time.
Sets the full year for a specified date according to universal time.
Sets the hour for a specified date according to universal time.
Sets the milliseconds for a specified date according to universal time.
Sets the minutes for a specified date according to universal time.
Sets the month for a specified date according to universal time.
Sets the seconds for a specified date according to universal time.
Deprecated - Sets the year for a specified date according to local time. Use setFullYear instead.
Returns the "date" portion of the Date as a human-readable string.
Deprecated - Converts a date to a string, using the Internet GMT conventions. Use toUTCString instead.
Returns the "date" portion of the Date as a string, using the current locale's conventions.
Converts a date to a string, using a format string.
Converts a date to a string, using the current locale's conventions.
Returns the "time" portion of the Date as a string, using the current locale's conventions.
Returns a string representing the source for an equivalent Date object; you can use this value to create a new object.
Returns a string representing the specified Date object.
Returns the "time" portion of the Date as a human-readable string.
Converts a date to a string, using the universal time convention.
Returns the primitive value of a Date object.
Converts a date to a string, using the universal time convention.
In addition to the many instance methods listed previously, the Date object also defines two static methods. These methods are invoked through the Date() constructor itself.
Parses a string representation of a date and time and returns the internal millisecond representation of that date.
Returns the millisecond representation of the specified UTC date and time.
In the following sections, we will have a few examples to demonstrate the usages of Date Static methods.
The math object provides you properties and methods for mathematical constants and functions. Unlike other global objects, Math is not a constructor. All the properties and methods of Math are static and can be called by using Math as an object without creating it.
Thus, you refer to the constant pi as Math.PI and you call the sine function as Math.sin(x), where x is the method's argument.
The syntax to call the properties and methods of Math are as follows
var pi_val = Math.PI;
var sine_val = Math.sin(30);
Here is a list of all the properties of Math and their description.
Euler's constant and the base of natural logarithms, approximately 2.718.
Natural logarithm of 2, approximately 0.693.
Natural logarithm of 10, approximately 2.302.
Base 2 logarithm of E, approximately 1.442.
Base 10 logarithm of E, approximately 0.434.
Ratio of the circumference of a circle to its diameter, approximately 3.14159.
Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.
Square root of 2, approximately 1.414.
In the following sections, we will have a few examples to demonstrate the usage of Math properties.
Here is a list of the methods associated with Math object and their description
Returns the absolute value of a number.
Returns the arccosine (in radians) of a number.
Returns the arcsine (in radians) of a number.
Returns the arctangent (in radians) of a number.
Returns the arctangent of the quotient of its arguments.
Returns the smallest integer greater than or equal to a number.
Returns the cosine of a number.
Returns EN, where N is the argument, and E is Euler's constant, the base of the natural logarithm.
Returns the largest integer less than or equal to a number.
Returns the natural logarithm (base E) of a number.
Returns the largest of zero or more numbers.
Returns the smallest of zero or more numbers.
Returns base to the exponent power, that is, base exponent.
Returns a pseudo-random number between 0 and 1.
Returns the value of a number rounded to the nearest integer.
Returns the sine of a number.
Returns the square root of a number.
Returns the tangent of a number.
Returns the string "Math".
In the following sections, we will have a few examples to demonstrate the usage of the methods associated with Math.
A regular expression is an object that describes a pattern of characters.
The JavaScript RegExp class represents regular expressions, and both String and RegExp define methods that use regular expressions to perform powerful pattern-matching and search-and-replace functions on text.
A regular expression could be defined with the RegExp () constructor, as follows −
var pattern = new RegExp(pattern, attributes);
or simply
var pattern = /pattern/attributes;
Here is the description of the parameters −
pattern − A string that specifies the pattern of the regular expression or another regular expression.
pattern − A string that specifies the pattern of the regular expression or another regular expression.
attributes − An optional string containing any of the "g", "i", and "m" attributes that specify global, case-insensitive, and multi-line matches, respectively.
attributes − An optional string containing any of the "g", "i", and "m" attributes that specify global, case-insensitive, and multi-line matches, respectively.
Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of characters.
[...]
Any one character between the brackets.
[^...]
Any one character not between the brackets.
[0-9]
It matches any decimal digit from 0 through 9.
[a-z]
It matches any character from lowercase a through lowercase z.
[A-Z]
It matches any character from uppercase A through uppercase Z.
[a-Z]
It matches any character from lowercase a through uppercase Z.
The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v.
The frequency or position of bracketed character sequences and single characters can be denoted by a special character. Each special character has a specific connotation. The +, *, ?, and $ flags all follow a character sequence.
p+
It matches any string containing one or more p's.
p*
It matches any string containing zero or more p's.
p?
It matches any string containing at most one p.
p{N}
It matches any string containing a sequence of N p's
p{2,3}
It matches any string containing a sequence of two or three p's.
p{2, }
It matches any string containing a sequence of at least two p's.
p$
It matches any string with p at the end of it.
^p
It matches any string with p at the beginning of it.
Following examples explain more about matching characters.
[^a-zA-Z]
It matches any string not containing any of the characters ranging from a through z and A through Z.
p.p
It matches any string containing p, followed by any character, in turn followed by another p.
^.{2}$
It matches any string containing exactly two characters.
<b>(.*)</b>
It matches any string enclosed within <b> and </b>.
p(hp)*
It matches any string containing a p followed by zero or more instances of the sequence hp.
Alphanumeric
Itself
\0
The NUL character (\u0000)
\t
Tab (\u0009
\n
Newline (\u000A)
\v
Vertical tab (\u000B)
\f
Form feed (\u000C)
\r
Carriage return (\u000D)
\xnn
The Latin character specified by the hexadecimal number nn; for example, \x0A is the same as \n
\uxxxx
The Unicode character specified by the hexadecimal number xxxx; for example, \u0009 is the same as \t
\cX
The control character ^X; for example, \cJ is equivalent to the newline character \n
A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the combination a special meaning.
For instance, you can search for a large sum of money using the '\d' metacharacter: /([\d]+)000/, Here \d will search for any string of numerical character.
The following table lists a set of metacharacters which can be used in PERL Style Regular Expressions.
.
a single character
\s
a whitespace character (space, tab, newline)
\S
non-whitespace character
\d
a digit (0-9)
\D
a non-digit
\w
a word character (a-z, A-Z, 0-9, _)
\W
a non-word character
[\b]
a literal backspace (special case).
[aeiou]
matches a single character in the given set
[^aeiou]
matches a single character outside the given set
(foo|bar|baz)
matches any of the alternatives specified
Several modifiers are available that can simplify the way you work with regexps, like case sensitivity, searching in multiple lines, etc.
i
Perform case-insensitive matching.
m
Specifies that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary
g
Performs a global matchthat is, find all matches rather than stopping after the first match.
Here is a list of the properties associated with RegExp and their description.
Specifies the function that creates an object's prototype.
Specifies if the "g" modifier is set.
Specifies if the "i" modifier is set.
The index at which to start the next match.
Specifies if the "m" modifier is set.
The text of the pattern.
In the following sections, we will have a few examples to demonstrate the usage of RegExp properties.
Here is a list of the methods associated with RegExp along with their description.
Executes a search for a match in its string parameter.
Tests for a match in its string parameter.
Returns an object literal representing the specified object; you can use this value to create a new object.
Returns a string representing the specified object.
In the following sections, we will have a few examples to demonstrate the usage of RegExp methods.
Every web page resides inside a browser window which can be considered as an object.
A Document object represents the HTML document that is displayed in that window. The Document object has various properties that refer to other objects which allow access to and modification of document content.
The way a document content is accessed and modified is called the Document Object Model, or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document.
Window object − Top of the hierarchy. It is the outmost element of the object hierarchy.
Window object − Top of the hierarchy. It is the outmost element of the object hierarchy.
Document object − Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page.
Document object − Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page.
Form object − Everything enclosed in the <form>...</form> tags sets the form object.
Form object − Everything enclosed in the <form>...</form> tags sets the form object.
Form control elements − The form object contains all the elements defined for that object such as text fields, buttons, radio buttons, and checkboxes.
Form control elements − The form object contains all the elements defined for that object such as text fields, buttons, radio buttons, and checkboxes.
Here is a simple hierarchy of a few important objects −
There are several DOMs in existence. The following sections explain each of these DOMs in detail and describe how you can use them to access and modify document content.
The Legacy DOM − This is the model which was introduced in early versions of JavaScript language. It is well supported by all browsers, but allows access only to certain key portions of documents, such as forms, form elements, and images.
The Legacy DOM − This is the model which was introduced in early versions of JavaScript language. It is well supported by all browsers, but allows access only to certain key portions of documents, such as forms, form elements, and images.
The W3C DOM − This document object model allows access and modification of all document content and is standardized by the World Wide Web Consortium (W3C). This model is supported by almost all the modern browsers.
The W3C DOM − This document object model allows access and modification of all document content and is standardized by the World Wide Web Consortium (W3C). This model is supported by almost all the modern browsers.
The IE4 DOM − This document object model was introduced in Version 4 of Microsoft's Internet Explorer browser. IE 5 and later versions include support for most basic W3C DOM features.
The IE4 DOM − This document object model was introduced in Version 4 of Microsoft's Internet Explorer browser. IE 5 and later versions include support for most basic W3C DOM features.
If you want to write a script with the flexibility to use either W3C DOM or IE 4 DOM depending on their availability, then you can use a capability-testing approach that first checks for the existence of a method or property to determine whether the browser has the capability you desire. For example −
if (document.getElementById) {
// If the W3C method exists, use it
} else if (document.all) {
// If the all[] array exists, use it
} else {
// Otherwise use the legacy DOM
}
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c) Logical Errors.
Syntax errors, also called parsing errors, occur at compile time in traditional programming languages and at interpret time in JavaScript.
For example, the following line causes a syntax error because it is missing a closing parenthesis.
<script type = "text/javascript">
<!--
window.print(;
//-->
</script>
When a syntax error occurs in JavaScript, only the code contained within the same thread as the syntax error is affected and the rest of the code in other threads gets executed assuming nothing in them depends on the code containing the error.
Runtime errors, also called exceptions, occur during execution (after compilation/interpretation).
For example, the following line causes a runtime error because here the syntax is correct, but at runtime, it is trying to call a method that does not exist.
<script type = "text/javascript">
<!--
window.printme();
//-->
</script>
Exceptions also affect the thread in which they occur, allowing other JavaScript threads to continue normal execution.
Logic errors can be the most difficult type of errors to track down. These errors are not the result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script and you do not get the result you expected.
You cannot catch those errors, because it depends on your business requirement what type of logic you want to put in your program.
The latest versions of JavaScript added exception handling capabilities. JavaScript implements the try...catch...finally construct as well as the throw operator to handle exceptions.
You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors.
Here is the try...catch...finally block syntax −
<script type = "text/javascript">
<!--
try {
// Code to run
[break;]
}
catch ( e ) {
// Code to run if an exception occurs
[break;]
}
[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
//-->
</script>
The try block must be followed by either exactly one catch block or one finally block (or one of both). When an exception occurs in the try block, the exception is placed in e and the catch block is executed. The optional finally block executes unconditionally after try/catch.
Here is an example where we are trying to call a non-existing function which in turn is raising an exception. Let us see how it behaves without try...catch−
<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
alert("Value of variable a is : " + a );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
Click the following to see the result:
Now let us try to catch this exception using try...catch and display a user-friendly message. You can also suppress this message, if you want to hide this error from a user.
<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + e.description );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
Click the following to see the result:
You can use finally block which will always execute unconditionally after the try/catch. Here is an example.
<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + e.description );
}
finally {
alert("Finally block will always execute!" );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
Click the following to see the result:
You can use throw statement to raise your built-in exceptions or your customized exceptions. Later these exceptions can be captured and you can take an appropriate action.
The following example demonstrates how to use a throw statement.
<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
var b = 0;
try {
if ( b == 0 ) {
throw( "Divide by zero error." );
} else {
var c = a / b;
}
}
catch ( e ) {
alert("Error: " + e );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
Click the following to see the result:
You can raise an exception in one function using a string, integer, Boolean, or an object and then you can capture that exception either in the same function as we did above, or in another function using a try...catch block.
The onerror event handler was the first feature to facilitate error handling in JavaScript. The error event is fired on the window object whenever an exception occurs on the page.
<html>
<head>
<script type = "text/javascript">
<!--
window.onerror = function () {
alert("An error occurred.");
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
Click the following to see the result:
The onerror event handler provides three pieces of information to identify the exact nature of the error −
Error message − The same message that the browser would display for the given error
Error message − The same message that the browser would display for the given error
URL − The file in which the error occurred
URL − The file in which the error occurred
Line number− The line number in the given URL that caused the error
Line number− The line number in the given URL that caused the error
Here is the example to show how to extract this information.
<html>
<head>
<script type = "text/javascript">
<!--
window.onerror = function (msg, url, line) {
alert("Message : " + msg );
alert("url : " + url );
alert("Line number : " + line );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
Click the following to see the result:
You can display extracted information in whatever way you think it is better.
You can use an onerror method, as shown below, to display an error message in case there is any problem in loading an image.
<img src="myimage.gif" onerror="alert('An error occurred loading the image.')" />
You can use onerror with many HTML tags to display appropriate messages in case of errors.
Form validation normally used to occur at the server, after the client had entered all the necessary data and then pressed the Submit button. If the data entered by a client was incorrect or was simply missing, the server would have to send all the data back to the client and request that the form be resubmitted with correct information. This was really a lengthy process which used to put a lot of burden on the server.
JavaScript provides a way to validate form's data on the client's computer before sending it to the web server. Form validation generally performs two functions.
Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data.
Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data.
Data Format Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test correctness of data.
Data Format Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test correctness of data.
We will take an example to understand the process of validation. Here is a simple form in html format.
<html>
<head>
<title>Form Validation</title>
<script type = "text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action = "/cgi-bin/test.cgi" name = "myForm" onsubmit = "return(validate());">
<table cellspacing = "2" cellpadding = "2" border = "1">
<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr>
<tr>
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td>
</tr>
<tr>
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>
<tr>
<td align = "right">Country</td>
<td>
<select name = "Country">
<option value = "-1" selected>[choose yours]</option>
<option value = "1">USA</option>
<option value = "2">UK</option>
<option value = "3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
First let us see how to do a basic form validation. In the above form, we are calling validate() to validate data when onsubmit event is occurring. The following code shows the implementation of this validate() function.
<script type = "text/javascript">
<!--
// Form validation code will come here.
function validate() {
if( document.myForm.Name.value == "" ) {
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" ) {
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" || isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 ) {
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" ) {
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>
Now we will see how we can validate our entered form data before submitting it to the web server.
The following example shows how to validate an entered email address. An email address must contain at least a ‘@’ sign and a dot (.). Also, the ‘@’ must not be the first character of the email address, and the last dot must at least be one character after the ‘@’ sign.
Try the following code for email validation.
<script type = "text/javascript">
<!--
function validateEmail() {
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 )) {
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
//-->
</script>
You can use JavaScript to create a complex animation having, but not limited to, the following elements −
Fireworks
Fade Effect
Roll-in or Roll-out
Page-in or Page-out
Object movements
You might be interested in existing JavaScript based animation library: Script.Aculo.us.
This tutorial provides a basic understanding of how to use JavaScript to create an animation.
JavaScript can be used to move a number of DOM elements (<img />, <div> or any other HTML element) around the page according to some sort of pattern determined by a logical equation or function.
JavaScript provides the following two functions to be frequently used in animation programs.
setTimeout( function, duration) − This function calls function after duration milliseconds from now.
setTimeout( function, duration) − This function calls function after duration milliseconds from now.
setInterval(function, duration) − This function calls function after every duration milliseconds.
setInterval(function, duration) − This function calls function after every duration milliseconds.
clearTimeout(setTimeout_variable) − This function calls clears any timer set by the setTimeout() functions.
clearTimeout(setTimeout_variable) − This function calls clears any timer set by the setTimeout() functions.
JavaScript can also set a number of attributes of a DOM object including its position on the screen. You can set top and left attribute of an object to position it anywhere on the screen. Here is its syntax.
// Set distance from left edge of the screen.
object.style.left = distance in pixels or points;
or
// Set distance from top edge of the screen.
object.style.top = distance in pixels or points;
So let's implement one simple animation using DOM object properties and JavaScript functions as follows. The following list contains different DOM methods.
We are using the JavaScript function getElementById() to get a DOM object and then assigning it to a global variable imgObj.
We are using the JavaScript function getElementById() to get a DOM object and then assigning it to a global variable imgObj.
We have defined an initialization function init() to initialize imgObj where we have set its position and left attributes.
We have defined an initialization function init() to initialize imgObj where we have set its position and left attributes.
We are calling initialization function at the time of window load.
We are calling initialization function at the time of window load.
Finally, we are calling moveRight() function to increase the left distance by 10 pixels. You could also set it to a negative value to move it to the left side.
Finally, we are calling moveRight() function to increase the left distance by 10 pixels. You could also set it to a negative value to move it to the left side.
Try the following example.
<html>
<head>
<title>JavaScript Animation</title>
<script type = "text/javascript">
<!--
var imgObj = null;
function init() {
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
}
function moveRight() {
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
}
window.onload = init;
//-->
</script>
</head>
<body>
<form>
<img id = "myImage" src = "/images/html.gif" />
<p>Click button below to move the image to right</p>
<input type = "button" value = "Click Me" onclick = "moveRight();" />
</form>
</body>
</html>
Click button below to move the image to right
In the above example, we saw how an image moves to right with every click. We can automate this process by using the JavaScript function setTimeout() as follows −
Here we have added more methods. So let's see what is new here −
The moveRight() function is calling setTimeout() function to set the position of imgObj.
The moveRight() function is calling setTimeout() function to set the position of imgObj.
We have added a new function stop() to clear the timer set by setTimeout() function and to set the object at its initial position.
We have added a new function stop() to clear the timer set by setTimeout() function and to set the object at its initial position.
Try the following example code.
<html>
<head>
<title>JavaScript Animation</title>
<script type = "text/javascript">
<!--
var imgObj = null;
var animate ;
function init() {
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
}
function moveRight() {
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
animate = setTimeout(moveRight,20); // call moveRight in 20msec
}
function stop() {
clearTimeout(animate);
imgObj.style.left = '0px';
}
window.onload = init;
//-->
</script>
</head>
<body>
<form>
<img id = "myImage" src = "/images/html.gif" />
<p>Click the buttons below to handle animation</p>
<input type = "button" value = "Start" onclick = "moveRight();" />
<input type = "button" value = "Stop" onclick = "stop();" />
</form>
</body>
</html>
Click the buttons below to handle animation
Here is a simple example showing image rollover with a mouse event.
Let's see what we are using in the following example −
At the time of loading this page, the ‘if’ statement checks for the existence of the image object. If the image object is unavailable, this block will not be executed.
At the time of loading this page, the ‘if’ statement checks for the existence of the image object. If the image object is unavailable, this block will not be executed.
The Image() constructor creates and preloads a new image object called image1.
The Image() constructor creates and preloads a new image object called image1.
The src property is assigned the name of the external image file called /images/html.gif.
The src property is assigned the name of the external image file called /images/html.gif.
Similarly, we have created image2 object and assigned /images/http.gif in this object.
Similarly, we have created image2 object and assigned /images/http.gif in this object.
The # (hash mark) disables the link so that the browser does not try to go to a URL when clicked. This link is an image.
The # (hash mark) disables the link so that the browser does not try to go to a URL when clicked. This link is an image.
The onMouseOver event handler is triggered when the user's mouse moves onto the link, and the onMouseOut event handler is triggered when the user's mouse moves away from the link (image).
The onMouseOver event handler is triggered when the user's mouse moves onto the link, and the onMouseOut event handler is triggered when the user's mouse moves away from the link (image).
When the mouse moves over the image, the HTTP image changes from the first image to the second one. When the mouse is moved away from the image, the original image is displayed.
When the mouse moves over the image, the HTTP image changes from the first image to the second one. When the mouse is moved away from the image, the original image is displayed.
When the mouse is moved away from the link, the initial image html.gif will reappear on the screen.
When the mouse is moved away from the link, the initial image html.gif will reappear on the screen.
<html>
<head>
<title>Rollover with a Mouse Events</title>
<script type = "text/javascript">
<!--
if(document.images) {
var image1 = new Image(); // Preload an image
image1.src = "/images/html.gif";
var image2 = new Image(); // Preload second image
image2.src = "/images/http.gif";
}
//-->
</script>
</head>
<body>
<p>Move your mouse over the image to see the result</p>
<a href = "#" onMouseOver = "document.myImage.src = image2.src;"
onMouseOut = "document.myImage.src = image1.src;">
<img name = "myImage" src = "/images/html.gif" />
</a>
</body>
</html>
Move your mouse over the image to see the result
The JavaScript navigator object includes a child object called plugins. This object is an array, with one entry for each plug-in installed on the browser. The navigator.plugins object is supported only by Netscape, Firefox, and Mozilla only.
Here is an example that shows how to list down all the plug-on installed in your browser −
<html>
<head>
<title>List of Plug-Ins</title>
</head>
<body>
<table border = "1">
<tr>
<th>Plug-in Name</th>
<th>Filename</th>
<th>Description</th>
</tr>
<script language = "JavaScript" type = "text/javascript">
for (i = 0; i<navigator.plugins.length; i++) {
document.write("<tr><td>");
document.write(navigator.plugins[i].name);
document.write("</td><td>");
document.write(navigator.plugins[i].filename);
document.write("</td><td>");
document.write(navigator.plugins[i].description);
document.write("</td></tr>");
}
</script>
</table>
</body>
</html>
Each plug-in has an entry in the array. Each entry has the following properties −
name − is the name of the plug-in.
name − is the name of the plug-in.
filename − is the executable file that was loaded to install the plug-in.
filename − is the executable file that was loaded to install the plug-in.
description − is a description of the plug-in, supplied by the developer.
description − is a description of the plug-in, supplied by the developer.
mimeTypes − is an array with one entry for each MIME type supported by the plug-in.
mimeTypes − is an array with one entry for each MIME type supported by the plug-in.
You can use these properties in a script to find out the installed plug-ins, and then using JavaScript, you can play appropriate multimedia file. Take a look at the following example.
<html>
<head>
<title>Using Plug-Ins</title>
</head>
<body>
<script language = "JavaScript" type = "text/javascript">
media = navigator.mimeTypes["video/quicktime"];
if (media) {
document.write("<embed src = 'quick.mov' height = 100 width = 100>");
} else {
document.write("<img src = 'quick.gif' height = 100 width = 100>");
}
</script>
</body>
</html>
NOTE − Here we are using HTML <embed> tag to embed a multimedia file.
Let us take one real example which works in almost all the browsers −
<html>
<head>
<title>Using Embeded Object</title>
<script type = "text/javascript">
<!--
function play() {
if (!document.demo.IsPlaying()) {
document.demo.Play();
}
}
function stop() {
if (document.demo.IsPlaying()) {
document.demo.StopPlay();
}
}
function rewind() {
if (document.demo.IsPlaying()) {
document.demo.StopPlay();
}
document.demo.Rewind();
}
//-->
</script>
</head>
<body>
<embed id = "demo" name = "demo"
src = "http://www.amrood.com/games/kumite.swf"
width = "318" height = "300" play = "false" loop = "false"
pluginspage = "http://www.macromedia.com/go/getflashplayer"
swliveconnect = "true">
<form name = "form" id = "form" action = "#" method = "get">
<input type = "button" value = "Start" onclick = "play();" />
<input type = "button" value = "Stop" onclick = "stop();" />
<input type = "button" value = "Rewind" onclick = "rewind();" />
</form>
</body>
</html>
If you are using Mozilla, Firefox or Netscape, then
Every now and then, developers commit mistakes while coding. A mistake in a program or a script is referred to as a bug.
The process of finding and fixing bugs is called debugging and is a normal part of the development process. This section covers tools and techniques that can help you with debugging tasks..
The most basic way to track down errors is by turning on error information in your browser. By default, Internet Explorer shows an error icon in the status bar when an error occurs on the page.
Double-clicking this icon takes you to a dialog box showing information about the specific error that occurred.
Since this icon is easy to overlook, Internet Explorer gives you the option to automatically show the Error dialog box whenever an error occurs.
To enable this option, select Tools → Internet Options → Advanced tab. and then finally check the "Display a Notification About Every Script Error" box option as shown below −
Other browsers like Firefox, Netscape, and Mozilla send error messages to a special window called the JavaScript Console or Error Consol. To view the console, select Tools → Error Consol or Web Development.
Unfortunately, since these browsers give no visual indication when an error occurs, you must keep the Console open and watch for errors as your script executes.
Error notifications that show up on Console or through Internet Explorer dialog boxes are the result of both syntax and runtime errors. These error notification include the line number at which the error occurred.
If you are using Firefox, then you can click on the error available in the error console to go to the exact line in the script having error.
There are various ways to debug your JavaScript −
One way to check your JavaScript code for strange bugs is to run it through a program that checks it to make sure it is valid and that it follows the official syntax rules of the language. These programs are called validating parsers or just validators for short, and often come with commercial HTML and JavaScript editors.
The most convenient validator for JavaScript is Douglas Crockford's JavaScript Lint, which is available for free at Douglas Crockford's JavaScript Lint.
Simply visit that web page, paste your JavaScript (Only JavaScript) code into the text area provided, and click the jslint button. This program will parse through your JavaScript code, ensuring that all the variable and function definitions follow the correct syntax. It will also check JavaScript statements, such as if and while, to ensure they too follow the correct format
You can use the alert() or document.write() methods in your program to debug your code. For example, you might write something as follows −
var debugging = true;
var whichImage = "widget";
if( debugging )
alert( "Calls swapImage() with argument: " + whichImage );
var swapStatus = swapImage( whichImage );
if( debugging )
alert( "Exits swapImage() with swapStatus=" + swapStatus );
By examining the content and order of the alert() as they appear, you can examine the health of your program very easily.
A debugger is an application that places all aspects of script execution under the control of the programmer. Debuggers provide fine-grained control over the state of the script through an interface that allows you to examine and set values as well as control the flow of execution.
Once a script has been loaded into a debugger, it can be run one line at a time or instructed to halt at certain breakpoints. Once execution is halted, the programmer can examine the state of the script and its variables in order to determine if something is amiss. You can also watch variables for changes in their values.
The latest version of the Mozilla JavaScript Debugger (code-named Venkman) for both Mozilla and Netscape browsers can be downloaded at http://www.hacksrus.com/~ginda/venkman
You can keep the following tips in mind to reduce the number of errors in your scripts and simplify the debugging process −
Use plenty of comments. Comments enable you to explain why you wrote the script the way you did and to explain particularly difficult sections of code.
Use plenty of comments. Comments enable you to explain why you wrote the script the way you did and to explain particularly difficult sections of code.
Always use indentation to make your code easy to read. Indenting statements also makes it easier for you to match up beginning and ending tags, curly braces, and other HTML and script elements.
Always use indentation to make your code easy to read. Indenting statements also makes it easier for you to match up beginning and ending tags, curly braces, and other HTML and script elements.
Write modular code. Whenever possible, group your statements into functions. Functions let you group related statements, and test and reuse portions of code with minimal effort.
Write modular code. Whenever possible, group your statements into functions. Functions let you group related statements, and test and reuse portions of code with minimal effort.
Be consistent in the way you name your variables and functions. Try using names that are long enough to be meaningful and that describe the contents of the variable or the purpose of the function.
Be consistent in the way you name your variables and functions. Try using names that are long enough to be meaningful and that describe the contents of the variable or the purpose of the function.
Use consistent syntax when naming variables and functions. In other words, keep them all lowercase or all uppercase; if you prefer Camel-Back notation, use it consistently.
Use consistent syntax when naming variables and functions. In other words, keep them all lowercase or all uppercase; if you prefer Camel-Back notation, use it consistently.
Test long scripts in a modular fashion. In other words, do not try to write the entire script before testing any portion of it. Write a piece and get it to work before adding the next portion of code.
Test long scripts in a modular fashion. In other words, do not try to write the entire script before testing any portion of it. Write a piece and get it to work before adding the next portion of code.
Use descriptive variable and function names and avoid using single-character names.
Use descriptive variable and function names and avoid using single-character names.
Watch your quotation marks. Remember that quotation marks are used in pairs around strings and that both quotation marks must be of the same style (either single or double).
Watch your quotation marks. Remember that quotation marks are used in pairs around strings and that both quotation marks must be of the same style (either single or double).
Watch your equal signs. You should not used a single = for comparison purpose.
Watch your equal signs. You should not used a single = for comparison purpose.
Declare variables explicitly using the var keyword.
Declare variables explicitly using the var keyword.
You can use JavaScript to create client-side image map. Client-side image maps are enabled by the usemap attribute for the <img /> tag and defined by special <map> and <area> extension tags.
The image that is going to form the map is inserted into the page using the <img /> element as normal, except that it carries an extra attribute called usemap. The value of the usemap attribute is the value of the name attribute on the <map> element, which you are about to meet, preceded by a pound or hash sign.
The <map> element actually creates the map for the image and usually follows directly after the <img /> element. It acts as a container for the <area /> elements that actually define the clickable hotspots. The <map> element carries only one attribute, the name attribute, which is the name that identifies the map. This is how the <img /> element knows which <map> element to use.
The <area> element specifies the shape and the coordinates that define the boundaries of each clickable hotspot.
The following code combines imagemaps and JavaScript to produce a message in a text box when the mouse is moved over different parts of an image.
<html>
<head>
<title>Using JavaScript Image Map</title>
<script type = "text/javascript">
<!--
function showTutorial(name) {
document.myform.stage.value = name
}
//-->
</script>
</head>
<body>
<form name = "myform">
<input type = "text" name = "stage" size = "20" />
</form>
<!-- Create Mappings -->
<img src = "/images/usemap.gif" alt = "HTML Map" border = "0" usemap = "#tutorials"/>
<map name = "tutorials">
<area shape="poly"
coords = "74,0,113,29,98,72,52,72,38,27"
href = "/perl/index.htm" alt = "Perl Tutorial"
target = "_self"
onMouseOver = "showTutorial('perl')"
onMouseOut = "showTutorial('')"/>
<area shape = "rect"
coords = "22,83,126,125"
href = "/html/index.htm" alt = "HTML Tutorial"
target = "_self"
onMouseOver = "showTutorial('html')"
onMouseOut = "showTutorial('')"/>
<area shape = "circle"
coords = "73,168,32"
href = "/php/index.htm" alt = "PHP Tutorial"
target = "_self"
onMouseOver = "showTutorial('php')"
onMouseOut = "showTutorial('')"/>
</map>
</body>
</html>
You can feel the map concept by placing the mouse cursor on the image object.
It is important to understand the differences between different browsers in order to handle each in the way it is expected. So it is important to know which browser your web page is running in.
To get information about the browser your webpage is currently running in, use the built-in navigator object.
There are several Navigator related properties that you can use in your Web page. The following is a list of the names and descriptions of each.
appCodeName
This property is a string that contains the code name of the browser, Netscape for Netscape and Microsoft Internet Explorer for Internet Explorer.
appVersion
This property is a string that contains the version of the browser as well as other useful information such as its language and compatibility.
language
This property contains the two-letter abbreviation for the language that is used by the browser. Netscape only.
mimTypes[]
This property is an array that contains all MIME types supported by the client. Netscape only.
platform[]
This property is a string that contains the platform for which the browser was compiled."Win32" for 32-bit Windows operating systems
plugins[]
This property is an array containing all the plug-ins that have been installed on the client. Netscape only.
userAgent[]
This property is a string that contains the code name and version of the browser. This value is sent to the originating server to identify the client.
There are several Navigator-specific methods. Here is a list of their names and descriptions.
javaEnabled()
This method determines if JavaScript is enabled in the client. If JavaScript is enabled, this method returns true; otherwise, it returns false.
plugings.refresh
This method makes newly installed plug-ins available and populates the plugins array with all new plug-in names. Netscape only.
preference(name,value)
This method allows a signed script to get and set some Netscape preferences. If the second parameter is omitted, this method will return the value of the specified preference; otherwise, it sets the value. Netscape only.
taintEnabled()
This method returns true if data tainting is enabled; false otherwise.
There is a simple JavaScript which can be used to find out the name of a browser and then accordingly an HTML page can be served to the user.
<html>
<head>
<title>Browser Detection Example</title>
</head>
<body>
<script type = "text/javascript">
<!--
var userAgent = navigator.userAgent;
var opera = (userAgent.indexOf('Opera') != -1);
var ie = (userAgent.indexOf('MSIE') != -1);
var gecko = (userAgent.indexOf('Gecko') != -1);
var netscape = (userAgent.indexOf('Mozilla') != -1);
var version = navigator.appVersion;
if (opera) {
document.write("Opera based browser");
// Keep your opera specific URL here.
} else if (gecko) {
document.write("Mozilla based browser");
// Keep your gecko specific URL here.
} else if (ie) {
document.write("IE based browser");
// Keep your IE specific URL here.
} else if (netscape) {
document.write("Netscape based browser");
// Keep your Netscape specific URL here.
} else {
document.write("Unknown browser");
}
// You can include version to along with any above condition.
document.write("<br /> Browser version info : " + version );
//-->
</script>
</body>
</html>
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2760,
"s": 2466,
"text": "JavaScript is a dynamic computer programming language. It is lightweight and most commonly used as a part of web pages, whose implementations allow client-side script to interact with the user and make dynamic pages. It is an interpreted programming language with object-oriented capabilities."
},
{
"code": null,
"e": 3109,
"s": 2760,
"text": "JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because of the excitement being generated by Java. JavaScript made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers."
},
{
"code": null,
"e": 3196,
"s": 3109,
"text": "The ECMA-262 Specification defined a standard version of the core JavaScript language."
},
{
"code": null,
"e": 3259,
"s": 3196,
"text": "JavaScript is a lightweight, interpreted programming language."
},
{
"code": null,
"e": 3311,
"s": 3259,
"text": "Designed for creating network-centric applications."
},
{
"code": null,
"e": 3354,
"s": 3311,
"text": "Complementary to and integrated with Java."
},
{
"code": null,
"e": 3397,
"s": 3354,
"text": "Complementary to and integrated with HTML."
},
{
"code": null,
"e": 3421,
"s": 3397,
"text": "Open and cross-platform"
},
{
"code": null,
"e": 3599,
"s": 3421,
"text": "Client-side JavaScript is the most common form of the language. The script should be included in or referenced by an HTML document for the code to be interpreted by the browser."
},
{
"code": null,
"e": 3763,
"s": 3599,
"text": "It means that a web page need not be a static HTML, but can include programs that interact with the user, control the browser, and dynamically create HTML content."
},
{
"code": null,
"e": 3978,
"s": 3763,
"text": "The JavaScript client-side mechanism provides many advantages over traditional CGI server-side scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail address in a form field."
},
{
"code": null,
"e": 4124,
"s": 3978,
"text": "The JavaScript code is executed when the user submits the form, and only if all the entries are valid, they would be submitted to the Web Server."
},
{
"code": null,
"e": 4285,
"s": 4124,
"text": "JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other actions that the user initiates explicitly or implicitly."
},
{
"code": null,
"e": 4322,
"s": 4285,
"text": "The merits of using JavaScript are −"
},
{
"code": null,
"e": 4484,
"s": 4322,
"text": "Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server."
},
{
"code": null,
"e": 4646,
"s": 4484,
"text": "Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server."
},
{
"code": null,
"e": 4775,
"s": 4646,
"text": "Immediate feedback to the visitors − They don't have to wait for a page reload to see if they have forgotten to enter something."
},
{
"code": null,
"e": 4904,
"s": 4775,
"text": "Immediate feedback to the visitors − They don't have to wait for a page reload to see if they have forgotten to enter something."
},
{
"code": null,
"e": 5047,
"s": 4904,
"text": "Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard."
},
{
"code": null,
"e": 5190,
"s": 5047,
"text": "Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard."
},
{
"code": null,
"e": 5343,
"s": 5190,
"text": "Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors."
},
{
"code": null,
"e": 5496,
"s": 5343,
"text": "Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors."
},
{
"code": null,
"e": 5607,
"s": 5496,
"text": "We cannot treat JavaScript as a full-fledged programming language. It lacks the following important features −"
},
{
"code": null,
"e": 5718,
"s": 5607,
"text": "Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason."
},
{
"code": null,
"e": 5829,
"s": 5718,
"text": "Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason."
},
{
"code": null,
"e": 5927,
"s": 5829,
"text": "JavaScript cannot be used for networking applications because there is no such support available."
},
{
"code": null,
"e": 6025,
"s": 5927,
"text": "JavaScript cannot be used for networking applications because there is no such support available."
},
{
"code": null,
"e": 6101,
"s": 6025,
"text": "JavaScript doesn't have any multi-threading or multiprocessor capabilities."
},
{
"code": null,
"e": 6177,
"s": 6101,
"text": "JavaScript doesn't have any multi-threading or multiprocessor capabilities."
},
{
"code": null,
"e": 6324,
"s": 6177,
"text": "Once again, JavaScript is a lightweight, interpreted programming language that allows you to build interactivity into otherwise static HTML pages."
},
{
"code": null,
"e": 6587,
"s": 6324,
"text": "One of major strengths of JavaScript is that it does not require expensive development tools. You can start with a simple text editor such as Notepad. Since it is an interpreted language inside the context of a web browser, you don't even need to buy a compiler."
},
{
"code": null,
"e": 6714,
"s": 6587,
"text": "To make our life simpler, various vendors have come up with very nice JavaScript editing tools. Some of them are listed here −"
},
{
"code": null,
"e": 6924,
"s": 6714,
"text": "Microsoft FrontPage − Microsoft has developed a popular HTML editor called FrontPage. FrontPage also provides web developers with a number of JavaScript tools to assist in the creation of interactive websites."
},
{
"code": null,
"e": 7134,
"s": 6924,
"text": "Microsoft FrontPage − Microsoft has developed a popular HTML editor called FrontPage. FrontPage also provides web developers with a number of JavaScript tools to assist in the creation of interactive websites."
},
{
"code": null,
"e": 7419,
"s": 7134,
"text": "Macromedia Dreamweaver MX − Macromedia Dreamweaver MX is a very popular HTML and JavaScript editor in the professional web development crowd. It provides several handy prebuilt JavaScript components, integrates well with databases, and conforms to new standards such as XHTML and XML."
},
{
"code": null,
"e": 7704,
"s": 7419,
"text": "Macromedia Dreamweaver MX − Macromedia Dreamweaver MX is a very popular HTML and JavaScript editor in the professional web development crowd. It provides several handy prebuilt JavaScript components, integrates well with databases, and conforms to new standards such as XHTML and XML."
},
{
"code": null,
"e": 7856,
"s": 7704,
"text": "Macromedia HomeSite 5 − HomeSite 5 is a well-liked HTML and JavaScript editor from Macromedia that can be used to manage personal websites effectively."
},
{
"code": null,
"e": 8008,
"s": 7856,
"text": "Macromedia HomeSite 5 − HomeSite 5 is a well-liked HTML and JavaScript editor from Macromedia that can be used to manage personal websites effectively."
},
{
"code": null,
"e": 8222,
"s": 8008,
"text": "The ECMAScript Edition 5 standard will be the first update to be released in over four years. JavaScript 2.0 conforms to Edition 5 of the ECMAScript standard, and the difference between the two is extremely minor."
},
{
"code": null,
"e": 8322,
"s": 8222,
"text": "The specification for JavaScript 2.0 can be found on the following site: http://www.ecmascript.org/"
},
{
"code": null,
"e": 8503,
"s": 8322,
"text": "Today, Netscape's JavaScript and Microsoft's JScript conform to the ECMAScript standard, although both the languages still support the features that are not a part of the standard."
},
{
"code": null,
"e": 8635,
"s": 8503,
"text": "JavaScript can be implemented using JavaScript statements that are placed within the <script>... </script> HTML tags in a web page."
},
{
"code": null,
"e": 8806,
"s": 8635,
"text": "You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is normally recommended that you should keep it within the <head> tags."
},
{
"code": null,
"e": 8976,
"s": 8806,
"text": "The <script> tag alerts the browser program to start interpreting all the text between these tags as a script. A simple syntax of your JavaScript will appear as follows."
},
{
"code": null,
"e": 9019,
"s": 8976,
"text": "<script ...>\n JavaScript code\n</script>\n"
},
{
"code": null,
"e": 9067,
"s": 9019,
"text": "The script tag takes two important attributes −"
},
{
"code": null,
"e": 9286,
"s": 9067,
"text": "Language − This attribute specifies what scripting language you are using. Typically, its value will be javascript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute."
},
{
"code": null,
"e": 9505,
"s": 9286,
"text": "Language − This attribute specifies what scripting language you are using. Typically, its value will be javascript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute."
},
{
"code": null,
"e": 9646,
"s": 9505,
"text": "Type − This attribute is what is now recommended to indicate the scripting language in use and its value should be set to \"text/javascript\"."
},
{
"code": null,
"e": 9787,
"s": 9646,
"text": "Type − This attribute is what is now recommended to indicate the scripting language in use and its value should be set to \"text/javascript\"."
},
{
"code": null,
"e": 9831,
"s": 9787,
"text": "So your JavaScript segment will look like −"
},
{
"code": null,
"e": 9919,
"s": 9831,
"text": "<script language = \"javascript\" type = \"text/javascript\">\n JavaScript code\n</script>\n"
},
{
"code": null,
"e": 10392,
"s": 9919,
"text": "Let us take a sample example to print out \"Hello World\". We added an optional HTML comment that surrounds our JavaScript code. This is to save our code from a browser that does not support JavaScript. The comment ends with a \"//-->\". Here \"//\" signifies a comment in JavaScript, so we add that to prevent a browser from reading the end of the HTML comment as a piece of JavaScript code. Next, we call a function document.write which writes a string into our HTML document."
},
{
"code": null,
"e": 10483,
"s": 10392,
"text": "This function can be used to write text, HTML, or both. Take a look at the following code."
},
{
"code": null,
"e": 10680,
"s": 10483,
"text": "<html>\n <body> \n <script language = \"javascript\" type = \"text/javascript\">\n <!--\n document.write(\"Hello World!\")\n //-->\n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 10726,
"s": 10680,
"text": "This code will produce the following result −"
},
{
"code": null,
"e": 10740,
"s": 10726,
"text": "Hello World!\n"
},
{
"code": null,
"e": 11014,
"s": 10740,
"text": "JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. You can use spaces, tabs, and newlines freely in your program and you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand."
},
{
"code": null,
"e": 11315,
"s": 11014,
"text": "Simple statements in JavaScript are generally followed by a semicolon character, just as they are in C, C++, and Java. JavaScript, however, allows you to omit this semicolon if each of your statements are placed on a separate line. For example, the following code could be written without semicolons."
},
{
"code": null,
"e": 11432,
"s": 11315,
"text": "<script language = \"javascript\" type = \"text/javascript\">\n <!--\n var1 = 10\n var2 = 20\n //-->\n</script>"
},
{
"code": null,
"e": 11506,
"s": 11432,
"text": "But when formatted in a single line as follows, you must use semicolons −"
},
{
"code": null,
"e": 11619,
"s": 11506,
"text": "<script language = \"javascript\" type = \"text/javascript\">\n <!--\n var1 = 10; var2 = 20;\n //-->\n</script>"
},
{
"code": null,
"e": 11679,
"s": 11619,
"text": "Note − It is a good programming practice to use semicolons."
},
{
"code": null,
"e": 11878,
"s": 11679,
"text": "JavaScript is a case-sensitive language. This means that the language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters."
},
{
"code": null,
"e": 11957,
"s": 11878,
"text": "So the identifiers Time and TIME will convey different meanings in JavaScript."
},
{
"code": null,
"e": 12042,
"s": 11957,
"text": "NOTE − Care should be taken while writing variable and function names in JavaScript."
},
{
"code": null,
"e": 12106,
"s": 12042,
"text": "JavaScript supports both C-style and C++-style comments, Thus −"
},
{
"code": null,
"e": 12204,
"s": 12106,
"text": "Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript."
},
{
"code": null,
"e": 12302,
"s": 12204,
"text": "Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript."
},
{
"code": null,
"e": 12399,
"s": 12302,
"text": "Any text between the characters /* and */ is treated as a comment. This may span multiple lines."
},
{
"code": null,
"e": 12496,
"s": 12399,
"text": "Any text between the characters /* and */ is treated as a comment. This may span multiple lines."
},
{
"code": null,
"e": 12644,
"s": 12496,
"text": "JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a single-line comment, just as it does the // comment."
},
{
"code": null,
"e": 12792,
"s": 12644,
"text": "JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a single-line comment, just as it does the // comment."
},
{
"code": null,
"e": 12897,
"s": 12792,
"text": "The HTML comment closing sequence --> is not recognized by JavaScript so it should be written as //-->."
},
{
"code": null,
"e": 13002,
"s": 12897,
"text": "The HTML comment closing sequence --> is not recognized by JavaScript so it should be written as //-->."
},
{
"code": null,
"e": 13065,
"s": 13002,
"text": "The following example shows how to use comments in JavaScript."
},
{
"code": null,
"e": 13340,
"s": 13065,
"text": "<script language = \"javascript\" type = \"text/javascript\">\n <!--\n // This is a comment. It is similar to comments in C++\n \n /*\n * This is a multi-line comment in JavaScript\n * It is very similar to comments in C Programming\n */\n //-->\n</script>"
},
{
"code": null,
"e": 13622,
"s": 13340,
"text": "All the modern browsers come with built-in support for JavaScript. Frequently, you may need to enable or disable this support manually. This chapter explains the procedure of enabling and disabling JavaScript support in your browsers: Internet Explorer, Firefox, chrome, and Opera."
},
{
"code": null,
"e": 13706,
"s": 13622,
"text": "Here are simple steps to turn on or turn off JavaScript in your Internet Explorer −"
},
{
"code": null,
"e": 13753,
"s": 13706,
"text": "Follow Tools → Internet Options from the menu."
},
{
"code": null,
"e": 13800,
"s": 13753,
"text": "Follow Tools → Internet Options from the menu."
},
{
"code": null,
"e": 13841,
"s": 13800,
"text": "Select Security tab from the dialog box."
},
{
"code": null,
"e": 13882,
"s": 13841,
"text": "Select Security tab from the dialog box."
},
{
"code": null,
"e": 13913,
"s": 13882,
"text": "Click the Custom Level button."
},
{
"code": null,
"e": 13944,
"s": 13913,
"text": "Click the Custom Level button."
},
{
"code": null,
"e": 13988,
"s": 13944,
"text": "Scroll down till you find Scripting option."
},
{
"code": null,
"e": 14032,
"s": 13988,
"text": "Scroll down till you find Scripting option."
},
{
"code": null,
"e": 14083,
"s": 14032,
"text": "Select Enable radio button under Active scripting."
},
{
"code": null,
"e": 14134,
"s": 14083,
"text": "Select Enable radio button under Active scripting."
},
{
"code": null,
"e": 14164,
"s": 14134,
"text": "Finally click OK and come out"
},
{
"code": null,
"e": 14194,
"s": 14164,
"text": "Finally click OK and come out"
},
{
"code": null,
"e": 14315,
"s": 14194,
"text": "To disable JavaScript support in your Internet Explorer, you need to select Disable radio button under Active scripting."
},
{
"code": null,
"e": 14381,
"s": 14315,
"text": "Here are the steps to turn on or turn off JavaScript in Firefox −"
},
{
"code": null,
"e": 14437,
"s": 14381,
"text": "Open a new tab → type about: config in the address bar."
},
{
"code": null,
"e": 14493,
"s": 14437,
"text": "Open a new tab → type about: config in the address bar."
},
{
"code": null,
"e": 14567,
"s": 14493,
"text": "Then you will find the warning dialog. Select I’ll be careful, I promise!"
},
{
"code": null,
"e": 14641,
"s": 14567,
"text": "Then you will find the warning dialog. Select I’ll be careful, I promise!"
},
{
"code": null,
"e": 14706,
"s": 14641,
"text": "Then you will find the list of configure options in the browser."
},
{
"code": null,
"e": 14771,
"s": 14706,
"text": "Then you will find the list of configure options in the browser."
},
{
"code": null,
"e": 14815,
"s": 14771,
"text": "In the search bar, type javascript.enabled."
},
{
"code": null,
"e": 14859,
"s": 14815,
"text": "In the search bar, type javascript.enabled."
},
{
"code": null,
"e": 14985,
"s": 14859,
"text": "There you will find the option to enable or disable javascript by right-clicking on the value of that option → select toggle."
},
{
"code": null,
"e": 15111,
"s": 14985,
"text": "There you will find the option to enable or disable javascript by right-clicking on the value of that option → select toggle."
},
{
"code": null,
"e": 15250,
"s": 15111,
"text": "If javascript.enabled is true; it converts to false upon clicking toogle. If javascript is disabled; it gets enabled upon clicking toggle."
},
{
"code": null,
"e": 15315,
"s": 15250,
"text": "Here are the steps to turn on or turn off JavaScript in Chrome −"
},
{
"code": null,
"e": 15383,
"s": 15315,
"text": "Click the Chrome menu at the top right hand corner of your browser."
},
{
"code": null,
"e": 15451,
"s": 15383,
"text": "Click the Chrome menu at the top right hand corner of your browser."
},
{
"code": null,
"e": 15468,
"s": 15451,
"text": "Select Settings."
},
{
"code": null,
"e": 15485,
"s": 15468,
"text": "Select Settings."
},
{
"code": null,
"e": 15538,
"s": 15485,
"text": "Click Show advanced settings at the end of the page."
},
{
"code": null,
"e": 15591,
"s": 15538,
"text": "Click Show advanced settings at the end of the page."
},
{
"code": null,
"e": 15653,
"s": 15591,
"text": "Under the Privacy section, click the Content settings button."
},
{
"code": null,
"e": 15715,
"s": 15653,
"text": "Under the Privacy section, click the Content settings button."
},
{
"code": null,
"e": 15847,
"s": 15715,
"text": "In the \"Javascript\" section, select \"Do not allow any site to run JavaScript\" or \"Allow all sites to run JavaScript (recommended)\"."
},
{
"code": null,
"e": 15979,
"s": 15847,
"text": "In the \"Javascript\" section, select \"Do not allow any site to run JavaScript\" or \"Allow all sites to run JavaScript (recommended)\"."
},
{
"code": null,
"e": 16043,
"s": 15979,
"text": "Here are the steps to turn on or turn off JavaScript in Opera −"
},
{
"code": null,
"e": 16085,
"s": 16043,
"text": "Follow Tools → Preferences from the menu."
},
{
"code": null,
"e": 16127,
"s": 16085,
"text": "Follow Tools → Preferences from the menu."
},
{
"code": null,
"e": 16171,
"s": 16127,
"text": "Select Advanced option from the dialog box."
},
{
"code": null,
"e": 16215,
"s": 16171,
"text": "Select Advanced option from the dialog box."
},
{
"code": null,
"e": 16254,
"s": 16215,
"text": "Select Content from the listed items."
},
{
"code": null,
"e": 16293,
"s": 16254,
"text": "Select Content from the listed items."
},
{
"code": null,
"e": 16328,
"s": 16293,
"text": "Select Enable JavaScript checkbox."
},
{
"code": null,
"e": 16363,
"s": 16328,
"text": "Select Enable JavaScript checkbox."
},
{
"code": null,
"e": 16394,
"s": 16363,
"text": "Finally click OK and come out."
},
{
"code": null,
"e": 16425,
"s": 16394,
"text": "Finally click OK and come out."
},
{
"code": null,
"e": 16524,
"s": 16425,
"text": "To disable JavaScript support in your Opera, you should not select the Enable JavaScript checkbox."
},
{
"code": null,
"e": 16654,
"s": 16524,
"text": "If you have to do something important using JavaScript, then you can display a warning message to the user using <noscript> tags."
},
{
"code": null,
"e": 16731,
"s": 16654,
"text": "You can add a noscript block immediately after the script block as follows −"
},
{
"code": null,
"e": 17018,
"s": 16731,
"text": "<html>\n <body>\n <script language = \"javascript\" type = \"text/javascript\">\n <!--\n document.write(\"Hello World!\")\n //-->\n </script>\n \n <noscript>\n Sorry...JavaScript is needed to go ahead.\n </noscript> \n </body>\n</html>"
},
{
"code": null,
"e": 17170,
"s": 17018,
"text": "Now, if the user's browser does not support JavaScript or JavaScript is not enabled, then the message from </noscript> will be displayed on the screen."
},
{
"code": null,
"e": 17343,
"s": 17170,
"text": "There is a flexibility given to include JavaScript code anywhere in an HTML document. However the most preferred ways to include JavaScript in an HTML file are as follows −"
},
{
"code": null,
"e": 17379,
"s": 17343,
"text": "Script in <head>...</head> section."
},
{
"code": null,
"e": 17415,
"s": 17379,
"text": "Script in <head>...</head> section."
},
{
"code": null,
"e": 17451,
"s": 17415,
"text": "Script in <body>...</body> section."
},
{
"code": null,
"e": 17487,
"s": 17451,
"text": "Script in <body>...</body> section."
},
{
"code": null,
"e": 17545,
"s": 17487,
"text": "Script in <body>...</body> and <head>...</head> sections."
},
{
"code": null,
"e": 17603,
"s": 17545,
"text": "Script in <body>...</body> and <head>...</head> sections."
},
{
"code": null,
"e": 17676,
"s": 17603,
"text": "Script in an external file and then include in <head>...</head> section."
},
{
"code": null,
"e": 17749,
"s": 17676,
"text": "Script in an external file and then include in <head>...</head> section."
},
{
"code": null,
"e": 17850,
"s": 17749,
"text": "In the following section, we will see how we can place JavaScript in an HTML file in different ways."
},
{
"code": null,
"e": 17993,
"s": 17850,
"text": "If you want to have a script run on some event, such as when a user clicks somewhere, then you will place that script in the head as follows −"
},
{
"code": null,
"e": 18311,
"s": 17993,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n function sayHello() {\n alert(\"Hello World\")\n }\n //-->\n </script> \n </head>\n \n <body>\n <input type = \"button\" onclick = \"sayHello()\" value = \"Say Hello\" />\n </body> \n</html>"
},
{
"code": null,
"e": 18358,
"s": 18311,
"text": "This code will produce the following results −"
},
{
"code": null,
"e": 18384,
"s": 18358,
"text": "Click here for the result"
},
{
"code": null,
"e": 18647,
"s": 18384,
"text": "If you need a script to run as the page loads so that the script generates content in the page, then the script goes in the <body> portion of the document. In this case, you would not have any function defined using JavaScript. Take a look at the following code."
},
{
"code": null,
"e": 18878,
"s": 18647,
"text": "<html>\n <head>\n </head>\n \n <body>\n <script type = \"text/javascript\">\n <!--\n document.write(\"Hello World\")\n //-->\n </script>\n \n <p>This is web page body </p>\n </body>\n</html>"
},
{
"code": null,
"e": 18925,
"s": 18878,
"text": "This code will produce the following results −"
},
{
"code": null,
"e": 18948,
"s": 18925,
"text": "This is web page body "
},
{
"code": null,
"e": 19034,
"s": 18948,
"text": "You can put your JavaScript code in <head> and <body> section altogether as follows −"
},
{
"code": null,
"e": 19473,
"s": 19034,
"text": "<html>\n <head>\n <script type = \"text/javascript\">\n <!--\n function sayHello() {\n alert(\"Hello World\")\n }\n //-->\n </script>\n </head>\n \n <body>\n <script type = \"text/javascript\">\n <!--\n document.write(\"Hello World\")\n //-->\n </script>\n \n <input type = \"button\" onclick = \"sayHello()\" value = \"Say Hello\" />\n </body>\n</html>"
},
{
"code": null,
"e": 19519,
"s": 19473,
"text": "This code will produce the following result −"
},
{
"code": null,
"e": 19531,
"s": 19519,
"text": "Hello World"
},
{
"code": null,
"e": 19711,
"s": 19531,
"text": "As you begin to work more extensively with JavaScript, you will be likely to find that there are cases where you are reusing identical JavaScript code on multiple pages of a site."
},
{
"code": null,
"e": 19922,
"s": 19711,
"text": "You are not restricted to be maintaining identical code in multiple HTML files. The script tag provides a mechanism to allow you to store JavaScript in an external file and then include it into your HTML files."
},
{
"code": null,
"e": 20055,
"s": 19922,
"text": "Here is an example to show how you can include an external JavaScript file in your HTML code using script tag and its src attribute."
},
{
"code": null,
"e": 20200,
"s": 20055,
"text": "<html>\n <head>\n <script type = \"text/javascript\" src = \"filename.js\" ></script>\n </head>\n \n <body>\n .......\n </body>\n</html>"
},
{
"code": null,
"e": 20388,
"s": 20200,
"text": "To use JavaScript from an external file source, you need to write all your JavaScript source code in a simple text file with the extension \".js\" and then include that file as shown above."
},
{
"code": null,
"e": 20551,
"s": 20388,
"text": "For example, you can keep the following content in filename.js file and then you can use sayHello function in your HTML file after including the filename.js file."
},
{
"code": null,
"e": 20600,
"s": 20551,
"text": "function sayHello() {\n alert(\"Hello World\")\n}\n"
},
{
"code": null,
"e": 20804,
"s": 20600,
"text": "One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language."
},
{
"code": null,
"e": 20868,
"s": 20804,
"text": "JavaScript allows you to work with three primitive data types −"
},
{
"code": null,
"e": 20898,
"s": 20868,
"text": "Numbers, eg. 123, 120.50 etc."
},
{
"code": null,
"e": 20928,
"s": 20898,
"text": "Numbers, eg. 123, 120.50 etc."
},
{
"code": null,
"e": 20974,
"s": 20928,
"text": "Strings of text e.g. \"This text string\" etc."
},
{
"code": null,
"e": 21020,
"s": 20974,
"text": "Strings of text e.g. \"This text string\" etc."
},
{
"code": null,
"e": 21048,
"s": 21020,
"text": "Boolean e.g. true or false."
},
{
"code": null,
"e": 21076,
"s": 21048,
"text": "Boolean e.g. true or false."
},
{
"code": null,
"e": 21344,
"s": 21076,
"text": "JavaScript also defines two trivial data types, null and undefined, each of which defines only a single value. In addition to these primitive data types, JavaScript supports a composite data type known as object. We will cover objects in detail in a separate chapter."
},
{
"code": null,
"e": 21611,
"s": 21344,
"text": "Note − JavaScript does not make a distinction between integer values and floating-point values. All numbers in JavaScript are represented as floating-point values. JavaScript represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard."
},
{
"code": null,
"e": 21825,
"s": 21611,
"text": "Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container."
},
{
"code": null,
"e": 21953,
"s": 21825,
"text": "Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows."
},
{
"code": null,
"e": 22047,
"s": 21953,
"text": "<script type = \"text/javascript\">\n <!--\n var money;\n var name;\n //-->\n</script>"
},
{
"code": null,
"e": 22126,
"s": 22047,
"text": "You can also declare multiple variables with the same var keyword as follows −"
},
{
"code": null,
"e": 22210,
"s": 22126,
"text": "<script type = \"text/javascript\">\n <!--\n var money, name;\n //-->\n</script>"
},
{
"code": null,
"e": 22400,
"s": 22210,
"text": "Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or at a later point in time when you need that variable."
},
{
"code": null,
"e": 22583,
"s": 22400,
"text": "For instance, you might create a variable named money and assign the value 2000.50 to it later. For another variable, you can assign a value at the time of initialization as follows."
},
{
"code": null,
"e": 22708,
"s": 22583,
"text": "<script type = \"text/javascript\">\n <!--\n var name = \"Ali\";\n var money;\n money = 2000.50;\n //-->\n</script>"
},
{
"code": null,
"e": 22876,
"s": 22708,
"text": "Note − Use the var keyword only for declaration or initialization, once for the life of any variable name in a document. You should not re-declare same variable twice."
},
{
"code": null,
"e": 23236,
"s": 22876,
"text": "JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don't have to tell JavaScript during variable declaration what type of value the variable will hold. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically."
},
{
"code": null,
"e": 23357,
"s": 23236,
"text": "The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes."
},
{
"code": null,
"e": 23475,
"s": 23357,
"text": "Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code."
},
{
"code": null,
"e": 23593,
"s": 23475,
"text": "Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code."
},
{
"code": null,
"e": 23743,
"s": 23593,
"text": "Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function."
},
{
"code": null,
"e": 23893,
"s": 23743,
"text": "Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function."
},
{
"code": null,
"e": 24178,
"s": 23893,
"text": "Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. Take a look into the following example."
},
{
"code": null,
"e": 24554,
"s": 24178,
"text": "<html>\n <body onload = checkscope();> \n <script type = \"text/javascript\">\n <!--\n var myVar = \"global\"; // Declare a global variable\n function checkscope( ) {\n var myVar = \"local\"; // Declare a local variable\n document.write(myVar);\n }\n //-->\n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 24591,
"s": 24554,
"text": "This produces the following result −"
},
{
"code": null,
"e": 24598,
"s": 24591,
"text": "local\n"
},
{
"code": null,
"e": 24675,
"s": 24598,
"text": "While naming your variables in JavaScript, keep the following rules in mind."
},
{
"code": null,
"e": 24864,
"s": 24675,
"text": "You should not use any of the JavaScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid."
},
{
"code": null,
"e": 25053,
"s": 24864,
"text": "You should not use any of the JavaScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid."
},
{
"code": null,
"e": 25254,
"s": 25053,
"text": "JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one."
},
{
"code": null,
"e": 25455,
"s": 25254,
"text": "JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one."
},
{
"code": null,
"e": 25557,
"s": 25455,
"text": "JavaScript variable names are case-sensitive. For example, Name and name are two different variables."
},
{
"code": null,
"e": 25659,
"s": 25557,
"text": "JavaScript variable names are case-sensitive. For example, Name and name are two different variables."
},
{
"code": null,
"e": 25839,
"s": 25659,
"text": "A list of all the reserved words in JavaScript are given in the following table. They cannot be used as JavaScript variables, functions, methods, loop labels, or any object names."
},
{
"code": null,
"e": 26011,
"s": 25839,
"text": "Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is called the operator. JavaScript supports the following types of operators."
},
{
"code": null,
"e": 26032,
"s": 26011,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 26053,
"s": 26032,
"text": "Comparison Operators"
},
{
"code": null,
"e": 26087,
"s": 26053,
"text": "Logical (or Relational) Operators"
},
{
"code": null,
"e": 26108,
"s": 26087,
"text": "Assignment Operators"
},
{
"code": null,
"e": 26143,
"s": 26108,
"text": "Conditional (or ternary) Operators"
},
{
"code": null,
"e": 26189,
"s": 26143,
"text": "Lets have a look on all operators one by one."
},
{
"code": null,
"e": 26246,
"s": 26189,
"text": "JavaScript supports the following arithmetic operators −"
},
{
"code": null,
"e": 26305,
"s": 26246,
"text": "Assume variable A holds 10 and variable B holds 20, then −"
},
{
"code": null,
"e": 26318,
"s": 26305,
"text": "+ (Addition)"
},
{
"code": null,
"e": 26336,
"s": 26318,
"text": "Adds two operands"
},
{
"code": null,
"e": 26359,
"s": 26336,
"text": "Ex: A + B will give 30"
},
{
"code": null,
"e": 26375,
"s": 26359,
"text": "- (Subtraction)"
},
{
"code": null,
"e": 26419,
"s": 26375,
"text": "Subtracts the second operand from the first"
},
{
"code": null,
"e": 26443,
"s": 26419,
"text": "Ex: A - B will give -10"
},
{
"code": null,
"e": 26462,
"s": 26443,
"text": "* (Multiplication)"
},
{
"code": null,
"e": 26485,
"s": 26462,
"text": "Multiply both operands"
},
{
"code": null,
"e": 26509,
"s": 26485,
"text": "Ex: A * B will give 200"
},
{
"code": null,
"e": 26522,
"s": 26509,
"text": "/ (Division)"
},
{
"code": null,
"e": 26562,
"s": 26522,
"text": "Divide the numerator by the denominator"
},
{
"code": null,
"e": 26584,
"s": 26562,
"text": "Ex: B / A will give 2"
},
{
"code": null,
"e": 26596,
"s": 26584,
"text": "% (Modulus)"
},
{
"code": null,
"e": 26641,
"s": 26596,
"text": "Outputs the remainder of an integer division"
},
{
"code": null,
"e": 26663,
"s": 26641,
"text": "Ex: B % A will give 0"
},
{
"code": null,
"e": 26678,
"s": 26663,
"text": "++ (Increment)"
},
{
"code": null,
"e": 26712,
"s": 26678,
"text": "Increases an integer value by one"
},
{
"code": null,
"e": 26733,
"s": 26712,
"text": "Ex: A++ will give 11"
},
{
"code": null,
"e": 26748,
"s": 26733,
"text": "-- (Decrement)"
},
{
"code": null,
"e": 26782,
"s": 26748,
"text": "Decreases an integer value by one"
},
{
"code": null,
"e": 26802,
"s": 26782,
"text": "Ex: A-- will give 9"
},
{
"code": null,
"e": 26900,
"s": 26802,
"text": "Note − Addition operator (+) works for Numeric as well as Strings. e.g. \"a\" + 10 will give \"a10\"."
},
{
"code": null,
"e": 26972,
"s": 26900,
"text": "The following code shows how to use arithmetic operators in JavaScript."
},
{
"code": null,
"e": 28391,
"s": 26972,
"text": "<html>\n <body>\n \n <script type = \"text/javascript\">\n <!--\n var a = 33;\n var b = 10;\n var c = \"Test\";\n var linebreak = \"<br />\";\n \n document.write(\"a + b = \");\n result = a + b;\n document.write(result);\n document.write(linebreak);\n \n document.write(\"a - b = \");\n result = a - b;\n document.write(result);\n document.write(linebreak);\n \n document.write(\"a / b = \");\n result = a / b;\n document.write(result);\n document.write(linebreak);\n \n document.write(\"a % b = \");\n result = a % b;\n document.write(result);\n document.write(linebreak);\n \n document.write(\"a + b + c = \");\n result = a + b + c;\n document.write(result);\n document.write(linebreak);\n \n a = ++a;\n document.write(\"++a = \");\n result = ++a;\n document.write(result);\n document.write(linebreak);\n \n b = --b;\n document.write(\"--b = \");\n result = --b;\n document.write(result);\n document.write(linebreak);\n //-->\n </script>\n \n Set the variables to different values and then try...\n </body>\n</html>"
},
{
"code": null,
"e": 28526,
"s": 28391,
"text": "a + b = 43\na - b = 23\na / b = 3.3\na % b = 3\na + b + c = 43Test\n++a = 35\n--b = 8\nSet the variables to different values and then try...\n"
},
{
"code": null,
"e": 28583,
"s": 28526,
"text": "JavaScript supports the following comparison operators −"
},
{
"code": null,
"e": 28642,
"s": 28583,
"text": "Assume variable A holds 10 and variable B holds 20, then −"
},
{
"code": null,
"e": 28654,
"s": 28642,
"text": "= = (Equal)"
},
{
"code": null,
"e": 28749,
"s": 28654,
"text": "Checks if the value of two operands are equal or not, if yes, then the condition becomes true."
},
{
"code": null,
"e": 28775,
"s": 28749,
"text": "Ex: (A == B) is not true."
},
{
"code": null,
"e": 28790,
"s": 28775,
"text": "!= (Not Equal)"
},
{
"code": null,
"e": 28906,
"s": 28790,
"text": "Checks if the value of two operands are equal or not, if the values are not equal, then the condition becomes true."
},
{
"code": null,
"e": 28928,
"s": 28906,
"text": "Ex: (A != B) is true."
},
{
"code": null,
"e": 28945,
"s": 28928,
"text": "> (Greater than)"
},
{
"code": null,
"e": 29074,
"s": 28945,
"text": "Checks if the value of the left operand is greater than the value of the right operand, if yes, then the condition becomes true."
},
{
"code": null,
"e": 29099,
"s": 29074,
"text": "Ex: (A > B) is not true."
},
{
"code": null,
"e": 29113,
"s": 29099,
"text": "< (Less than)"
},
{
"code": null,
"e": 29239,
"s": 29113,
"text": "Checks if the value of the left operand is less than the value of the right operand, if yes, then the condition becomes true."
},
{
"code": null,
"e": 29260,
"s": 29239,
"text": "Ex: (A < B) is true."
},
{
"code": null,
"e": 29290,
"s": 29260,
"text": ">= (Greater than or Equal to)"
},
{
"code": null,
"e": 29431,
"s": 29290,
"text": "Checks if the value of the left operand is greater than or equal to the value of the right operand, if yes, then the condition becomes true."
},
{
"code": null,
"e": 29457,
"s": 29431,
"text": "Ex: (A >= B) is not true."
},
{
"code": null,
"e": 29484,
"s": 29457,
"text": "<= (Less than or Equal to)"
},
{
"code": null,
"e": 29622,
"s": 29484,
"text": "Checks if the value of the left operand is less than or equal to the value of the right operand, if yes, then the condition becomes true."
},
{
"code": null,
"e": 29644,
"s": 29622,
"text": "Ex: (A <= B) is true."
},
{
"code": null,
"e": 29716,
"s": 29644,
"text": "The following code shows how to use comparison operators in JavaScript."
},
{
"code": null,
"e": 30968,
"s": 29716,
"text": "<html>\n <body> \n <script type = \"text/javascript\">\n <!--\n var a = 10;\n var b = 20;\n var linebreak = \"<br />\";\n \n document.write(\"(a == b) => \");\n result = (a == b);\n document.write(result);\n document.write(linebreak);\n \n document.write(\"(a < b) => \");\n result = (a < b);\n document.write(result);\n document.write(linebreak);\n \n document.write(\"(a > b) => \");\n result = (a > b);\n document.write(result);\n document.write(linebreak);\n \n document.write(\"(a != b) => \");\n result = (a != b);\n document.write(result);\n document.write(linebreak);\n \n document.write(\"(a >= b) => \");\n result = (a >= b);\n document.write(result);\n document.write(linebreak);\n \n document.write(\"(a <= b) => \");\n result = (a <= b);\n document.write(result);\n document.write(linebreak);\n //-->\n </script> \n Set the variables to different values and different operators and then try...\n </body>\n</html>"
},
{
"code": null,
"e": 31154,
"s": 30968,
"text": "(a == b) => false \n(a < b) => true \n(a > b) => false \n(a != b) => true \n(a >= b) => false \na <= b) => true\nSet the variables to different values and different operators and then try...\n"
},
{
"code": null,
"e": 31208,
"s": 31154,
"text": "JavaScript supports the following logical operators −"
},
{
"code": null,
"e": 31267,
"s": 31208,
"text": "Assume variable A holds 10 and variable B holds 20, then −"
},
{
"code": null,
"e": 31284,
"s": 31267,
"text": "&& (Logical AND)"
},
{
"code": null,
"e": 31352,
"s": 31284,
"text": "If both the operands are non-zero, then the condition becomes true."
},
{
"code": null,
"e": 31374,
"s": 31352,
"text": "Ex: (A && B) is true."
},
{
"code": null,
"e": 31390,
"s": 31374,
"text": "|| (Logical OR)"
},
{
"code": null,
"e": 31464,
"s": 31390,
"text": "If any of the two operands are non-zero, then the condition becomes true."
},
{
"code": null,
"e": 31486,
"s": 31464,
"text": "Ex: (A || B) is true."
},
{
"code": null,
"e": 31502,
"s": 31486,
"text": "! (Logical NOT)"
},
{
"code": null,
"e": 31619,
"s": 31502,
"text": "Reverses the logical state of its operand. If a condition is true, then the Logical NOT operator will make it false."
},
{
"code": null,
"e": 31644,
"s": 31619,
"text": "Ex: ! (A && B) is false."
},
{
"code": null,
"e": 31726,
"s": 31644,
"text": "Try the following code to learn how to implement Logical Operators in JavaScript."
},
{
"code": null,
"e": 32519,
"s": 31726,
"text": "<html>\n <body> \n <script type = \"text/javascript\">\n <!--\n var a = true;\n var b = false;\n var linebreak = \"<br />\";\n \n document.write(\"(a && b) => \");\n result = (a && b);\n document.write(result);\n document.write(linebreak);\n \n document.write(\"(a || b) => \");\n result = (a || b);\n document.write(result);\n document.write(linebreak);\n \n document.write(\"!(a && b) => \");\n result = (!(a && b));\n document.write(result);\n document.write(linebreak);\n //-->\n </script> \n <p>Set the variables to different values and different operators and then try...</p>\n </body>\n</html>"
},
{
"code": null,
"e": 32653,
"s": 32519,
"text": "(a && b) => false \n(a || b) => true \n!(a && b) => true\nSet the variables to different values and different operators and then try...\n"
},
{
"code": null,
"e": 32707,
"s": 32653,
"text": "JavaScript supports the following bitwise operators −"
},
{
"code": null,
"e": 32764,
"s": 32707,
"text": "Assume variable A holds 2 and variable B holds 3, then −"
},
{
"code": null,
"e": 32780,
"s": 32764,
"text": "& (Bitwise AND)"
},
{
"code": null,
"e": 32854,
"s": 32780,
"text": "It performs a Boolean AND operation on each bit of its integer arguments."
},
{
"code": null,
"e": 32872,
"s": 32854,
"text": "Ex: (A & B) is 2."
},
{
"code": null,
"e": 32887,
"s": 32872,
"text": "| (BitWise OR)"
},
{
"code": null,
"e": 32960,
"s": 32887,
"text": "It performs a Boolean OR operation on each bit of its integer arguments."
},
{
"code": null,
"e": 32978,
"s": 32960,
"text": "Ex: (A | B) is 3."
},
{
"code": null,
"e": 32994,
"s": 32978,
"text": "^ (Bitwise XOR)"
},
{
"code": null,
"e": 33166,
"s": 32994,
"text": "It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both."
},
{
"code": null,
"e": 33184,
"s": 33166,
"text": "Ex: (A ^ B) is 1."
},
{
"code": null,
"e": 33200,
"s": 33184,
"text": "~ (Bitwise Not)"
},
{
"code": null,
"e": 33278,
"s": 33200,
"text": "It is a unary operator and operates by reversing all the bits in the operand."
},
{
"code": null,
"e": 33294,
"s": 33278,
"text": "Ex: (~B) is -4."
},
{
"code": null,
"e": 33310,
"s": 33294,
"text": "<< (Left Shift)"
},
{
"code": null,
"e": 33599,
"s": 33310,
"text": "It moves all the bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying by 4, and so on."
},
{
"code": null,
"e": 33618,
"s": 33599,
"text": "Ex: (A << 1) is 4."
},
{
"code": null,
"e": 33635,
"s": 33618,
"text": ">> (Right Shift)"
},
{
"code": null,
"e": 33758,
"s": 33635,
"text": "Binary Right Shift Operator. The left operand’s value is moved right by the number of bits specified by the right operand."
},
{
"code": null,
"e": 33777,
"s": 33758,
"text": "Ex: (A >> 1) is 1."
},
{
"code": null,
"e": 33805,
"s": 33777,
"text": ">>> (Right shift with Zero)"
},
{
"code": null,
"e": 33910,
"s": 33805,
"text": "This operator is just like the >> operator, except that the bits shifted in on the left are always zero."
},
{
"code": null,
"e": 33930,
"s": 33910,
"text": "Ex: (A >>> 1) is 1."
},
{
"code": null,
"e": 33998,
"s": 33930,
"text": "Try the following code to implement Bitwise operator in JavaScript."
},
{
"code": null,
"e": 35295,
"s": 33998,
"text": "<html>\n <body> \n <script type = \"text/javascript\">\n <!--\n var a = 2; // Bit presentation 10\n var b = 3; // Bit presentation 11\n var linebreak = \"<br />\";\n \n document.write(\"(a & b) => \");\n result = (a & b);\n document.write(result);\n document.write(linebreak);\n \n document.write(\"(a | b) => \");\n result = (a | b);\n document.write(result);\n document.write(linebreak);\n \n document.write(\"(a ^ b) => \");\n result = (a ^ b);\n document.write(result);\n document.write(linebreak);\n \n document.write(\"(~b) => \");\n result = (~b);\n document.write(result);\n document.write(linebreak);\n \n document.write(\"(a << b) => \");\n result = (a << b);\n document.write(result);\n document.write(linebreak);\n \n document.write(\"(a >> b) => \");\n result = (a >> b);\n document.write(result);\n document.write(linebreak);\n //-->\n </script> \n <p>Set the variables to different values and different operators and then try...</p>\n </body>\n</html>"
},
{
"code": null,
"e": 35458,
"s": 35295,
"text": "(a & b) => 2 \n(a | b) => 3 \n(a ^ b) => 1 \n(~b) => -4 \n(a << b) => 16 \n(a >> b) => 0\nSet the variables to different values and different operators and then try...\n"
},
{
"code": null,
"e": 35515,
"s": 35458,
"text": "JavaScript supports the following assignment operators −"
},
{
"code": null,
"e": 35538,
"s": 35515,
"text": "= (Simple Assignment )"
},
{
"code": null,
"e": 35606,
"s": 35538,
"text": "Assigns values from the right side operand to the left side operand"
},
{
"code": null,
"e": 35658,
"s": 35606,
"text": "Ex: C = A + B will assign the value of A + B into C"
},
{
"code": null,
"e": 35682,
"s": 35658,
"text": "+= (Add and Assignment)"
},
{
"code": null,
"e": 35772,
"s": 35682,
"text": "It adds the right operand to the left operand and assigns the result to the left operand."
},
{
"code": null,
"e": 35810,
"s": 35772,
"text": "Ex: C += A is equivalent to C = C + A"
},
{
"code": null,
"e": 35839,
"s": 35810,
"text": "−= (Subtract and Assignment)"
},
{
"code": null,
"e": 35936,
"s": 35839,
"text": "It subtracts the right operand from the left operand and assigns the result to the left operand."
},
{
"code": null,
"e": 35974,
"s": 35936,
"text": "Ex: C -= A is equivalent to C = C - A"
},
{
"code": null,
"e": 36003,
"s": 35974,
"text": "*= (Multiply and Assignment)"
},
{
"code": null,
"e": 36101,
"s": 36003,
"text": "It multiplies the right operand with the left operand and assigns the result to the left operand."
},
{
"code": null,
"e": 36139,
"s": 36101,
"text": "Ex: C *= A is equivalent to C = C * A"
},
{
"code": null,
"e": 36166,
"s": 36139,
"text": "/= (Divide and Assignment)"
},
{
"code": null,
"e": 36261,
"s": 36166,
"text": "It divides the left operand with the right operand and assigns the result to the left operand."
},
{
"code": null,
"e": 36299,
"s": 36261,
"text": "Ex: C /= A is equivalent to C = C / A"
},
{
"code": null,
"e": 36327,
"s": 36299,
"text": "%= (Modules and Assignment)"
},
{
"code": null,
"e": 36407,
"s": 36327,
"text": "It takes modulus using two operands and assigns the result to the left operand."
},
{
"code": null,
"e": 36445,
"s": 36407,
"text": "Ex: C %= A is equivalent to C = C % A"
},
{
"code": null,
"e": 36547,
"s": 36445,
"text": "Note − Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=, |= and ^=."
},
{
"code": null,
"e": 36618,
"s": 36547,
"text": "Try the following code to implement assignment operator in JavaScript."
},
{
"code": null,
"e": 37967,
"s": 36618,
"text": "<html>\n <body> \n <script type = \"text/javascript\">\n <!--\n var a = 33;\n var b = 10;\n var linebreak = \"<br />\";\n \n document.write(\"Value of a => (a = b) => \");\n result = (a = b);\n document.write(result);\n document.write(linebreak);\n \n document.write(\"Value of a => (a += b) => \");\n result = (a += b);\n document.write(result);\n document.write(linebreak);\n \n document.write(\"Value of a => (a -= b) => \");\n result = (a -= b);\n document.write(result);\n document.write(linebreak);\n \n document.write(\"Value of a => (a *= b) => \");\n result = (a *= b);\n document.write(result);\n document.write(linebreak);\n \n document.write(\"Value of a => (a /= b) => \");\n result = (a /= b);\n document.write(result);\n document.write(linebreak);\n \n document.write(\"Value of a => (a %= b) => \");\n result = (a %= b);\n document.write(result);\n document.write(linebreak);\n //-->\n </script> \n <p>Set the variables to different values and different operators and then try...</p>\n </body>\n</html>"
},
{
"code": null,
"e": 38222,
"s": 37967,
"text": "Value of a => (a = b) => 10\nValue of a => (a += b) => 20 \nValue of a => (a -= b) => 10 \nValue of a => (a *= b) => 100 \nValue of a => (a /= b) => 10\nValue of a => (a %= b) => 0\nSet the variables to different values and different operators and then try...\n"
},
{
"code": null,
"e": 38350,
"s": 38222,
"text": "We will discuss two operators here that are quite useful in JavaScript: the conditional operator (? :) and the typeof operator."
},
{
"code": null,
"e": 38526,
"s": 38350,
"text": "The conditional operator first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation."
},
{
"code": null,
"e": 38545,
"s": 38526,
"text": "? : (Conditional )"
},
{
"code": null,
"e": 38600,
"s": 38545,
"text": "If Condition is true? Then value X : Otherwise value Y"
},
{
"code": null,
"e": 38687,
"s": 38600,
"text": "Try the following code to understand how the Conditional Operator works in JavaScript."
},
{
"code": null,
"e": 39364,
"s": 38687,
"text": "<html>\n <body> \n <script type = \"text/javascript\">\n <!--\n var a = 10;\n var b = 20;\n var linebreak = \"<br />\";\n \n document.write (\"((a > b) ? 100 : 200) => \");\n result = (a > b) ? 100 : 200;\n document.write(result);\n document.write(linebreak);\n \n document.write (\"((a < b) ? 100 : 200) => \");\n result = (a < b) ? 100 : 200;\n document.write(result);\n document.write(linebreak);\n //-->\n </script> \n <p>Set the variables to different values and different operators and then try...</p>\n </body>\n</html>"
},
{
"code": null,
"e": 39502,
"s": 39364,
"text": "((a > b) ? 100 : 200) => 200 \n((a < b) ? 100 : 200) => 100\nSet the variables to different values and different operators and then try...\n"
},
{
"code": null,
"e": 39673,
"s": 39502,
"text": "The typeof operator is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand."
},
{
"code": null,
"e": 39843,
"s": 39673,
"text": "The typeof operator evaluates to \"number\", \"string\", or \"boolean\" if its operand is a number, string, or boolean value and returns true or false based on the evaluation."
},
{
"code": null,
"e": 39904,
"s": 39843,
"text": "Here is a list of the return values for the typeof Operator."
},
{
"code": null,
"e": 39963,
"s": 39904,
"text": "The following code shows how to implement typeof operator."
},
{
"code": null,
"e": 40689,
"s": 39963,
"text": "<html>\n <body> \n <script type = \"text/javascript\">\n <!--\n var a = 10;\n var b = \"String\";\n var linebreak = \"<br />\";\n \n result = (typeof b == \"string\" ? \"B is String\" : \"B is Numeric\");\n document.write(\"Result => \");\n document.write(result);\n document.write(linebreak);\n \n result = (typeof a == \"string\" ? \"A is String\" : \"A is Numeric\");\n document.write(\"Result => \");\n document.write(result);\n document.write(linebreak);\n //-->\n </script> \n <p>Set the variables to different values and different operators and then try...</p>\n </body>\n</html>"
},
{
"code": null,
"e": 40814,
"s": 40689,
"text": "Result => B is String \nResult => A is Numeric\nSet the variables to different values and different operators and then try...\n"
},
{
"code": null,
"e": 41051,
"s": 40814,
"text": "While writing a program, there may be a situation when you need to adopt one out of a given set of paths. In such cases, you need to use conditional statements that allow your program to make correct decisions and perform right actions."
},
{
"code": null,
"e": 41214,
"s": 41051,
"text": "JavaScript supports conditional statements which are used to perform different actions based on different conditions. Here we will explain the if..else statement."
},
{
"code": null,
"e": 41278,
"s": 41214,
"text": "The following flow chart shows how the if-else statement works."
},
{
"code": null,
"e": 41342,
"s": 41278,
"text": "JavaScript supports the following forms of if..else statement −"
},
{
"code": null,
"e": 41355,
"s": 41342,
"text": "if statement"
},
{
"code": null,
"e": 41368,
"s": 41355,
"text": "if statement"
},
{
"code": null,
"e": 41388,
"s": 41368,
"text": "if...else statement"
},
{
"code": null,
"e": 41408,
"s": 41388,
"text": "if...else statement"
},
{
"code": null,
"e": 41435,
"s": 41408,
"text": "if...else if... statement."
},
{
"code": null,
"e": 41462,
"s": 41435,
"text": "if...else if... statement."
},
{
"code": null,
"e": 41595,
"s": 41462,
"text": "The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally."
},
{
"code": null,
"e": 41647,
"s": 41595,
"text": "The syntax for a basic if statement is as follows −"
},
{
"code": null,
"e": 41721,
"s": 41647,
"text": "if (expression) {\n Statement(s) to be executed if expression is true\n}\n"
},
{
"code": null,
"e": 41979,
"s": 41721,
"text": "Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s) are executed. If the expression is false, then no statement would be not executed. Most of the times, you will use comparison operators while making decisions."
},
{
"code": null,
"e": 42047,
"s": 41979,
"text": "Try the following example to understand how the if statement works."
},
{
"code": null,
"e": 42386,
"s": 42047,
"text": "<html>\n <body> \n <script type = \"text/javascript\">\n <!--\n var age = 20;\n \n if( age > 18 ) {\n document.write(\"<b>Qualifies for driving</b>\");\n }\n //-->\n </script> \n <p>Set the variable to different value and then try...</p>\n </body>\n</html>"
},
{
"code": null,
"e": 42461,
"s": 42386,
"text": "Qualifies for driving\nSet the variable to different value and then try...\n"
},
{
"code": null,
"e": 42596,
"s": 42461,
"text": "The 'if...else' statement is the next form of control statement that allows JavaScript to execute statements in a more controlled way."
},
{
"code": null,
"e": 42733,
"s": 42596,
"text": "if (expression) {\n Statement(s) to be executed if expression is true\n} else {\n Statement(s) to be executed if expression is false\n}\n"
},
{
"code": null,
"e": 42950,
"s": 42733,
"text": "Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else block are executed."
},
{
"code": null,
"e": 43035,
"s": 42950,
"text": "Try the following code to learn how to implement an if-else statement in JavaScript."
},
{
"code": null,
"e": 43462,
"s": 43035,
"text": "<html>\n <body> \n <script type = \"text/javascript\">\n <!--\n var age = 15;\n \n if( age > 18 ) {\n document.write(\"<b>Qualifies for driving</b>\");\n } else {\n document.write(\"<b>Does not qualify for driving</b>\");\n }\n //-->\n </script> \n <p>Set the variable to different value and then try...</p>\n </body>\n</html>"
},
{
"code": null,
"e": 43544,
"s": 43462,
"text": "Does not qualify for driving\nSet the variable to different value and then try...\n"
},
{
"code": null,
"e": 43684,
"s": 43544,
"text": "The if...else if... statement is an advanced form of if...else that allows JavaScript to make a correct decision out of several conditions."
},
{
"code": null,
"e": 43738,
"s": 43684,
"text": "The syntax of an if-else-if statement is as follows −"
},
{
"code": null,
"e": 44045,
"s": 43738,
"text": "if (expression 1) {\n Statement(s) to be executed if expression 1 is true\n} else if (expression 2) {\n Statement(s) to be executed if expression 2 is true\n} else if (expression 3) {\n Statement(s) to be executed if expression 3 is true\n} else {\n Statement(s) to be executed if no expression is true\n}\n"
},
{
"code": null,
"e": 44318,
"s": 44045,
"text": "There is nothing special about this code. It is just a series of if statements, where each if is a part of the else clause of the previous statement. Statement(s) are executed based on the true condition, if none of the conditions is true, then the else block is executed."
},
{
"code": null,
"e": 44406,
"s": 44318,
"text": "Try the following code to learn how to implement an if-else-if statement in JavaScript."
},
{
"code": null,
"e": 45011,
"s": 44406,
"text": "<html>\n <body> \n <script type = \"text/javascript\">\n <!--\n var book = \"maths\";\n if( book == \"history\" ) {\n document.write(\"<b>History Book</b>\");\n } else if( book == \"maths\" ) {\n document.write(\"<b>Maths Book</b>\");\n } else if( book == \"economics\" ) {\n document.write(\"<b>Economics Book</b>\");\n } else {\n document.write(\"<b>Unknown Book</b>\");\n }\n //-->\n </script> \n <p>Set the variable to different value and then try...</p>\n </body>\n<html>"
},
{
"code": null,
"e": 45075,
"s": 45011,
"text": "Maths Book\nSet the variable to different value and then try...\n"
},
{
"code": null,
"e": 45306,
"s": 45075,
"text": "You can use multiple if...else...if statements, as in the previous chapter, to perform a multiway branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable."
},
{
"code": null,
"e": 45476,
"s": 45306,
"text": "Starting with JavaScript 1.2, you can use a switch statement which handles exactly this situation, and it does so more efficiently than repeated if...else if statements."
},
{
"code": null,
"e": 45541,
"s": 45476,
"text": "The following flow chart explains a switch-case statement works."
},
{
"code": null,
"e": 45843,
"s": 45541,
"text": "The objective of a switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used."
},
{
"code": null,
"e": 46044,
"s": 45843,
"text": "switch (expression) {\n case condition 1: statement(s)\n break;\n \n case condition 2: statement(s)\n break;\n ...\n \n case condition n: statement(s)\n break;\n \n default: statement(s)\n}\n"
},
{
"code": null,
"e": 46214,
"s": 46044,
"text": "The break statements indicate the end of a particular case. If they were omitted, the interpreter would continue executing each statement in each of the following cases."
},
{
"code": null,
"e": 46271,
"s": 46214,
"text": "We will explain break statement in Loop Control chapter."
},
{
"code": null,
"e": 46333,
"s": 46271,
"text": "Try the following example to implement switch-case statement."
},
{
"code": null,
"e": 47246,
"s": 46333,
"text": "<html>\n <body> \n <script type = \"text/javascript\">\n <!--\n var grade = 'A';\n document.write(\"Entering switch block<br />\");\n switch (grade) {\n case 'A': document.write(\"Good job<br />\");\n break;\n \n case 'B': document.write(\"Pretty good<br />\");\n break;\n \n case 'C': document.write(\"Passed<br />\");\n break;\n \n case 'D': document.write(\"Not so good<br />\");\n break;\n \n case 'F': document.write(\"Failed<br />\");\n break;\n \n default: document.write(\"Unknown grade<br />\")\n }\n document.write(\"Exiting switch block\");\n //-->\n </script> \n <p>Set the variable to different value and then try...</p>\n </body>\n</html>"
},
{
"code": null,
"e": 47351,
"s": 47246,
"text": "Entering switch block\nGood job\nExiting switch block\nSet the variable to different value and then try...\n"
},
{
"code": null,
"e": 47497,
"s": 47351,
"text": "Break statements play a major role in switch-case statements. Try the following code that uses switch-case statement without any break statement."
},
{
"code": null,
"e": 48237,
"s": 47497,
"text": "<html>\n <body> \n <script type = \"text/javascript\">\n <!--\n var grade = 'A';\n document.write(\"Entering switch block<br />\");\n switch (grade) {\n case 'A': document.write(\"Good job<br />\");\n case 'B': document.write(\"Pretty good<br />\");\n case 'C': document.write(\"Passed<br />\");\n case 'D': document.write(\"Not so good<br />\");\n case 'F': document.write(\"Failed<br />\");\n default: document.write(\"Unknown grade<br />\")\n }\n document.write(\"Exiting switch block\");\n //-->\n </script> \n <p>Set the variable to different value and then try...</p>\n </body>\n</html>"
},
{
"code": null,
"e": 48394,
"s": 48237,
"text": "Entering switch block\nGood job\nPretty good\nPassed\nNot so good\nFailed\nUnknown grade\nExiting switch block\nSet the variable to different value and then try...\n"
},
{
"code": null,
"e": 48597,
"s": 48394,
"text": "While writing a program, you may encounter a situation where you need to perform an action over and over again. In such situations, you would need to write loop statements to reduce the number of lines."
},
{
"code": null,
"e": 48683,
"s": 48597,
"text": "JavaScript supports all the necessary loops to ease down the pressure of programming."
},
{
"code": null,
"e": 48946,
"s": 48683,
"text": "The most basic loop in JavaScript is the while loop which would be discussed in this chapter. The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the loop terminates."
},
{
"code": null,
"e": 48994,
"s": 48946,
"text": "The flow chart of while loop looks as follows −"
},
{
"code": null,
"e": 49049,
"s": 48994,
"text": "The syntax of while loop in JavaScript is as follows −"
},
{
"code": null,
"e": 49126,
"s": 49049,
"text": "while (expression) {\n Statement(s) to be executed if expression is true\n}\n"
},
{
"code": null,
"e": 49177,
"s": 49126,
"text": "Try the following example to implement while loop."
},
{
"code": null,
"e": 49656,
"s": 49177,
"text": "<html>\n <body>\n \n <script type = \"text/javascript\">\n <!--\n var count = 0;\n document.write(\"Starting Loop \");\n \n while (count < 10) {\n document.write(\"Current Count : \" + count + \"<br />\");\n count++;\n }\n \n document.write(\"Loop stopped!\");\n //-->\n </script>\n \n <p>Set the variable to different value and then try...</p>\n </body>\n</html>"
},
{
"code": null,
"e": 49918,
"s": 49656,
"text": "Starting Loop\nCurrent Count : 0\nCurrent Count : 1\nCurrent Count : 2\nCurrent Count : 3\nCurrent Count : 4\nCurrent Count : 5\nCurrent Count : 6\nCurrent Count : 7\nCurrent Count : 8\nCurrent Count : 9\nLoop stopped!\nSet the variable to different value and then try... \n"
},
{
"code": null,
"e": 50127,
"s": 49918,
"text": "The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false."
},
{
"code": null,
"e": 50183,
"s": 50127,
"text": "The flow chart of a do-while loop would be as follows −"
},
{
"code": null,
"e": 50242,
"s": 50183,
"text": "The syntax for do-while loop in JavaScript is as follows −"
},
{
"code": null,
"e": 50302,
"s": 50242,
"text": "do {\n Statement(s) to be executed;\n} while (expression);\n"
},
{
"code": null,
"e": 50374,
"s": 50302,
"text": "Note − Don’t miss the semicolon used at the end of the do...while loop."
},
{
"code": null,
"e": 50457,
"s": 50374,
"text": "Try the following example to learn how to implement a do-while loop in JavaScript."
},
{
"code": null,
"e": 50963,
"s": 50457,
"text": "<html>\n <body> \n <script type = \"text/javascript\">\n <!--\n var count = 0;\n \n document.write(\"Starting Loop\" + \"<br />\");\n do {\n document.write(\"Current Count : \" + count + \"<br />\");\n count++;\n }\n \n while (count < 5);\n document.write (\"Loop stopped!\");\n //-->\n </script> \n <p>Set the variable to different value and then try...</p>\n </body>\n</html>"
},
{
"code": null,
"e": 51138,
"s": 50963,
"text": "Starting Loop\nCurrent Count : 0 \nCurrent Count : 1 \nCurrent Count : 2 \nCurrent Count : 3 \nCurrent Count : 4\nLoop Stopped!\nSet the variable to different value and then try...\n"
},
{
"code": null,
"e": 51240,
"s": 51138,
"text": "The 'for' loop is the most compact form of looping. It includes the following three important parts −"
},
{
"code": null,
"e": 51382,
"s": 51240,
"text": "The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins."
},
{
"code": null,
"e": 51524,
"s": 51382,
"text": "The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins."
},
{
"code": null,
"e": 51725,
"s": 51524,
"text": "The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop."
},
{
"code": null,
"e": 51926,
"s": 51725,
"text": "The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop."
},
{
"code": null,
"e": 51999,
"s": 51926,
"text": "The iteration statement where you can increase or decrease your counter."
},
{
"code": null,
"e": 52072,
"s": 51999,
"text": "The iteration statement where you can increase or decrease your counter."
},
{
"code": null,
"e": 52146,
"s": 52072,
"text": "You can put all the three parts in a single line separated by semicolons."
},
{
"code": null,
"e": 52211,
"s": 52146,
"text": "The flow chart of a for loop in JavaScript would be as follows −"
},
{
"code": null,
"e": 52264,
"s": 52211,
"text": "The syntax of for loop is JavaScript is as follows −"
},
{
"code": null,
"e": 52384,
"s": 52264,
"text": "for (initialization; test condition; iteration statement) {\n Statement(s) to be executed if test condition is true\n}\n"
},
{
"code": null,
"e": 52455,
"s": 52384,
"text": "Try the following example to learn how a for loop works in JavaScript."
},
{
"code": null,
"e": 52961,
"s": 52455,
"text": "<html>\n <body> \n <script type = \"text/javascript\">\n <!--\n var count;\n document.write(\"Starting Loop\" + \"<br />\");\n \n for(count = 0; count < 10; count++) {\n document.write(\"Current Count : \" + count );\n document.write(\"<br />\");\n } \n document.write(\"Loop stopped!\");\n //-->\n </script> \n <p>Set the variable to different value and then try...</p>\n </body>\n</html>"
},
{
"code": null,
"e": 53223,
"s": 52961,
"text": "Starting Loop\nCurrent Count : 0\nCurrent Count : 1\nCurrent Count : 2\nCurrent Count : 3\nCurrent Count : 4\nCurrent Count : 5\nCurrent Count : 6\nCurrent Count : 7\nCurrent Count : 8\nCurrent Count : 9\nLoop stopped! \nSet the variable to different value and then try...\n"
},
{
"code": null,
"e": 53467,
"s": 53223,
"text": "The for...in loop is used to loop through an object's properties. As we have not discussed Objects yet, you may not feel comfortable with this loop. But once you understand how objects behave in JavaScript, you will find this loop very useful."
},
{
"code": null,
"e": 53534,
"s": 53467,
"text": "for (variablename in object) {\n statement or block to execute\n}\n"
},
{
"code": null,
"e": 53683,
"s": 53534,
"text": "In each iteration, one property from object is assigned to variablename and this loop continues till all the properties of the object are exhausted."
},
{
"code": null,
"e": 53783,
"s": 53683,
"text": "Try the following example to implement ‘for-in’ loop. It prints the web browser’s Navigator object."
},
{
"code": null,
"e": 54278,
"s": 53783,
"text": "<html>\n <body> \n <script type = \"text/javascript\">\n <!--\n var aProperty;\n document.write(\"Navigator Object Properties<br /> \"); \n for (aProperty in navigator) {\n document.write(aProperty);\n document.write(\"<br />\");\n }\n document.write (\"Exiting from the loop!\");\n //-->\n </script> \n <p>Set the variable to different object and then try...</p>\n </body>\n</html>"
},
{
"code": null,
"e": 54819,
"s": 54278,
"text": "Navigator Object Properties \nserviceWorker \nwebkitPersistentStorage \nwebkitTemporaryStorage \ngeolocation \ndoNotTrack \nonLine \nlanguages \nlanguage \nuserAgent \nproduct \nplatform \nappVersion \nappName \nappCodeName \nhardwareConcurrency \nmaxTouchPoints \nvendorSub \nvendor \nproductSub \ncookieEnabled \nmimeTypes \nplugins \njavaEnabled \ngetStorageUpdates \ngetGamepads \nwebkitGetUserMedia \nvibrate \ngetBattery \nsendBeacon \nregisterProtocolHandler \nunregisterProtocolHandler \nExiting from the loop!\nSet the variable to different object and then try...\n"
},
{
"code": null,
"e": 55101,
"s": 54819,
"text": "JavaScript provides full control to handle loops and switch statements. There may be a situation when you need to come out of a loop without reaching its bottom. There may also be a situation when you want to skip a part of your code block and start the next iteration of the loop."
},
{
"code": null,
"e": 55302,
"s": 55101,
"text": "To handle all such situations, JavaScript provides break and continue statements. These statements are used to immediately come out of any loop or to start the next iteration of any loop respectively."
},
{
"code": null,
"e": 55453,
"s": 55302,
"text": "The break statement, which was briefly introduced with the switch statement, is used to exit a loop early, breaking out of the enclosing curly braces."
},
{
"code": null,
"e": 55513,
"s": 55453,
"text": "The flow chart of a break statement would look as follows −"
},
{
"code": null,
"e": 55734,
"s": 55513,
"text": "The following example illustrates the use of a break statement with a while loop. Notice how the loop breaks out early once x reaches 5 and reaches to document.write (..) statement just below to the closing curly brace −"
},
{
"code": null,
"e": 56277,
"s": 55734,
"text": "<html>\n <body> \n <script type = \"text/javascript\">\n <!--\n var x = 1;\n document.write(\"Entering the loop<br /> \");\n \n while (x < 20) {\n if (x == 5) {\n break; // breaks out of loop completely\n }\n x = x + 1;\n document.write( x + \"<br />\");\n } \n document.write(\"Exiting the loop!<br /> \");\n //-->\n </script>\n \n <p>Set the variable to different value and then try...</p>\n </body>\n</html>"
},
{
"code": null,
"e": 56374,
"s": 56277,
"text": "Entering the loop\n2\n3\n4\n5\nExiting the loop!\nSet the variable to different value and then try...\n"
},
{
"code": null,
"e": 56451,
"s": 56374,
"text": "We already have seen the usage of break statement inside a switch statement."
},
{
"code": null,
"e": 56804,
"s": 56451,
"text": "The continue statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block. When a continue statement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise the control comes out of the loop."
},
{
"code": null,
"e": 56985,
"s": 56804,
"text": "This example illustrates the use of a continue statement with a while loop. Notice how the continue statement is used to skip printing when the index held in variable x reaches 5 −"
},
{
"code": null,
"e": 57574,
"s": 56985,
"text": "<html>\n <body> \n <script type = \"text/javascript\">\n <!--\n var x = 1;\n document.write(\"Entering the loop<br /> \");\n \n while (x < 10) {\n x = x + 1;\n \n if (x == 5) {\n continue; // skip rest of the loop body\n }\n document.write( x + \"<br />\");\n } \n document.write(\"Exiting the loop!<br /> \");\n //-->\n </script> \n <p>Set the variable to different value and then try...</p>\n </body>\n</html>"
},
{
"code": null,
"e": 57680,
"s": 57574,
"text": "Entering the loop\n2\n3\n4\n6\n7\n8\n9\n10\nExiting the loop!\nSet the variable to different value and then try...\n"
},
{
"code": null,
"e": 57989,
"s": 57680,
"text": "Starting from JavaScript 1.2, a label can be used with break and continue to control the flow more precisely. A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. We will see two different examples to understand how to use labels with break and continue."
},
{
"code": null,
"e": 58179,
"s": 57989,
"text": "Note − Line breaks are not allowed between the ‘continue’ or ‘break’ statement and its label name. Also, there should not be any other statement in between a label name and associated loop."
},
{
"code": null,
"e": 58248,
"s": 58179,
"text": "Try the following two examples for a better understanding of Labels."
},
{
"code": null,
"e": 58323,
"s": 58248,
"text": "The following example shows how to implement Label with a break statement."
},
{
"code": null,
"e": 59127,
"s": 58323,
"text": "<html>\n <body> \n <script type = \"text/javascript\">\n <!--\n document.write(\"Entering the loop!<br /> \");\n outerloop: // This is the label name \n for (var i = 0; i < 5; i++) {\n document.write(\"Outerloop: \" + i + \"<br />\");\n innerloop:\n for (var j = 0; j < 5; j++) {\n if (j > 3 ) break ; // Quit the innermost loop\n if (i == 2) break innerloop; // Do the same thing\n if (i == 4) break outerloop; // Quit the outer loop\n document.write(\"Innerloop: \" + j + \" <br />\");\n }\n } \n document.write(\"Exiting the loop!<br /> \");\n //-->\n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 59398,
"s": 59127,
"text": "Entering the loop!\nOuterloop: 0\nInnerloop: 0 \nInnerloop: 1 \nInnerloop: 2 \nInnerloop: 3 \nOuterloop: 1\nInnerloop: 0 \nInnerloop: 1 \nInnerloop: 2 \nInnerloop: 3 \nOuterloop: 2\nOuterloop: 3\nInnerloop: 0 \nInnerloop: 1 \nInnerloop: 2 \nInnerloop: 3 \nOuterloop: 4\nExiting the loop!\n"
},
{
"code": null,
"e": 60016,
"s": 59398,
"text": "<html>\n <body>\n \n <script type = \"text/javascript\">\n <!--\n document.write(\"Entering the loop!<br /> \");\n outerloop: // This is the label name\n \n for (var i = 0; i < 3; i++) {\n document.write(\"Outerloop: \" + i + \"<br />\");\n for (var j = 0; j < 5; j++) {\n if (j == 3) {\n continue outerloop;\n }\n document.write(\"Innerloop: \" + j + \"<br />\");\n }\n }\n \n document.write(\"Exiting the loop!<br /> \");\n //-->\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 60210,
"s": 60016,
"text": "Entering the loop!\nOuterloop: 0\nInnerloop: 0\nInnerloop: 1\nInnerloop: 2\nOuterloop: 1\nInnerloop: 0\nInnerloop: 1\nInnerloop: 2\nOuterloop: 2\nInnerloop: 0\nInnerloop: 1\nInnerloop: 2\nExiting the loop!\n"
},
{
"code": null,
"e": 60511,
"s": 60210,
"text": "A function is a group of reusable code which can be called anywhere in your program. This eliminates the need of writing the same code again and again. It helps programmers in writing modular codes. Functions allow a programmer to divide a big program into a number of small and manageable functions."
},
{
"code": null,
"e": 60830,
"s": 60511,
"text": "Like any other advanced programming language, JavaScript also supports all the features necessary to write modular code using functions. You must have seen functions like alert() and write() in the earlier chapters. We were using these functions again and again, but they had been written in core JavaScript only once."
},
{
"code": null,
"e": 60956,
"s": 60830,
"text": "JavaScript allows us to write our own functions as well. This section explains how to write your own functions in JavaScript."
},
{
"code": null,
"e": 61223,
"s": 60956,
"text": "Before we use a function, we need to define it. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces."
},
{
"code": null,
"e": 61255,
"s": 61223,
"text": "The basic syntax is shown here."
},
{
"code": null,
"e": 61391,
"s": 61255,
"text": "<script type = \"text/javascript\">\n <!--\n function functionname(parameter-list) {\n statements\n }\n //-->\n</script>\n"
},
{
"code": null,
"e": 61483,
"s": 61391,
"text": "Try the following example. It defines a function called sayHello that takes no parameters −"
},
{
"code": null,
"e": 61611,
"s": 61483,
"text": "<script type = \"text/javascript\">\n <!--\n function sayHello() {\n alert(\"Hello there\");\n }\n //-->\n</script>"
},
{
"code": null,
"e": 61752,
"s": 61611,
"text": "To invoke a function somewhere later in the script, you would simply need to write the name of that function as shown in the following code."
},
{
"code": null,
"e": 62206,
"s": 61752,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n function sayHello() {\n document.write (\"Hello there!\");\n }\n </script>\n \n </head>\n \n <body>\n <p>Click the following button to call the function</p> \n <form>\n <input type = \"button\" onclick = \"sayHello()\" value = \"Say Hello\">\n </form> \n <p>Use different text in write method and then try...</p>\n </body>\n</html>"
},
{
"code": null,
"e": 62254,
"s": 62206,
"text": "Click the following button to call the function"
},
{
"code": null,
"e": 62305,
"s": 62254,
"text": "Use different text in write method and then try..."
},
{
"code": null,
"e": 62613,
"s": 62305,
"text": "Till now, we have seen functions without parameters. But there is a facility to pass different parameters while calling a function. These passed parameters can be captured inside the function and any manipulation can be done over those parameters. A function can take multiple parameters separated by comma."
},
{
"code": null,
"e": 62714,
"s": 62613,
"text": "Try the following example. We have modified our sayHello function here. Now it takes two parameters."
},
{
"code": null,
"e": 63216,
"s": 62714,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n function sayHello(name, age) {\n document.write (name + \" is \" + age + \" years old.\");\n }\n </script> \n </head>\n \n <body>\n <p>Click the following button to call the function</p> \n <form>\n <input type = \"button\" onclick = \"sayHello('Zara', 7)\" value = \"Say Hello\">\n </form> \n <p>Use different parameters inside the function and then try...</p>\n </body>\n</html>"
},
{
"code": null,
"e": 63264,
"s": 63216,
"text": "Click the following button to call the function"
},
{
"code": null,
"e": 63325,
"s": 63264,
"text": "Use different parameters inside the function and then try..."
},
{
"code": null,
"e": 63509,
"s": 63325,
"text": "A JavaScript function can have an optional return statement. This is required if you want to return a value from a function. This statement should be the last statement in a function."
},
{
"code": null,
"e": 63654,
"s": 63509,
"text": "For example, you can pass two numbers in a function and then you can expect the function to return their multiplication in your calling program."
},
{
"code": null,
"e": 63806,
"s": 63654,
"text": "Try the following example. It defines a function that takes two parameters and concatenates them before returning the resultant in the calling program."
},
{
"code": null,
"e": 64487,
"s": 63806,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n function concatenate(first, last) {\n var full;\n full = first + last;\n return full;\n }\n function secondFunction() {\n var result;\n result = concatenate('Zara', 'Ali');\n document.write (result );\n }\n </script> \n </head>\n \n <body>\n <p>Click the following button to call the function</p> \n <form>\n <input type = \"button\" onclick = \"secondFunction()\" value = \"Call Function\">\n </form> \n <p>Use different parameters inside the function and then try...</p> \n </body>\n</html>"
},
{
"code": null,
"e": 64535,
"s": 64487,
"text": "Click the following button to call the function"
},
{
"code": null,
"e": 64596,
"s": 64535,
"text": "Use different parameters inside the function and then try..."
},
{
"code": null,
"e": 64718,
"s": 64596,
"text": "There is a lot to learn about JavaScript functions, however we have covered the most important concepts in this tutorial."
},
{
"code": null,
"e": 64746,
"s": 64718,
"text": "JavaScript Nested Functions"
},
{
"code": null,
"e": 64774,
"s": 64746,
"text": "JavaScript Nested Functions"
},
{
"code": null,
"e": 64810,
"s": 64774,
"text": "JavaScript Function( ) Constructor"
},
{
"code": null,
"e": 64846,
"s": 64810,
"text": "JavaScript Function( ) Constructor"
},
{
"code": null,
"e": 64875,
"s": 64846,
"text": "JavaScript Function Literals"
},
{
"code": null,
"e": 64904,
"s": 64875,
"text": "JavaScript Function Literals"
},
{
"code": null,
"e": 65025,
"s": 64904,
"text": "JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page."
},
{
"code": null,
"e": 65223,
"s": 65025,
"text": "When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other examples include events like pressing any key, closing a window, resizing a window, etc."
},
{
"code": null,
"e": 65442,
"s": 65223,
"text": "Developers can use these events to execute JavaScript coded responses, which cause buttons to close windows, messages to be displayed to users, data to be validated, and virtually any other type of response imaginable."
},
{
"code": null,
"e": 65586,
"s": 65442,
"text": "Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of events which can trigger JavaScript Code."
},
{
"code": null,
"e": 65761,
"s": 65586,
"text": "Please go through this small tutorial for a better understanding HTML Event Reference. Here we will see a few examples to understand a relation between Event and JavaScript −"
},
{
"code": null,
"e": 65935,
"s": 65761,
"text": "This is the most frequently used event type which occurs when a user clicks the left button of his mouse. You can put your validation, warning etc., against this event type."
},
{
"code": null,
"e": 65962,
"s": 65935,
"text": "Try the following example."
},
{
"code": null,
"e": 66373,
"s": 65962,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n function sayHello() {\n alert(\"Hello World\")\n }\n //-->\n </script> \n </head>\n \n <body>\n <p>Click the following button and see result</p> \n <form>\n <input type = \"button\" onclick = \"sayHello()\" value = \"Say Hello\" />\n </form> \n </body>\n</html>"
},
{
"code": null,
"e": 66415,
"s": 66373,
"text": "Click the following button and see result"
},
{
"code": null,
"e": 66537,
"s": 66415,
"text": "onsubmit is an event that occurs when you try to submit a form. You can put your form validation against this event type."
},
{
"code": null,
"e": 66780,
"s": 66537,
"text": "The following example shows how to use onsubmit. Here we are calling a validate() function before submitting a form data to the webserver. If validate() function returns true, the form will be submitted, otherwise it will not submit the data."
},
{
"code": null,
"e": 66807,
"s": 66780,
"text": "Try the following example."
},
{
"code": null,
"e": 67289,
"s": 66807,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n function validation() {\n all validation goes here\n .........\n return either true or false\n }\n //-->\n </script> \n </head>\n \n <body> \n <form method = \"POST\" action = \"t.cgi\" onsubmit = \"return validate()\">\n .......\n <input type = \"submit\" value = \"Submit\" />\n </form> \n </body>\n</html>"
},
{
"code": null,
"e": 67561,
"s": 67289,
"text": "These two event types will help you create nice effects with images or even with text as well. The onmouseover event triggers when you bring your mouse over any element and the onmouseout triggers when you move your mouse out from that element. Try the following example."
},
{
"code": null,
"e": 68119,
"s": 67561,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n function over() {\n document.write (\"Mouse Over\");\n } \n function out() {\n document.write (\"Mouse Out\");\n } \n //-->\n </script> \n </head>\n \n <body>\n <p>Bring your mouse inside the division to see the result:</p> \n <div onmouseover = \"over()\" onmouseout = \"out()\">\n <h2> This is inside the division </h2>\n </div> \n </body>\n</html>"
},
{
"code": null,
"e": 68175,
"s": 68119,
"text": "Bring your mouse inside the division to see the result:"
},
{
"code": null,
"e": 68317,
"s": 68175,
"text": "The standard HTML 5 events are listed here for your reference. Here script indicates a Javascript function to be executed against that event."
},
{
"code": null,
"e": 68651,
"s": 68317,
"text": "Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website, it is required to maintain session information among different pages. For example, one user registration ends after completing many pages. But how to maintain users' session information across all the web pages."
},
{
"code": null,
"e": 68860,
"s": 68651,
"text": "In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics."
},
{
"code": null,
"e": 69242,
"s": 68860,
"text": "Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the browser sends the same cookie to the server for retrieval. Once retrieved, your server knows/remembers what was stored earlier."
},
{
"code": null,
"e": 69309,
"s": 69242,
"text": "Cookies are a plain text data record of 5 variable-length fields −"
},
{
"code": null,
"e": 69429,
"s": 69309,
"text": "Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser."
},
{
"code": null,
"e": 69549,
"s": 69429,
"text": "Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser."
},
{
"code": null,
"e": 69588,
"s": 69549,
"text": "Domain − The domain name of your site."
},
{
"code": null,
"e": 69627,
"s": 69588,
"text": "Domain − The domain name of your site."
},
{
"code": null,
"e": 69774,
"s": 69627,
"text": "Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page."
},
{
"code": null,
"e": 69921,
"s": 69774,
"text": "Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page."
},
{
"code": null,
"e": 70084,
"s": 69921,
"text": "Secure − If this field contains the word \"secure\", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists."
},
{
"code": null,
"e": 70247,
"s": 70084,
"text": "Secure − If this field contains the word \"secure\", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists."
},
{
"code": null,
"e": 70321,
"s": 70247,
"text": "Name=Value − Cookies are set and retrieved in the form of key-value pairs"
},
{
"code": null,
"e": 70395,
"s": 70321,
"text": "Name=Value − Cookies are set and retrieved in the form of key-value pairs"
},
{
"code": null,
"e": 70646,
"s": 70395,
"text": "Cookies were originally designed for CGI programming. The data contained in a cookie is automatically transmitted between the web browser and the web server, so CGI scripts on the server can read and write cookie values that are stored on the client."
},
{
"code": null,
"e": 70831,
"s": 70646,
"text": "JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookies that apply to the current web page."
},
{
"code": null,
"e": 70949,
"s": 70831,
"text": "The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this."
},
{
"code": null,
"e": 71014,
"s": 70949,
"text": "document.cookie = \"key1 = value1;key2 = value2;expires = date\";\n"
},
{
"code": null,
"e": 71222,
"s": 71014,
"text": "Here the expires attribute is optional. If you provide this attribute with a valid date or time, then the cookie will expire on a given date or time and thereafter, the cookies' value will not be accessible."
},
{
"code": null,
"e": 71529,
"s": 71222,
"text": "Note − Cookie values may not include semicolons, commas, or whitespace. For this reason, you may want to use the JavaScript escape() function to encode the value before storing it in the cookie. If you do this, you will also have to use the corresponding unescape() function when you read the cookie value."
},
{
"code": null,
"e": 71592,
"s": 71529,
"text": "Try the following. It sets a customer name in an input cookie."
},
{
"code": null,
"e": 72365,
"s": 71592,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n function WriteCookie() {\n if( document.myform.customer.value == \"\" ) {\n alert(\"Enter some value!\");\n return;\n }\n cookievalue = escape(document.myform.customer.value) + \";\";\n document.cookie = \"name=\" + cookievalue;\n document.write (\"Setting Cookies : \" + \"name=\" + cookievalue );\n }\n //-->\n </script> \n </head>\n \n <body> \n <form name = \"myform\" action = \"\">\n Enter name: <input type = \"text\" name = \"customer\"/>\n <input type = \"button\" value = \"Set Cookie\" onclick = \"WriteCookie();\"/>\n </form> \n </body>\n</html>"
},
{
"code": null,
"e": 72490,
"s": 72365,
"text": "Now your machine has a cookie called name. You can set multiple cookies using multiple key = value pairs separated by comma."
},
{
"code": null,
"e": 72826,
"s": 72490,
"text": "Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name=value pairs separated by semicolons, where name is the name of a cookie and value is its string value."
},
{
"code": null,
"e": 72915,
"s": 72826,
"text": "You can use strings' split() function to break a string into key and values as follows −"
},
{
"code": null,
"e": 72965,
"s": 72915,
"text": "Try the following example to get all the cookies."
},
{
"code": null,
"e": 73962,
"s": 72965,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n function ReadCookie() {\n var allcookies = document.cookie;\n document.write (\"All Cookies : \" + allcookies );\n \n // Get all the cookies pairs in an array\n cookiearray = allcookies.split(';');\n \n // Now take key value pair out of this array\n for(var i=0; i<cookiearray.length; i++) {\n name = cookiearray[i].split('=')[0];\n value = cookiearray[i].split('=')[1];\n document.write (\"Key is : \" + name + \" and Value is : \" + value);\n }\n }\n //-->\n </script> \n </head>\n \n <body> \n <form name = \"myform\" action = \"\">\n <p> click the following button and see the result:</p>\n <input type = \"button\" value = \"Get Cookie\" onclick = \"ReadCookie()\"/>\n </form> \n </body>\n</html>"
},
{
"code": null,
"e": 74131,
"s": 73962,
"text": "Note − Here length is a method of Array class which returns the length of an array. We will discuss Arrays in a separate chapter. By that time, please try to digest it."
},
{
"code": null,
"e": 74179,
"s": 74131,
"text": " click the following button and see the result:"
},
{
"code": null,
"e": 74312,
"s": 74179,
"text": "Note − There may be some other cookies already set on your machine. The above code will display all the cookies set on your machine."
},
{
"code": null,
"e": 74531,
"s": 74312,
"text": "You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiry date within the cookie. This can be done by setting the ‘expires’ attribute to a date and time."
},
{
"code": null,
"e": 74627,
"s": 74531,
"text": "Try the following example. It illustrates how to extend the expiry date of a cookie by 1 Month."
},
{
"code": null,
"e": 75420,
"s": 74627,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n function WriteCookie() {\n var now = new Date();\n now.setMonth( now.getMonth() + 1 );\n cookievalue = escape(document.myform.customer.value) + \";\"\n \n document.cookie = \"name=\" + cookievalue;\n document.cookie = \"expires=\" + now.toUTCString() + \";\"\n document.write (\"Setting Cookies : \" + \"name=\" + cookievalue );\n }\n //-->\n </script> \n </head>\n \n <body>\n <form name = \"myform\" action = \"\">\n Enter name: <input type = \"text\" name = \"customer\"/>\n <input type = \"button\" value = \"Set Cookie\" onclick = \"WriteCookie()\"/>\n </form> \n </body>\n</html>"
},
{
"code": null,
"e": 75598,
"s": 75420,
"text": "Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiry date to a time in the past."
},
{
"code": null,
"e": 75728,
"s": 75598,
"text": "Try the following example. It illustrates how to delete a cookie by setting its expiry date to one month behind the current date."
},
{
"code": null,
"e": 76521,
"s": 75728,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n function WriteCookie() {\n var now = new Date();\n now.setMonth( now.getMonth() - 1 );\n cookievalue = escape(document.myform.customer.value) + \";\"\n \n document.cookie = \"name=\" + cookievalue;\n document.cookie = \"expires=\" + now.toUTCString() + \";\"\n document.write(\"Setting Cookies : \" + \"name=\" + cookievalue );\n }\n //-->\n </script> \n </head>\n \n <body>\n <form name = \"myform\" action = \"\">\n Enter name: <input type = \"text\" name = \"customer\"/>\n <input type = \"button\" value = \"Set Cookie\" onclick = \"WriteCookie()\"/>\n </form> \n </body>\n</html>"
},
{
"code": null,
"e": 76746,
"s": 76521,
"text": "You might have encountered a situation where you clicked a URL to reach a page X but internally you were directed to another page Y. It happens due to page redirection. This concept is different from JavaScript Page Refresh."
},
{
"code": null,
"e": 76882,
"s": 76746,
"text": "There could be various reasons why you would like to redirect a user from the original page. We are listing down a few of the reasons −"
},
{
"code": null,
"e": 77186,
"s": 76882,
"text": "You did not like the name of your domain and you are moving to a new one. In such a scenario, you may want to direct all your visitors to the new site. Here you can maintain your old domain but put a single page with a page redirection such that all your old domain visitors can come to your new domain."
},
{
"code": null,
"e": 77490,
"s": 77186,
"text": "You did not like the name of your domain and you are moving to a new one. In such a scenario, you may want to direct all your visitors to the new site. Here you can maintain your old domain but put a single page with a page redirection such that all your old domain visitors can come to your new domain."
},
{
"code": null,
"e": 77745,
"s": 77490,
"text": "You have built-up various pages based on browser versions or their names or may be based on different countries, then instead of using your server-side page redirection, you can use client-side page redirection to land your users on the appropriate page."
},
{
"code": null,
"e": 78000,
"s": 77745,
"text": "You have built-up various pages based on browser versions or their names or may be based on different countries, then instead of using your server-side page redirection, you can use client-side page redirection to land your users on the appropriate page."
},
{
"code": null,
"e": 78316,
"s": 78000,
"text": "The Search Engines may have already indexed your pages. But while moving to another domain, you would not like to lose your visitors coming through search engines. So you can use client-side page redirection. But keep in mind this should not be done to fool the search engine, it could lead your site to get banned."
},
{
"code": null,
"e": 78632,
"s": 78316,
"text": "The Search Engines may have already indexed your pages. But while moving to another domain, you would not like to lose your visitors coming through search engines. So you can use client-side page redirection. But keep in mind this should not be done to fool the search engine, it could lead your site to get banned."
},
{
"code": null,
"e": 78688,
"s": 78632,
"text": "The implementations of Page-Redirection are as follows."
},
{
"code": null,
"e": 78869,
"s": 78688,
"text": "It is quite simple to do a page redirect using JavaScript at client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows."
},
{
"code": null,
"e": 79330,
"s": 78869,
"text": "<html>\n <head>\n <script type = \"text/javascript\">\n <!--\n function Redirect() {\n window.location = \"https://www.tutorialspoint.com\";\n }\n //-->\n </script>\n </head>\n \n <body>\n <p>Click the following button, you will be redirected to home page.</p>\n \n <form>\n <input type = \"button\" value = \"Redirect Me\" onclick = \"Redirect();\" />\n </form>\n \n </body>\n</html>"
},
{
"code": null,
"e": 79395,
"s": 79330,
"text": "Click the following button, you will be redirected to home page."
},
{
"code": null,
"e": 79727,
"s": 79395,
"text": "You can show an appropriate message to your site visitors before redirecting them to a new page. This would need a bit time delay to load a new page. The following example shows how to implement the same. Here setTimeout() is a built-in JavaScript function which can be used to execute another function after a given time interval."
},
{
"code": null,
"e": 80123,
"s": 79727,
"text": "<html>\n <head>\n <script type = \"text/javascript\">\n <!--\n function Redirect() {\n window.location = \"https://www.tutorialspoint.com\";\n } \n document.write(\"You will be redirected to main page in 10 sec.\");\n setTimeout('Redirect()', 10000);\n //-->\n </script>\n </head>\n \n <body>\n </body>\n</html>"
},
{
"code": null,
"e": 80194,
"s": 80123,
"text": "You will be redirected to tutorialspoint.com main page in 10 seconds!\n"
},
{
"code": null,
"e": 80304,
"s": 80194,
"text": "The following example shows how to redirect your site visitors onto a different page based on their browsers."
},
{
"code": null,
"e": 80866,
"s": 80304,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n var browsername = navigator.appName;\n if( browsername == \"Netscape\" ) {\n window.location = \"http://www.location.com/ns.htm\";\n } else if ( browsername ==\"Microsoft Internet Explorer\") {\n window.location = \"http://www.location.com/ie.htm\";\n } else {\n window.location = \"http://www.location.com/other.htm\";\n }\n //-->\n </script> \n </head>\n \n <body>\n </body>\n</html>"
},
{
"code": null,
"e": 81104,
"s": 80866,
"text": "JavaScript supports three important types of dialog boxes. These dialog boxes can be used to raise and alert, or to get confirmation on any input or to have a kind of input from the users. Here we will discuss each dialog box one by one."
},
{
"code": null,
"e": 81362,
"s": 81104,
"text": "An alert dialog box is mostly used to give a warning message to the users. For example, if one input field requires to enter some text but the user does not provide any input, then as a part of validation, you can use an alert box to give a warning message."
},
{
"code": null,
"e": 81491,
"s": 81362,
"text": "Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one button \"OK\" to select and proceed."
},
{
"code": null,
"e": 81976,
"s": 81491,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n function Warn() {\n alert (\"This is a warning message!\");\n document.write (\"This is a warning message!\");\n }\n //-->\n </script> \n </head>\n \n <body>\n <p>Click the following button to see the result: </p> \n <form>\n <input type = \"button\" value = \"Click Me\" onclick = \"Warn();\" />\n </form> \n </body>\n</html>"
},
{
"code": null,
"e": 82023,
"s": 81976,
"text": "Click the following button to see the result: "
},
{
"code": null,
"e": 82160,
"s": 82023,
"text": "A confirmation dialog box is mostly used to take user's consent on any option. It displays a dialog box with two buttons: OK and Cancel."
},
{
"code": null,
"e": 82364,
"s": 82160,
"text": "If the user clicks on the OK button, the window method confirm() will return true. If the user clicks on the Cancel button, then confirm() returns false. You can use a confirmation dialog box as follows."
},
{
"code": null,
"e": 83097,
"s": 82364,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n function getConfirmation() {\n var retVal = confirm(\"Do you want to continue ?\");\n if( retVal == true ) {\n document.write (\"User wants to continue!\");\n return true;\n } else {\n document.write (\"User does not want to continue!\");\n return false;\n }\n }\n //-->\n </script> \n </head>\n \n <body>\n <p>Click the following button to see the result: </p> \n <form>\n <input type = \"button\" value = \"Click Me\" onclick = \"getConfirmation();\" />\n </form> \n </body>\n</html>"
},
{
"code": null,
"e": 83144,
"s": 83097,
"text": "Click the following button to see the result: "
},
{
"code": null,
"e": 83338,
"s": 83144,
"text": "The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus, it enables you to interact with the user. The user needs to fill in the field and then click OK."
},
{
"code": null,
"e": 83534,
"s": 83338,
"text": "This dialog box is displayed using a method called prompt() which takes two parameters: (i) a label which you want to display in the text box and (ii) a default string to display in the text box."
},
{
"code": null,
"e": 83771,
"s": 83534,
"text": "This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window method prompt() will return the entered value from the text box. If the user clicks the Cancel button, the window method prompt() returns null."
},
{
"code": null,
"e": 83832,
"s": 83771,
"text": "The following example shows how to use a prompt dialog box −"
},
{
"code": null,
"e": 84353,
"s": 83832,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n function getValue() {\n var retVal = prompt(\"Enter your name : \", \"your name here\");\n document.write(\"You have entered : \" + retVal);\n }\n //-->\n </script> \n </head>\n \n <body>\n <p>Click the following button to see the result: </p> \n <form>\n <input type = \"button\" value = \"Click Me\" onclick = \"getValue();\" />\n </form> \n </body>\n</html>"
},
{
"code": null,
"e": 84400,
"s": 84353,
"text": "Click the following button to see the result: "
},
{
"code": null,
"e": 84628,
"s": 84400,
"text": "void is an important keyword in JavaScript which can be used as a unary operator that appears before its single operand, which may be of any type. This operator specifies an expression to be evaluated without returning a value."
},
{
"code": null,
"e": 84684,
"s": 84628,
"text": "The syntax of void can be either of the following two −"
},
{
"code": null,
"e": 84894,
"s": 84684,
"text": "<head>\n <script type = \"text/javascript\">\n <!--\n void func()\n javascript:void func()\n or:\n void(func())\n javascript:void(func())\n //-->\n </script>\n</head>\n"
},
{
"code": null,
"e": 85105,
"s": 84894,
"text": "The most common use of this operator is in a client-side javascript: URL, where it allows you to evaluate an expression for its side-effects without the browser displaying the value of the evaluated expression."
},
{
"code": null,
"e": 85213,
"s": 85105,
"text": "Here the expression alert ('Warning!!!') is evaluated but it is not loaded back into the current document −"
},
{
"code": null,
"e": 85506,
"s": 85213,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n //-->\n </script> \n </head>\n \n <body> \n <p>Click the following, This won't react at all...</p>\n <a href = \"javascript:void(alert('Warning!!!'))\">Click me!</a> \n </body>\n</html>"
},
{
"code": null,
"e": 85554,
"s": 85506,
"text": "Click the following, This won't react at all..."
},
{
"code": null,
"e": 85771,
"s": 85554,
"text": "Take a look at the following example. The following link does nothing because the expression \"0\" has no effect in JavaScript. Here the expression \"0\" is evaluated, but it is not loaded back into the current document."
},
{
"code": null,
"e": 86047,
"s": 85771,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n //-->\n </script> \n </head>\n \n <body> \n <p>Click the following, This won't react at all...</p>\n <a href = \"javascript:void(0)\">Click me!</a> \n </body>\n</html>"
},
{
"code": null,
"e": 86095,
"s": 86047,
"text": "Click the following, This won't react at all..."
},
{
"code": null,
"e": 86172,
"s": 86095,
"text": "Another use of void is to purposely generate the undefined value as follows."
},
{
"code": null,
"e": 86695,
"s": 86172,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n function getValue() {\n var a,b,c;\n \n a = void ( b = 5, c = 7 );\n document.write('a = ' + a + ' b = ' + b +' c = ' + c );\n }\n //-->\n </script> \n </head>\n \n <body>\n <p>Click the following to see the result:</p>\n <form>\n <input type = \"button\" value = \"Click Me\" onclick = \"getValue();\" />\n </form> \n </body>\n</html>"
},
{
"code": null,
"e": 86734,
"s": 86695,
"text": "Click the following to see the result:"
},
{
"code": null,
"e": 86951,
"s": 86734,
"text": "Many times you would like to place a button on your webpage to print the content of that web page via an actual printer. JavaScript helps you to implement this functionality using the print function of window object."
},
{
"code": null,
"e": 87134,
"s": 86951,
"text": "The JavaScript print function window.print() prints the current web page when executed. You can call this function directly using the onclick event as shown in the following example."
},
{
"code": null,
"e": 87161,
"s": 87134,
"text": "Try the following example."
},
{
"code": null,
"e": 87426,
"s": 87161,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n //-->\n </script>\n </head>\n \n <body> \n <form>\n <input type = \"button\" value = \"Print\" onclick = \"window.print()\" />\n </form> \n </body>\n<html>"
},
{
"code": null,
"e": 87603,
"s": 87426,
"text": "Although it serves the purpose of getting a printout, it is not a recommended way. A printer friendly page is really just a page with text, no images, graphics, or advertising."
},
{
"code": null,
"e": 87664,
"s": 87603,
"text": "You can make a page printer friendly in the following ways −"
},
{
"code": null,
"e": 87804,
"s": 87664,
"text": "Make a copy of the page and leave out unwanted text and graphics, then link to that printer friendly page from the original. Check Example."
},
{
"code": null,
"e": 87944,
"s": 87804,
"text": "Make a copy of the page and leave out unwanted text and graphics, then link to that printer friendly page from the original. Check Example."
},
{
"code": null,
"e": 88325,
"s": 87944,
"text": "If you do not want to keep an extra copy of a page, then you can mark your printable text using proper comments like <!-- PRINT STARTS HERE -->..... <!-- PRINT ENDS HERE --> and then you can use PERL or any other script in the background to purge printable text and display for final printing. We at Tutorialspoint use this method to provide print facility to our site visitors. \n"
},
{
"code": null,
"e": 88705,
"s": 88325,
"text": "If you do not want to keep an extra copy of a page, then you can mark your printable text using proper comments like <!-- PRINT STARTS HERE -->..... <!-- PRINT ENDS HERE --> and then you can use PERL or any other script in the background to purge printable text and display for final printing. We at Tutorialspoint use this method to provide print facility to our site visitors. "
},
{
"code": null,
"e": 88862,
"s": 88705,
"text": "If you don’t find the above facilities on a web page, then you can use the browser's standard toolbar to get print the web page. Follow the link as follows."
},
{
"code": null,
"e": 88897,
"s": 88862,
"text": "File → Print → Click OK button.\n"
},
{
"code": null,
"e": 89066,
"s": 88897,
"text": "JavaScript is an Object Oriented Programming (OOP) language. A programming language can be called object-oriented if it provides four basic capabilities to developers −"
},
{
"code": null,
"e": 89175,
"s": 89066,
"text": "Encapsulation − the capability to store related information, whether data or methods, together in an object."
},
{
"code": null,
"e": 89284,
"s": 89175,
"text": "Encapsulation − the capability to store related information, whether data or methods, together in an object."
},
{
"code": null,
"e": 89356,
"s": 89284,
"text": "Aggregation − the capability to store one object inside another object."
},
{
"code": null,
"e": 89428,
"s": 89356,
"text": "Aggregation − the capability to store one object inside another object."
},
{
"code": null,
"e": 89558,
"s": 89428,
"text": "Inheritance − the capability of a class to rely upon another class (or number of classes) for some of its properties and methods."
},
{
"code": null,
"e": 89688,
"s": 89558,
"text": "Inheritance − the capability of a class to rely upon another class (or number of classes) for some of its properties and methods."
},
{
"code": null,
"e": 89793,
"s": 89688,
"text": "Polymorphism − the capability to write one function or method that works in a variety of different ways."
},
{
"code": null,
"e": 89898,
"s": 89793,
"text": "Polymorphism − the capability to write one function or method that works in a variety of different ways."
},
{
"code": null,
"e": 90068,
"s": 89898,
"text": "Objects are composed of attributes. If an attribute contains a function, it is considered to be a method of the object, otherwise the attribute is considered a property."
},
{
"code": null,
"e": 90359,
"s": 90068,
"text": "Object properties can be any of the three primitive data types, or any of the abstract data types, such as another object. Object properties are usually variables that are used internally in the object's methods, but can also be globally visible variables that are used throughout the page."
},
{
"code": null,
"e": 90410,
"s": 90359,
"text": "The syntax for adding a property to an object is −"
},
{
"code": null,
"e": 90454,
"s": 90410,
"text": "objectName.objectProperty = propertyValue;\n"
},
{
"code": null,
"e": 90562,
"s": 90454,
"text": "For example − The following code gets the document title using the \"title\" property of the document object."
},
{
"code": null,
"e": 90589,
"s": 90562,
"text": "var str = document.title;\n"
},
{
"code": null,
"e": 90872,
"s": 90589,
"text": "Methods are the functions that let the object do something or let something be done to it. There is a small difference between a function and a method – at a function is a standalone unit of statements and a method is attached to an object and can be referenced by the this keyword."
},
{
"code": null,
"e": 91056,
"s": 90872,
"text": "Methods are useful for everything from displaying the contents of the object to the screen to performing complex mathematical operations on a group of local properties and parameters."
},
{
"code": null,
"e": 91195,
"s": 91056,
"text": "For example − Following is a simple example to show how to use the write() method of document object to write any content on the document."
},
{
"code": null,
"e": 91228,
"s": 91195,
"text": "document.write(\"This is test\");\n"
},
{
"code": null,
"e": 91318,
"s": 91228,
"text": "All user-defined objects and built-in objects are descendants of an object called Object."
},
{
"code": null,
"e": 91456,
"s": 91318,
"text": "The new operator is used to create an instance of an object. To create an object, the new operator is followed by the constructor method."
},
{
"code": null,
"e": 91595,
"s": 91456,
"text": "In the following example, the constructor methods are Object(), Array(), and Date(). These constructors are built-in JavaScript functions."
},
{
"code": null,
"e": 91709,
"s": 91595,
"text": "var employee = new Object();\nvar books = new Array(\"C++\", \"Perl\", \"Java\");\nvar day = new Date(\"August 15, 1947\");"
},
{
"code": null,
"e": 91937,
"s": 91709,
"text": "A constructor is a function that creates and initializes an object. JavaScript provides a special constructor function called Object() to build the object. The return value of the Object() constructor is assigned to a variable."
},
{
"code": null,
"e": 92088,
"s": 91937,
"text": "The variable contains a reference to the new object. The properties assigned to the object are not variables and are not defined with the var keyword."
},
{
"code": null,
"e": 92156,
"s": 92088,
"text": "Try the following example; it demonstrates how to create an Object."
},
{
"code": null,
"e": 92689,
"s": 92156,
"text": "<html>\n <head>\n <title>User-defined objects</title> \n <script type = \"text/javascript\">\n var book = new Object(); // Create the object\n book.subject = \"Perl\"; // Assign properties to the object\n book.author = \"Mohtashim\";\n </script> \n </head>\n \n <body> \n <script type = \"text/javascript\">\n document.write(\"Book name is : \" + book.subject + \"<br>\");\n document.write(\"Book author is : \" + book.author + \"<br>\");\n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 92738,
"s": 92689,
"text": "Book name is : Perl \nBook author is : Mohtashim\n"
},
{
"code": null,
"e": 92903,
"s": 92738,
"text": "This example demonstrates how to create an object with a User-Defined Function. Here this keyword is used to refer to the object that has been passed to a function."
},
{
"code": null,
"e": 93445,
"s": 92903,
"text": "<html>\n <head> \n <title>User-defined objects</title>\n <script type = \"text/javascript\">\n function book(title, author) {\n this.title = title; \n this.author = author;\n }\n </script> \n </head>\n \n <body> \n <script type = \"text/javascript\">\n var myBook = new book(\"Perl\", \"Mohtashim\");\n document.write(\"Book title is : \" + myBook.title + \"<br>\");\n document.write(\"Book author is : \" + myBook.author + \"<br>\");\n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 93495,
"s": 93445,
"text": "Book title is : Perl \nBook author is : Mohtashim\n"
},
{
"code": null,
"e": 93672,
"s": 93495,
"text": "The previous examples demonstrate how the constructor creates the object and assigns properties. But we need to complete the definition of an object by assigning methods to it."
},
{
"code": null,
"e": 93752,
"s": 93672,
"text": "Try the following example; it shows how to add a function along with an object."
},
{
"code": null,
"e": 94628,
"s": 93752,
"text": "<html>\n \n <head>\n <title>User-defined objects</title>\n <script type = \"text/javascript\">\n // Define a function which will work as a method\n function addPrice(amount) {\n this.price = amount; \n }\n \n function book(title, author) {\n this.title = title;\n this.author = author;\n this.addPrice = addPrice; // Assign that method as property.\n }\n </script> \n </head>\n \n <body> \n <script type = \"text/javascript\">\n var myBook = new book(\"Perl\", \"Mohtashim\");\n myBook.addPrice(100);\n \n document.write(\"Book title is : \" + myBook.title + \"<br>\");\n document.write(\"Book author is : \" + myBook.author + \"<br>\");\n document.write(\"Book price is : \" + myBook.price + \"<br>\");\n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 94699,
"s": 94628,
"text": "Book title is : Perl \nBook author is : Mohtashim \nBook price is : 100\n"
},
{
"code": null,
"e": 94800,
"s": 94699,
"text": "The ‘with’ keyword is used as a kind of shorthand for referencing an object's properties or methods."
},
{
"code": null,
"e": 94996,
"s": 94800,
"text": "The object specified as an argument to with becomes the default object for the duration of the block that follows. The properties and methods for the object can be used without naming the object."
},
{
"code": null,
"e": 95039,
"s": 94996,
"text": "The syntax for with object is as follows −"
},
{
"code": null,
"e": 95109,
"s": 95039,
"text": "with (object) {\n properties used without the object name and dot\n}\n"
},
{
"code": null,
"e": 95136,
"s": 95109,
"text": "Try the following example."
},
{
"code": null,
"e": 96064,
"s": 95136,
"text": "<html>\n <head>\n <title>User-defined objects</title> \n <script type = \"text/javascript\">\n // Define a function which will work as a method\n function addPrice(amount) {\n with(this) {\n price = amount;\n }\n }\n function book(title, author) {\n this.title = title;\n this.author = author;\n this.price = 0;\n this.addPrice = addPrice; // Assign that method as property.\n }\n </script> \n </head>\n \n <body> \n <script type = \"text/javascript\">\n var myBook = new book(\"Perl\", \"Mohtashim\");\n myBook.addPrice(100);\n \n document.write(\"Book title is : \" + myBook.title + \"<br>\");\n document.write(\"Book author is : \" + myBook.author + \"<br>\");\n document.write(\"Book price is : \" + myBook.price + \"<br>\");\n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 96135,
"s": 96064,
"text": "Book title is : Perl \nBook author is : Mohtashim \nBook price is : 100\n"
},
{
"code": null,
"e": 96315,
"s": 96135,
"text": "JavaScript has several built-in or native objects. These objects are accessible anywhere in your program and will work the same way in any browser running in any operating system."
},
{
"code": null,
"e": 96377,
"s": 96315,
"text": "Here is the list of all important JavaScript Native Objects −"
},
{
"code": null,
"e": 96402,
"s": 96377,
"text": "JavaScript Number Object"
},
{
"code": null,
"e": 96427,
"s": 96402,
"text": "JavaScript Number Object"
},
{
"code": null,
"e": 96453,
"s": 96427,
"text": "JavaScript Boolean Object"
},
{
"code": null,
"e": 96479,
"s": 96453,
"text": "JavaScript Boolean Object"
},
{
"code": null,
"e": 96504,
"s": 96479,
"text": "JavaScript String Object"
},
{
"code": null,
"e": 96529,
"s": 96504,
"text": "JavaScript String Object"
},
{
"code": null,
"e": 96553,
"s": 96529,
"text": "JavaScript Array Object"
},
{
"code": null,
"e": 96577,
"s": 96553,
"text": "JavaScript Array Object"
},
{
"code": null,
"e": 96600,
"s": 96577,
"text": "JavaScript Date Object"
},
{
"code": null,
"e": 96623,
"s": 96600,
"text": "JavaScript Date Object"
},
{
"code": null,
"e": 96646,
"s": 96623,
"text": "JavaScript Math Object"
},
{
"code": null,
"e": 96669,
"s": 96646,
"text": "JavaScript Math Object"
},
{
"code": null,
"e": 96694,
"s": 96669,
"text": "JavaScript RegExp Object"
},
{
"code": null,
"e": 96719,
"s": 96694,
"text": "JavaScript RegExp Object"
},
{
"code": null,
"e": 96958,
"s": 96719,
"text": "The Number object represents numerical date, either integers or floating-point numbers. In general, you do not need to worry about Number objects because the browser automatically converts number literals to instances of the number class."
},
{
"code": null,
"e": 97014,
"s": 96958,
"text": "The syntax for creating a number object is as follows −"
},
{
"code": null,
"e": 97045,
"s": 97014,
"text": "var val = new Number(number);\n"
},
{
"code": null,
"e": 97193,
"s": 97045,
"text": "In the place of number, if you provide any non-number argument, then the argument cannot be converted into a number, it returns NaN (Not-a-Number)."
},
{
"code": null,
"e": 97248,
"s": 97193,
"text": "Here is a list of each property and their description."
},
{
"code": null,
"e": 97331,
"s": 97248,
"text": "The largest possible value a number in JavaScript can have 1.7976931348623157E+308"
},
{
"code": null,
"e": 97398,
"s": 97331,
"text": "The smallest possible value a number in JavaScript can have 5E-324"
},
{
"code": null,
"e": 97437,
"s": 97398,
"text": "Equal to a value that is not a number."
},
{
"code": null,
"e": 97474,
"s": 97437,
"text": "A value that is less than MIN_VALUE."
},
{
"code": null,
"e": 97513,
"s": 97474,
"text": "A value that is greater than MAX_VALUE"
},
{
"code": null,
"e": 97662,
"s": 97513,
"text": "A static property of the Number object. Use the prototype property to assign new properties and methods to the Number object in the current document"
},
{
"code": null,
"e": 97758,
"s": 97662,
"text": "Returns the function that created this object's instance. By default this is the Number object."
},
{
"code": null,
"e": 97854,
"s": 97758,
"text": "In the following sections, we will take a few examples to demonstrate the properties of Number."
},
{
"code": null,
"e": 97952,
"s": 97854,
"text": "The Number object contains only the default methods that are a part of every object's definition."
},
{
"code": null,
"e": 98092,
"s": 97952,
"text": "Forces a number to display in exponential notation, even if the number is in the range in which JavaScript normally uses standard notation."
},
{
"code": null,
"e": 98171,
"s": 98092,
"text": "Formats a number with a specific number of digits to the right of the decimal."
},
{
"code": null,
"e": 98291,
"s": 98171,
"text": "Returns a string value version of the current number in a format that may vary according to a browser's local settings."
},
{
"code": null,
"e": 98401,
"s": 98291,
"text": "Defines how many total digits (including digits to the left and right of the decimal) to display of a number."
},
{
"code": null,
"e": 98458,
"s": 98401,
"text": "Returns the string representation of the number's value."
},
{
"code": null,
"e": 98486,
"s": 98458,
"text": "Returns the number's value."
},
{
"code": null,
"e": 98575,
"s": 98486,
"text": "In the following sections, we will have a few examples to explain the methods of Number."
},
{
"code": null,
"e": 98783,
"s": 98575,
"text": "The Boolean object represents two values, either \"true\" or \"false\". If value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (\"\"), the object has an initial value of false."
},
{
"code": null,
"e": 98836,
"s": 98783,
"text": "Use the following syntax to create a boolean object."
},
{
"code": null,
"e": 98867,
"s": 98836,
"text": "var val = new Boolean(value);\n"
},
{
"code": null,
"e": 98920,
"s": 98867,
"text": "Here is a list of the properties of Boolean object −"
},
{
"code": null,
"e": 98989,
"s": 98920,
"text": "Returns a reference to the Boolean function that created the object."
},
{
"code": null,
"e": 99067,
"s": 98989,
"text": "The prototype property allows you to add properties and methods to an object."
},
{
"code": null,
"e": 99170,
"s": 99067,
"text": "In the following sections, we will have a few examples to illustrate the properties of Boolean object."
},
{
"code": null,
"e": 99241,
"s": 99170,
"text": "Here is a list of the methods of Boolean object and their description."
},
{
"code": null,
"e": 99359,
"s": 99241,
"text": "Returns a string containing the source of the Boolean object; you can use this string to create an equivalent object."
},
{
"code": null,
"e": 99444,
"s": 99359,
"text": "Returns a string of either \"true\" or \"false\" depending upon the value of the object."
},
{
"code": null,
"e": 99495,
"s": 99444,
"text": "Returns the primitive value of the Boolean object."
},
{
"code": null,
"e": 99599,
"s": 99495,
"text": "In the following sections, we will have a few examples to demonstrate the usage of the Boolean methods."
},
{
"code": null,
"e": 99742,
"s": 99599,
"text": "The String object lets you work with a series of characters; it wraps Javascript's string primitive data type with a number of helper methods."
},
{
"code": null,
"e": 99908,
"s": 99742,
"text": "As JavaScript automatically converts between string primitives and String objects, you can call any of the helper methods of the String object on a string primitive."
},
{
"code": null,
"e": 99961,
"s": 99908,
"text": "Use the following syntax to create a String object −"
},
{
"code": null,
"e": 99992,
"s": 99961,
"text": "var val = new String(string);\n"
},
{
"code": null,
"e": 100071,
"s": 99992,
"text": "The String parameter is a series of characters that has been properly encoded."
},
{
"code": null,
"e": 100144,
"s": 100071,
"text": "Here is a list of the properties of String object and their description."
},
{
"code": null,
"e": 100212,
"s": 100144,
"text": "Returns a reference to the String function that created the object."
},
{
"code": null,
"e": 100246,
"s": 100212,
"text": "Returns the length of the string."
},
{
"code": null,
"e": 100324,
"s": 100246,
"text": "The prototype property allows you to add properties and methods to an object."
},
{
"code": null,
"e": 100426,
"s": 100324,
"text": "In the following sections, we will have a few examples to demonstrate the usage of String properties."
},
{
"code": null,
"e": 100513,
"s": 100426,
"text": "Here is a list of the methods available in String object along with their description."
},
{
"code": null,
"e": 100559,
"s": 100513,
"text": "Returns the character at the specified index."
},
{
"code": null,
"e": 100642,
"s": 100559,
"text": "Returns a number indicating the Unicode value of the character at the given index."
},
{
"code": null,
"e": 100701,
"s": 100642,
"text": "Combines the text of two strings and returns a new string."
},
{
"code": null,
"e": 100820,
"s": 100701,
"text": "Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found."
},
{
"code": null,
"e": 100938,
"s": 100820,
"text": "Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found."
},
{
"code": null,
"e": 101065,
"s": 100938,
"text": "Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order."
},
{
"code": null,
"e": 101118,
"s": 101065,
"text": "Used to match a regular expression against a string."
},
{
"code": null,
"e": 101241,
"s": 101118,
"text": "Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring."
},
{
"code": null,
"e": 101326,
"s": 101241,
"text": "Executes the search for a match between a regular expression and a specified string."
},
{
"code": null,
"e": 101383,
"s": 101326,
"text": "Extracts a section of a string and returns a new string."
},
{
"code": null,
"e": 101473,
"s": 101383,
"text": "Splits a String object into an array of strings by separating the string into substrings."
},
{
"code": null,
"e": 101588,
"s": 101473,
"text": "Returns the characters in a string beginning at the specified location through the specified number of characters."
},
{
"code": null,
"e": 101660,
"s": 101588,
"text": "Returns the characters in a string between two indexes into the string."
},
{
"code": null,
"e": 101756,
"s": 101660,
"text": "The characters within a string are converted to lower case while respecting the current locale."
},
{
"code": null,
"e": 101852,
"s": 101756,
"text": "The characters within a string are converted to upper case while respecting the current locale."
},
{
"code": null,
"e": 101910,
"s": 101852,
"text": "Returns the calling string value converted to lower case."
},
{
"code": null,
"e": 101962,
"s": 101910,
"text": "Returns a string representing the specified object."
},
{
"code": null,
"e": 102019,
"s": 101962,
"text": "Returns the calling string value converted to uppercase."
},
{
"code": null,
"e": 102072,
"s": 102019,
"text": "Returns the primitive value of the specified object."
},
{
"code": null,
"e": 102175,
"s": 102072,
"text": "Here is a list of the methods that return a copy of the string wrapped inside an appropriate HTML tag."
},
{
"code": null,
"e": 102234,
"s": 102175,
"text": "Creates an HTML anchor that is used as a hypertext target."
},
{
"code": null,
"e": 102311,
"s": 102234,
"text": "Creates a string to be displayed in a big font as if it were in a <big> tag."
},
{
"code": null,
"e": 102369,
"s": 102311,
"text": "Creates a string to blink as if it were in a <blink> tag."
},
{
"code": null,
"e": 102438,
"s": 102369,
"text": "Creates a string to be displayed as bold as if it were in a <b> tag."
},
{
"code": null,
"e": 102518,
"s": 102438,
"text": "Causes a string to be displayed in fixed-pitch font as if it were in a <tt> tag"
},
{
"code": null,
"e": 102618,
"s": 102518,
"text": "Causes a string to be displayed in the specified color as if it were in a <font color=\"color\"> tag."
},
{
"code": null,
"e": 102720,
"s": 102618,
"text": "Causes a string to be displayed in the specified font size as if it were in a <font size=\"size\"> tag."
},
{
"code": null,
"e": 102779,
"s": 102720,
"text": "Causes a string to be italic, as if it were in an <i> tag."
},
{
"code": null,
"e": 102837,
"s": 102779,
"text": "Creates an HTML hypertext link that requests another URL."
},
{
"code": null,
"e": 102918,
"s": 102837,
"text": "Causes a string to be displayed in a small font, as if it were in a <small> tag."
},
{
"code": null,
"e": 103003,
"s": 102918,
"text": "Causes a string to be displayed as struck-out text, as if it were in a <strike> tag."
},
{
"code": null,
"e": 103080,
"s": 103003,
"text": "Causes a string to be displayed as a subscript, as if it were in a <sub> tag"
},
{
"code": null,
"e": 103159,
"s": 103080,
"text": "Causes a string to be displayed as a superscript, as if it were in a <sup> tag"
},
{
"code": null,
"e": 103258,
"s": 103159,
"text": "In the following sections, we will have a few examples to demonstrate the usage of String methods."
},
{
"code": null,
"e": 103547,
"s": 103258,
"text": "The Array object lets you store multiple values in a single variable. It stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type."
},
{
"code": null,
"e": 103600,
"s": 103547,
"text": "Use the following syntax to create an Array object −"
},
{
"code": null,
"e": 103655,
"s": 103600,
"text": "var fruits = new Array( \"apple\", \"orange\", \"mango\" );\n"
},
{
"code": null,
"e": 103884,
"s": 103655,
"text": "The Array parameter is a list of strings or integers. When you specify a single numeric parameter with the Array constructor, you specify the initial length of the array. The maximum length allowed for an array is 4,294,967,295."
},
{
"code": null,
"e": 103945,
"s": 103884,
"text": "You can create array by simply assigning values as follows −"
},
{
"code": null,
"e": 103990,
"s": 103945,
"text": "var fruits = [ \"apple\", \"orange\", \"mango\" ];"
},
{
"code": null,
"e": 104075,
"s": 103990,
"text": "You will use ordinal numbers to access and to set values inside an array as follows."
},
{
"code": null,
"e": 104170,
"s": 104075,
"text": "fruits[0] is the first element\nfruits[1] is the second element\nfruits[2] is the third element\n"
},
{
"code": null,
"e": 104253,
"s": 104170,
"text": "Here is a list of the properties of the Array object along with their description."
},
{
"code": null,
"e": 104320,
"s": 104253,
"text": "Returns a reference to the array function that created the object."
},
{
"code": null,
"e": 104326,
"s": 104320,
"text": "index"
},
{
"code": null,
"e": 104398,
"s": 104326,
"text": "The property represents the zero-based index of the match in the string"
},
{
"code": null,
"e": 104404,
"s": 104398,
"text": "input"
},
{
"code": null,
"e": 104483,
"s": 104404,
"text": "This property is only present in arrays created by regular expression matches."
},
{
"code": null,
"e": 104528,
"s": 104483,
"text": "Reflects the number of elements in an array."
},
{
"code": null,
"e": 104606,
"s": 104528,
"text": "The prototype property allows you to add properties and methods to an object."
},
{
"code": null,
"e": 104706,
"s": 104606,
"text": "In the following sections, we will have a few examples to illustrate the usage of Array properties."
},
{
"code": null,
"e": 104786,
"s": 104706,
"text": "Here is a list of the methods of the Array object along with their description."
},
{
"code": null,
"e": 104874,
"s": 104786,
"text": "Returns a new array comprised of this array joined with other array(s) and/or value(s)."
},
{
"code": null,
"e": 104959,
"s": 104874,
"text": "Returns true if every element in this array satisfies the provided testing function."
},
{
"code": null,
"e": 105074,
"s": 104959,
"text": "Creates a new array with all of the elements of this array for which the provided filtering function returns true."
},
{
"code": null,
"e": 105122,
"s": 105074,
"text": "Calls a function for each element in the array."
},
{
"code": null,
"e": 105239,
"s": 105122,
"text": "Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found."
},
{
"code": null,
"e": 105285,
"s": 105239,
"text": "Joins all elements of an array into a string."
},
{
"code": null,
"e": 105404,
"s": 105285,
"text": "Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found."
},
{
"code": null,
"e": 105504,
"s": 105404,
"text": "Creates a new array with the results of calling a provided function on every element in this array."
},
{
"code": null,
"e": 105569,
"s": 105504,
"text": "Removes the last element from an array and returns that element."
},
{
"code": null,
"e": 105659,
"s": 105569,
"text": "Adds one or more elements to the end of an array and returns the new length of the array."
},
{
"code": null,
"e": 105779,
"s": 105659,
"text": "Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value."
},
{
"code": null,
"e": 105899,
"s": 105779,
"text": "Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value."
},
{
"code": null,
"e": 106009,
"s": 105899,
"text": "Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first."
},
{
"code": null,
"e": 106075,
"s": 106009,
"text": "Removes the first element from an array and returns that element."
},
{
"code": null,
"e": 106131,
"s": 106075,
"text": "Extracts a section of an array and returns a new array."
},
{
"code": null,
"e": 106223,
"s": 106131,
"text": "Returns true if at least one element in this array satisfies the provided testing function."
},
{
"code": null,
"e": 106263,
"s": 106223,
"text": "Represents the source code of an object"
},
{
"code": null,
"e": 106294,
"s": 106263,
"text": "Sorts the elements of an array"
},
{
"code": null,
"e": 106338,
"s": 106294,
"text": "Adds and/or removes elements from an array."
},
{
"code": null,
"e": 106396,
"s": 106338,
"text": "Returns a string representing the array and its elements."
},
{
"code": null,
"e": 106488,
"s": 106396,
"text": "Adds one or more elements to the front of an array and returns the new length of the array."
},
{
"code": null,
"e": 106586,
"s": 106488,
"text": "In the following sections, we will have a few examples to demonstrate the usage of Array methods."
},
{
"code": null,
"e": 106714,
"s": 106586,
"text": "The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date( ) as shown below."
},
{
"code": null,
"e": 106977,
"s": 106714,
"text": "Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time."
},
{
"code": null,
"e": 107257,
"s": 106977,
"text": "The ECMAScript standard requires the Date object to be able to represent any date and time, to millisecond precision, within 100 million days before or after 1/1/1970. This is a range of plus or minus 273,785 years, so JavaScript can represent date and time till the year 275755."
},
{
"code": null,
"e": 107349,
"s": 107257,
"text": "You can use any of the following syntaxes to create a Date object using Date() constructor."
},
{
"code": null,
"e": 107466,
"s": 107349,
"text": "new Date( )\nnew Date(milliseconds)\nnew Date(datestring)\nnew Date(year,month,date[,hour,minute,second,millisecond ])\n"
},
{
"code": null,
"e": 107521,
"s": 107466,
"text": "Note − Parameters in the brackets are always optional."
},
{
"code": null,
"e": 107563,
"s": 107521,
"text": "Here is a description of the parameters −"
},
{
"code": null,
"e": 107675,
"s": 107563,
"text": "No Argument − With no arguments, the Date() constructor creates a Date object set to the current date and time."
},
{
"code": null,
"e": 107787,
"s": 107675,
"text": "No Argument − With no arguments, the Date() constructor creates a Date object set to the current date and time."
},
{
"code": null,
"e": 108064,
"s": 107787,
"text": "milliseconds − When one numeric argument is passed, it is taken as the internal numeric representation of the date in milliseconds, as returned by the getTime() method. For example, passing the argument 5000 creates a date that represents five seconds past midnight on 1/1/70."
},
{
"code": null,
"e": 108341,
"s": 108064,
"text": "milliseconds − When one numeric argument is passed, it is taken as the internal numeric representation of the date in milliseconds, as returned by the getTime() method. For example, passing the argument 5000 creates a date that represents five seconds past midnight on 1/1/70."
},
{
"code": null,
"e": 108482,
"s": 108341,
"text": "datestring − When one string argument is passed, it is a string representation of a date, in the format accepted by the Date.parse() method."
},
{
"code": null,
"e": 108623,
"s": 108482,
"text": "datestring − When one string argument is passed, it is a string representation of a date, in the format accepted by the Date.parse() method."
},
{
"code": null,
"e": 108731,
"s": 108623,
"text": "7 agruments − To use the last form of the constructor shown above. Here is a description of each argument −"
},
{
"code": null,
"e": 108839,
"s": 108731,
"text": "7 agruments − To use the last form of the constructor shown above. Here is a description of each argument −"
},
{
"code": null,
"e": 109008,
"s": 108839,
"text": "year − Integer value representing the year. For compatibility (in order to avoid the Y2K problem), you should always specify the year in full; use 1998, rather than 98."
},
{
"code": null,
"e": 109177,
"s": 109008,
"text": "year − Integer value representing the year. For compatibility (in order to avoid the Y2K problem), you should always specify the year in full; use 1998, rather than 98."
},
{
"code": null,
"e": 109272,
"s": 109177,
"text": "month − Integer value representing the month, beginning with 0 for January to 11 for December."
},
{
"code": null,
"e": 109367,
"s": 109272,
"text": "month − Integer value representing the month, beginning with 0 for January to 11 for December."
},
{
"code": null,
"e": 109423,
"s": 109367,
"text": "date − Integer value representing the day of the month."
},
{
"code": null,
"e": 109479,
"s": 109423,
"text": "date − Integer value representing the day of the month."
},
{
"code": null,
"e": 109550,
"s": 109479,
"text": "hour − Integer value representing the hour of the day (24-hour scale)."
},
{
"code": null,
"e": 109621,
"s": 109550,
"text": "hour − Integer value representing the hour of the day (24-hour scale)."
},
{
"code": null,
"e": 109695,
"s": 109621,
"text": "minute − Integer value representing the minute segment of a time reading."
},
{
"code": null,
"e": 109769,
"s": 109695,
"text": "minute − Integer value representing the minute segment of a time reading."
},
{
"code": null,
"e": 109843,
"s": 109769,
"text": "second − Integer value representing the second segment of a time reading."
},
{
"code": null,
"e": 109917,
"s": 109843,
"text": "second − Integer value representing the second segment of a time reading."
},
{
"code": null,
"e": 110001,
"s": 109917,
"text": "millisecond − Integer value representing the millisecond segment of a time reading."
},
{
"code": null,
"e": 110085,
"s": 110001,
"text": "millisecond − Integer value representing the millisecond segment of a time reading."
},
{
"code": null,
"e": 110167,
"s": 110085,
"text": "Here is a list of the properties of the Date object along with their description."
},
{
"code": null,
"e": 110226,
"s": 110167,
"text": "Specifies the function that creates an object's prototype."
},
{
"code": null,
"e": 110303,
"s": 110226,
"text": "The prototype property allows you to add properties and methods to an object"
},
{
"code": null,
"e": 110413,
"s": 110303,
"text": "In the following sections, we will have a few examples to demonstrate the usage of different Date properties."
},
{
"code": null,
"e": 110481,
"s": 110413,
"text": "Here is a list of the methods used with Date and their description."
},
{
"code": null,
"e": 110511,
"s": 110481,
"text": "Returns today's date and time"
},
{
"code": null,
"e": 110588,
"s": 110511,
"text": "Returns the day of the month for the specified date according to local time."
},
{
"code": null,
"e": 110664,
"s": 110588,
"text": "Returns the day of the week for the specified date according to local time."
},
{
"code": null,
"e": 110728,
"s": 110664,
"text": "Returns the year of the specified date according to local time."
},
{
"code": null,
"e": 110792,
"s": 110728,
"text": "Returns the hour in the specified date according to local time."
},
{
"code": null,
"e": 110864,
"s": 110792,
"text": "Returns the milliseconds in the specified date according to local time."
},
{
"code": null,
"e": 110931,
"s": 110864,
"text": "Returns the minutes in the specified date according to local time."
},
{
"code": null,
"e": 110996,
"s": 110931,
"text": "Returns the month in the specified date according to local time."
},
{
"code": null,
"e": 111063,
"s": 110996,
"text": "Returns the seconds in the specified date according to local time."
},
{
"code": null,
"e": 111178,
"s": 111063,
"text": "Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC."
},
{
"code": null,
"e": 111242,
"s": 111178,
"text": "Returns the time-zone offset in minutes for the current locale."
},
{
"code": null,
"e": 111329,
"s": 111242,
"text": "Returns the day (date) of the month in the specified date according to universal time."
},
{
"code": null,
"e": 111408,
"s": 111329,
"text": "Returns the day of the week in the specified date according to universal time."
},
{
"code": null,
"e": 111476,
"s": 111408,
"text": "Returns the year in the specified date according to universal time."
},
{
"code": null,
"e": 111545,
"s": 111476,
"text": "Returns the hours in the specified date according to universal time."
},
{
"code": null,
"e": 111621,
"s": 111545,
"text": "Returns the milliseconds in the specified date according to universal time."
},
{
"code": null,
"e": 111692,
"s": 111621,
"text": "Returns the minutes in the specified date according to universal time."
},
{
"code": null,
"e": 111761,
"s": 111692,
"text": "Returns the month in the specified date according to universal time."
},
{
"code": null,
"e": 111832,
"s": 111761,
"text": "Returns the seconds in the specified date according to universal time."
},
{
"code": null,
"e": 111934,
"s": 111832,
"text": "Deprecated - Returns the year in the specified date according to local time. Use getFullYear instead."
},
{
"code": null,
"e": 112006,
"s": 111934,
"text": "Sets the day of the month for a specified date according to local time."
},
{
"code": null,
"e": 112071,
"s": 112006,
"text": "Sets the full year for a specified date according to local time."
},
{
"code": null,
"e": 112132,
"s": 112071,
"text": "Sets the hours for a specified date according to local time."
},
{
"code": null,
"e": 112200,
"s": 112132,
"text": "Sets the milliseconds for a specified date according to local time."
},
{
"code": null,
"e": 112263,
"s": 112200,
"text": "Sets the minutes for a specified date according to local time."
},
{
"code": null,
"e": 112324,
"s": 112263,
"text": "Sets the month for a specified date according to local time."
},
{
"code": null,
"e": 112387,
"s": 112324,
"text": "Sets the seconds for a specified date according to local time."
},
{
"code": null,
"e": 112497,
"s": 112387,
"text": "Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC."
},
{
"code": null,
"e": 112573,
"s": 112497,
"text": "Sets the day of the month for a specified date according to universal time."
},
{
"code": null,
"e": 112642,
"s": 112573,
"text": "Sets the full year for a specified date according to universal time."
},
{
"code": null,
"e": 112706,
"s": 112642,
"text": "Sets the hour for a specified date according to universal time."
},
{
"code": null,
"e": 112778,
"s": 112706,
"text": "Sets the milliseconds for a specified date according to universal time."
},
{
"code": null,
"e": 112845,
"s": 112778,
"text": "Sets the minutes for a specified date according to universal time."
},
{
"code": null,
"e": 112910,
"s": 112845,
"text": "Sets the month for a specified date according to universal time."
},
{
"code": null,
"e": 112977,
"s": 112910,
"text": "Sets the seconds for a specified date according to universal time."
},
{
"code": null,
"e": 113076,
"s": 112977,
"text": "Deprecated - Sets the year for a specified date according to local time. Use setFullYear instead."
},
{
"code": null,
"e": 113143,
"s": 113076,
"text": "Returns the \"date\" portion of the Date as a human-readable string."
},
{
"code": null,
"e": 113247,
"s": 113143,
"text": "Deprecated - Converts a date to a string, using the Internet GMT conventions. Use toUTCString instead."
},
{
"code": null,
"e": 113339,
"s": 113247,
"text": "Returns the \"date\" portion of the Date as a string, using the current locale's conventions."
},
{
"code": null,
"e": 113391,
"s": 113339,
"text": "Converts a date to a string, using a format string."
},
{
"code": null,
"e": 113460,
"s": 113391,
"text": "Converts a date to a string, using the current locale's conventions."
},
{
"code": null,
"e": 113552,
"s": 113460,
"text": "Returns the \"time\" portion of the Date as a string, using the current locale's conventions."
},
{
"code": null,
"e": 113671,
"s": 113552,
"text": "Returns a string representing the source for an equivalent Date object; you can use this value to create a new object."
},
{
"code": null,
"e": 113728,
"s": 113671,
"text": "Returns a string representing the specified Date object."
},
{
"code": null,
"e": 113795,
"s": 113728,
"text": "Returns the \"time\" portion of the Date as a human-readable string."
},
{
"code": null,
"e": 113861,
"s": 113795,
"text": "Converts a date to a string, using the universal time convention."
},
{
"code": null,
"e": 113907,
"s": 113861,
"text": "Returns the primitive value of a Date object."
},
{
"code": null,
"e": 113973,
"s": 113907,
"text": "Converts a date to a string, using the universal time convention."
},
{
"code": null,
"e": 114147,
"s": 113973,
"text": "In addition to the many instance methods listed previously, the Date object also defines two static methods. These methods are invoked through the Date() constructor itself."
},
{
"code": null,
"e": 114263,
"s": 114147,
"text": "Parses a string representation of a date and time and returns the internal millisecond representation of that date."
},
{
"code": null,
"e": 114338,
"s": 114263,
"text": "Returns the millisecond representation of the specified UTC date and time."
},
{
"code": null,
"e": 114443,
"s": 114338,
"text": "In the following sections, we will have a few examples to demonstrate the usages of Date Static methods."
},
{
"code": null,
"e": 114709,
"s": 114443,
"text": "The math object provides you properties and methods for mathematical constants and functions. Unlike other global objects, Math is not a constructor. All the properties and methods of Math are static and can be called by using Math as an object without creating it."
},
{
"code": null,
"e": 114836,
"s": 114709,
"text": "Thus, you refer to the constant pi as Math.PI and you call the sine function as Math.sin(x), where x is the method's argument."
},
{
"code": null,
"e": 114905,
"s": 114836,
"text": "The syntax to call the properties and methods of Math are as follows"
},
{
"code": null,
"e": 114957,
"s": 114905,
"text": "var pi_val = Math.PI;\nvar sine_val = Math.sin(30);\n"
},
{
"code": null,
"e": 115025,
"s": 114957,
"text": "Here is a list of all the properties of Math and their description."
},
{
"code": null,
"e": 115099,
"s": 115025,
"text": "Euler's constant and the base of natural logarithms, approximately 2.718."
},
{
"code": null,
"e": 115144,
"s": 115099,
"text": "Natural logarithm of 2, approximately 0.693."
},
{
"code": null,
"e": 115190,
"s": 115144,
"text": "Natural logarithm of 10, approximately 2.302."
},
{
"code": null,
"e": 115234,
"s": 115190,
"text": "Base 2 logarithm of E, approximately 1.442."
},
{
"code": null,
"e": 115279,
"s": 115234,
"text": "Base 10 logarithm of E, approximately 0.434."
},
{
"code": null,
"e": 115358,
"s": 115279,
"text": "Ratio of the circumference of a circle to its diameter, approximately 3.14159."
},
{
"code": null,
"e": 115442,
"s": 115358,
"text": "Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707."
},
{
"code": null,
"e": 115481,
"s": 115442,
"text": "Square root of 2, approximately 1.414."
},
{
"code": null,
"e": 115581,
"s": 115481,
"text": "In the following sections, we will have a few examples to demonstrate the usage of Math properties."
},
{
"code": null,
"e": 115661,
"s": 115581,
"text": "Here is a list of the methods associated with Math object and their description"
},
{
"code": null,
"e": 115701,
"s": 115661,
"text": "Returns the absolute value of a number."
},
{
"code": null,
"e": 115749,
"s": 115701,
"text": "Returns the arccosine (in radians) of a number."
},
{
"code": null,
"e": 115795,
"s": 115749,
"text": "Returns the arcsine (in radians) of a number."
},
{
"code": null,
"e": 115844,
"s": 115795,
"text": "Returns the arctangent (in radians) of a number."
},
{
"code": null,
"e": 115901,
"s": 115844,
"text": "Returns the arctangent of the quotient of its arguments."
},
{
"code": null,
"e": 115965,
"s": 115901,
"text": "Returns the smallest integer greater than or equal to a number."
},
{
"code": null,
"e": 115997,
"s": 115965,
"text": "Returns the cosine of a number."
},
{
"code": null,
"e": 116096,
"s": 115997,
"text": "Returns EN, where N is the argument, and E is Euler's constant, the base of the natural logarithm."
},
{
"code": null,
"e": 116156,
"s": 116096,
"text": "Returns the largest integer less than or equal to a number."
},
{
"code": null,
"e": 116208,
"s": 116156,
"text": "Returns the natural logarithm (base E) of a number."
},
{
"code": null,
"e": 116253,
"s": 116208,
"text": "Returns the largest of zero or more numbers."
},
{
"code": null,
"e": 116299,
"s": 116253,
"text": "Returns the smallest of zero or more numbers."
},
{
"code": null,
"e": 116359,
"s": 116299,
"text": "Returns base to the exponent power, that is, base exponent."
},
{
"code": null,
"e": 116407,
"s": 116359,
"text": "Returns a pseudo-random number between 0 and 1."
},
{
"code": null,
"e": 116469,
"s": 116407,
"text": "Returns the value of a number rounded to the nearest integer."
},
{
"code": null,
"e": 116499,
"s": 116469,
"text": "Returns the sine of a number."
},
{
"code": null,
"e": 116536,
"s": 116499,
"text": "Returns the square root of a number."
},
{
"code": null,
"e": 116569,
"s": 116536,
"text": "Returns the tangent of a number."
},
{
"code": null,
"e": 116596,
"s": 116569,
"text": "Returns the string \"Math\"."
},
{
"code": null,
"e": 116713,
"s": 116596,
"text": "In the following sections, we will have a few examples to demonstrate the usage of the methods associated with Math."
},
{
"code": null,
"e": 116787,
"s": 116713,
"text": "A regular expression is an object that describes a pattern of characters."
},
{
"code": null,
"e": 116997,
"s": 116787,
"text": "The JavaScript RegExp class represents regular expressions, and both String and RegExp define methods that use regular expressions to perform powerful pattern-matching and search-and-replace functions on text."
},
{
"code": null,
"e": 117080,
"s": 116997,
"text": "A regular expression could be defined with the RegExp () constructor, as follows −"
},
{
"code": null,
"e": 117173,
"s": 117080,
"text": "var pattern = new RegExp(pattern, attributes);\nor simply\nvar pattern = /pattern/attributes;\n"
},
{
"code": null,
"e": 117217,
"s": 117173,
"text": "Here is the description of the parameters −"
},
{
"code": null,
"e": 117320,
"s": 117217,
"text": "pattern − A string that specifies the pattern of the regular expression or another regular expression."
},
{
"code": null,
"e": 117423,
"s": 117320,
"text": "pattern − A string that specifies the pattern of the regular expression or another regular expression."
},
{
"code": null,
"e": 117583,
"s": 117423,
"text": "attributes − An optional string containing any of the \"g\", \"i\", and \"m\" attributes that specify global, case-insensitive, and multi-line matches, respectively."
},
{
"code": null,
"e": 117743,
"s": 117583,
"text": "attributes − An optional string containing any of the \"g\", \"i\", and \"m\" attributes that specify global, case-insensitive, and multi-line matches, respectively."
},
{
"code": null,
"e": 117874,
"s": 117743,
"text": "Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of characters."
},
{
"code": null,
"e": 117880,
"s": 117874,
"text": "[...]"
},
{
"code": null,
"e": 117920,
"s": 117880,
"text": "Any one character between the brackets."
},
{
"code": null,
"e": 117927,
"s": 117920,
"text": "[^...]"
},
{
"code": null,
"e": 117971,
"s": 117927,
"text": "Any one character not between the brackets."
},
{
"code": null,
"e": 117977,
"s": 117971,
"text": "[0-9]"
},
{
"code": null,
"e": 118024,
"s": 117977,
"text": "It matches any decimal digit from 0 through 9."
},
{
"code": null,
"e": 118030,
"s": 118024,
"text": "[a-z]"
},
{
"code": null,
"e": 118093,
"s": 118030,
"text": "It matches any character from lowercase a through lowercase z."
},
{
"code": null,
"e": 118099,
"s": 118093,
"text": "[A-Z]"
},
{
"code": null,
"e": 118162,
"s": 118099,
"text": "It matches any character from uppercase A through uppercase Z."
},
{
"code": null,
"e": 118168,
"s": 118162,
"text": "[a-Z]"
},
{
"code": null,
"e": 118231,
"s": 118168,
"text": "It matches any character from lowercase a through uppercase Z."
},
{
"code": null,
"e": 118433,
"s": 118231,
"text": "The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v."
},
{
"code": null,
"e": 118662,
"s": 118433,
"text": "The frequency or position of bracketed character sequences and single characters can be denoted by a special character. Each special character has a specific connotation. The +, *, ?, and $ flags all follow a character sequence."
},
{
"code": null,
"e": 118665,
"s": 118662,
"text": "p+"
},
{
"code": null,
"e": 118715,
"s": 118665,
"text": "It matches any string containing one or more p's."
},
{
"code": null,
"e": 118718,
"s": 118715,
"text": "p*"
},
{
"code": null,
"e": 118769,
"s": 118718,
"text": "It matches any string containing zero or more p's."
},
{
"code": null,
"e": 118772,
"s": 118769,
"text": "p?"
},
{
"code": null,
"e": 118820,
"s": 118772,
"text": "It matches any string containing at most one p."
},
{
"code": null,
"e": 118825,
"s": 118820,
"text": "p{N}"
},
{
"code": null,
"e": 118878,
"s": 118825,
"text": "It matches any string containing a sequence of N p's"
},
{
"code": null,
"e": 118885,
"s": 118878,
"text": "p{2,3}"
},
{
"code": null,
"e": 118950,
"s": 118885,
"text": "It matches any string containing a sequence of two or three p's."
},
{
"code": null,
"e": 118957,
"s": 118950,
"text": "p{2, }"
},
{
"code": null,
"e": 119022,
"s": 118957,
"text": "It matches any string containing a sequence of at least two p's."
},
{
"code": null,
"e": 119025,
"s": 119022,
"text": "p$"
},
{
"code": null,
"e": 119073,
"s": 119025,
"text": "It matches any string with p at the end of it."
},
{
"code": null,
"e": 119076,
"s": 119073,
"text": "^p"
},
{
"code": null,
"e": 119129,
"s": 119076,
"text": "It matches any string with p at the beginning of it."
},
{
"code": null,
"e": 119188,
"s": 119129,
"text": "Following examples explain more about matching characters."
},
{
"code": null,
"e": 119198,
"s": 119188,
"text": "[^a-zA-Z]"
},
{
"code": null,
"e": 119299,
"s": 119198,
"text": "It matches any string not containing any of the characters ranging from a through z and A through Z."
},
{
"code": null,
"e": 119303,
"s": 119299,
"text": "p.p"
},
{
"code": null,
"e": 119397,
"s": 119303,
"text": "It matches any string containing p, followed by any character, in turn followed by another p."
},
{
"code": null,
"e": 119404,
"s": 119397,
"text": "^.{2}$"
},
{
"code": null,
"e": 119461,
"s": 119404,
"text": "It matches any string containing exactly two characters."
},
{
"code": null,
"e": 119473,
"s": 119461,
"text": "<b>(.*)</b>"
},
{
"code": null,
"e": 119525,
"s": 119473,
"text": "It matches any string enclosed within <b> and </b>."
},
{
"code": null,
"e": 119532,
"s": 119525,
"text": "p(hp)*"
},
{
"code": null,
"e": 119624,
"s": 119532,
"text": "It matches any string containing a p followed by zero or more instances of the sequence hp."
},
{
"code": null,
"e": 119637,
"s": 119624,
"text": "Alphanumeric"
},
{
"code": null,
"e": 119644,
"s": 119637,
"text": "Itself"
},
{
"code": null,
"e": 119647,
"s": 119644,
"text": "\\0"
},
{
"code": null,
"e": 119674,
"s": 119647,
"text": "The NUL character (\\u0000)"
},
{
"code": null,
"e": 119677,
"s": 119674,
"text": "\\t"
},
{
"code": null,
"e": 119689,
"s": 119677,
"text": "Tab (\\u0009"
},
{
"code": null,
"e": 119692,
"s": 119689,
"text": "\\n"
},
{
"code": null,
"e": 119709,
"s": 119692,
"text": "Newline (\\u000A)"
},
{
"code": null,
"e": 119712,
"s": 119709,
"text": "\\v"
},
{
"code": null,
"e": 119734,
"s": 119712,
"text": "Vertical tab (\\u000B)"
},
{
"code": null,
"e": 119737,
"s": 119734,
"text": "\\f"
},
{
"code": null,
"e": 119756,
"s": 119737,
"text": "Form feed (\\u000C)"
},
{
"code": null,
"e": 119759,
"s": 119756,
"text": "\\r"
},
{
"code": null,
"e": 119784,
"s": 119759,
"text": "Carriage return (\\u000D)"
},
{
"code": null,
"e": 119789,
"s": 119784,
"text": "\\xnn"
},
{
"code": null,
"e": 119885,
"s": 119789,
"text": "The Latin character specified by the hexadecimal number nn; for example, \\x0A is the same as \\n"
},
{
"code": null,
"e": 119892,
"s": 119885,
"text": "\\uxxxx"
},
{
"code": null,
"e": 119994,
"s": 119892,
"text": "The Unicode character specified by the hexadecimal number xxxx; for example, \\u0009 is the same as \\t"
},
{
"code": null,
"e": 119998,
"s": 119994,
"text": "\\cX"
},
{
"code": null,
"e": 120083,
"s": 119998,
"text": "The control character ^X; for example, \\cJ is equivalent to the newline character \\n"
},
{
"code": null,
"e": 120212,
"s": 120083,
"text": "A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the combination a special meaning."
},
{
"code": null,
"e": 120369,
"s": 120212,
"text": "For instance, you can search for a large sum of money using the '\\d' metacharacter: /([\\d]+)000/, Here \\d will search for any string of numerical character."
},
{
"code": null,
"e": 120472,
"s": 120369,
"text": "The following table lists a set of metacharacters which can be used in PERL Style Regular Expressions."
},
{
"code": null,
"e": 120474,
"s": 120472,
"text": "."
},
{
"code": null,
"e": 120493,
"s": 120474,
"text": "a single character"
},
{
"code": null,
"e": 120496,
"s": 120493,
"text": "\\s"
},
{
"code": null,
"e": 120541,
"s": 120496,
"text": "a whitespace character (space, tab, newline)"
},
{
"code": null,
"e": 120544,
"s": 120541,
"text": "\\S"
},
{
"code": null,
"e": 120569,
"s": 120544,
"text": "non-whitespace character"
},
{
"code": null,
"e": 120572,
"s": 120569,
"text": "\\d"
},
{
"code": null,
"e": 120586,
"s": 120572,
"text": "a digit (0-9)"
},
{
"code": null,
"e": 120589,
"s": 120586,
"text": "\\D"
},
{
"code": null,
"e": 120601,
"s": 120589,
"text": "a non-digit"
},
{
"code": null,
"e": 120604,
"s": 120601,
"text": "\\w"
},
{
"code": null,
"e": 120640,
"s": 120604,
"text": "a word character (a-z, A-Z, 0-9, _)"
},
{
"code": null,
"e": 120643,
"s": 120640,
"text": "\\W"
},
{
"code": null,
"e": 120664,
"s": 120643,
"text": "a non-word character"
},
{
"code": null,
"e": 120669,
"s": 120664,
"text": "[\\b]"
},
{
"code": null,
"e": 120705,
"s": 120669,
"text": "a literal backspace (special case)."
},
{
"code": null,
"e": 120713,
"s": 120705,
"text": "[aeiou]"
},
{
"code": null,
"e": 120757,
"s": 120713,
"text": "matches a single character in the given set"
},
{
"code": null,
"e": 120766,
"s": 120757,
"text": "[^aeiou]"
},
{
"code": null,
"e": 120815,
"s": 120766,
"text": "matches a single character outside the given set"
},
{
"code": null,
"e": 120829,
"s": 120815,
"text": "(foo|bar|baz)"
},
{
"code": null,
"e": 120871,
"s": 120829,
"text": "matches any of the alternatives specified"
},
{
"code": null,
"e": 121009,
"s": 120871,
"text": "Several modifiers are available that can simplify the way you work with regexps, like case sensitivity, searching in multiple lines, etc."
},
{
"code": null,
"e": 121011,
"s": 121009,
"text": "i"
},
{
"code": null,
"e": 121046,
"s": 121011,
"text": "Perform case-insensitive matching."
},
{
"code": null,
"e": 121048,
"s": 121046,
"text": "m"
},
{
"code": null,
"e": 121214,
"s": 121048,
"text": "Specifies that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary"
},
{
"code": null,
"e": 121216,
"s": 121214,
"text": "g"
},
{
"code": null,
"e": 121309,
"s": 121216,
"text": "Performs a global matchthat is, find all matches rather than stopping after the first match."
},
{
"code": null,
"e": 121388,
"s": 121309,
"text": "Here is a list of the properties associated with RegExp and their description."
},
{
"code": null,
"e": 121447,
"s": 121388,
"text": "Specifies the function that creates an object's prototype."
},
{
"code": null,
"e": 121485,
"s": 121447,
"text": "Specifies if the \"g\" modifier is set."
},
{
"code": null,
"e": 121523,
"s": 121485,
"text": "Specifies if the \"i\" modifier is set."
},
{
"code": null,
"e": 121567,
"s": 121523,
"text": "The index at which to start the next match."
},
{
"code": null,
"e": 121605,
"s": 121567,
"text": "Specifies if the \"m\" modifier is set."
},
{
"code": null,
"e": 121630,
"s": 121605,
"text": "The text of the pattern."
},
{
"code": null,
"e": 121732,
"s": 121630,
"text": "In the following sections, we will have a few examples to demonstrate the usage of RegExp properties."
},
{
"code": null,
"e": 121815,
"s": 121732,
"text": "Here is a list of the methods associated with RegExp along with their description."
},
{
"code": null,
"e": 121870,
"s": 121815,
"text": "Executes a search for a match in its string parameter."
},
{
"code": null,
"e": 121913,
"s": 121870,
"text": "Tests for a match in its string parameter."
},
{
"code": null,
"e": 122021,
"s": 121913,
"text": "Returns an object literal representing the specified object; you can use this value to create a new object."
},
{
"code": null,
"e": 122073,
"s": 122021,
"text": "Returns a string representing the specified object."
},
{
"code": null,
"e": 122172,
"s": 122073,
"text": "In the following sections, we will have a few examples to demonstrate the usage of RegExp methods."
},
{
"code": null,
"e": 122257,
"s": 122172,
"text": "Every web page resides inside a browser window which can be considered as an object."
},
{
"code": null,
"e": 122469,
"s": 122257,
"text": "A Document object represents the HTML document that is displayed in that window. The Document object has various properties that refer to other objects which allow access to and modification of document content."
},
{
"code": null,
"e": 122694,
"s": 122469,
"text": "The way a document content is accessed and modified is called the Document Object Model, or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document."
},
{
"code": null,
"e": 122783,
"s": 122694,
"text": "Window object − Top of the hierarchy. It is the outmost element of the object hierarchy."
},
{
"code": null,
"e": 122872,
"s": 122783,
"text": "Window object − Top of the hierarchy. It is the outmost element of the object hierarchy."
},
{
"code": null,
"e": 123015,
"s": 122872,
"text": "Document object − Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page."
},
{
"code": null,
"e": 123158,
"s": 123015,
"text": "Document object − Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page."
},
{
"code": null,
"e": 123243,
"s": 123158,
"text": "Form object − Everything enclosed in the <form>...</form> tags sets the form object."
},
{
"code": null,
"e": 123328,
"s": 123243,
"text": "Form object − Everything enclosed in the <form>...</form> tags sets the form object."
},
{
"code": null,
"e": 123479,
"s": 123328,
"text": "Form control elements − The form object contains all the elements defined for that object such as text fields, buttons, radio buttons, and checkboxes."
},
{
"code": null,
"e": 123630,
"s": 123479,
"text": "Form control elements − The form object contains all the elements defined for that object such as text fields, buttons, radio buttons, and checkboxes."
},
{
"code": null,
"e": 123686,
"s": 123630,
"text": "Here is a simple hierarchy of a few important objects −"
},
{
"code": null,
"e": 123856,
"s": 123686,
"text": "There are several DOMs in existence. The following sections explain each of these DOMs in detail and describe how you can use them to access and modify document content."
},
{
"code": null,
"e": 124095,
"s": 123856,
"text": "The Legacy DOM − This is the model which was introduced in early versions of JavaScript language. It is well supported by all browsers, but allows access only to certain key portions of documents, such as forms, form elements, and images."
},
{
"code": null,
"e": 124334,
"s": 124095,
"text": "The Legacy DOM − This is the model which was introduced in early versions of JavaScript language. It is well supported by all browsers, but allows access only to certain key portions of documents, such as forms, form elements, and images."
},
{
"code": null,
"e": 124549,
"s": 124334,
"text": "The W3C DOM − This document object model allows access and modification of all document content and is standardized by the World Wide Web Consortium (W3C). This model is supported by almost all the modern browsers."
},
{
"code": null,
"e": 124764,
"s": 124549,
"text": "The W3C DOM − This document object model allows access and modification of all document content and is standardized by the World Wide Web Consortium (W3C). This model is supported by almost all the modern browsers."
},
{
"code": null,
"e": 124948,
"s": 124764,
"text": "The IE4 DOM − This document object model was introduced in Version 4 of Microsoft's Internet Explorer browser. IE 5 and later versions include support for most basic W3C DOM features."
},
{
"code": null,
"e": 125132,
"s": 124948,
"text": "The IE4 DOM − This document object model was introduced in Version 4 of Microsoft's Internet Explorer browser. IE 5 and later versions include support for most basic W3C DOM features."
},
{
"code": null,
"e": 125435,
"s": 125132,
"text": "If you want to write a script with the flexibility to use either W3C DOM or IE 4 DOM depending on their availability, then you can use a capability-testing approach that first checks for the existence of a method or property to determine whether the browser has the capability you desire. For example −"
},
{
"code": null,
"e": 125619,
"s": 125435,
"text": "if (document.getElementById) {\n // If the W3C method exists, use it\n} else if (document.all) {\n // If the all[] array exists, use it\n} else {\n // Otherwise use the legacy DOM\n}\n"
},
{
"code": null,
"e": 125730,
"s": 125619,
"text": "There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c) Logical Errors."
},
{
"code": null,
"e": 125869,
"s": 125730,
"text": "Syntax errors, also called parsing errors, occur at compile time in traditional programming languages and at interpret time in JavaScript."
},
{
"code": null,
"e": 125968,
"s": 125869,
"text": "For example, the following line causes a syntax error because it is missing a closing parenthesis."
},
{
"code": null,
"e": 126051,
"s": 125968,
"text": "<script type = \"text/javascript\">\n <!--\n window.print(;\n //-->\n</script>\n"
},
{
"code": null,
"e": 126295,
"s": 126051,
"text": "When a syntax error occurs in JavaScript, only the code contained within the same thread as the syntax error is affected and the rest of the code in other threads gets executed assuming nothing in them depends on the code containing the error."
},
{
"code": null,
"e": 126394,
"s": 126295,
"text": "Runtime errors, also called exceptions, occur during execution (after compilation/interpretation)."
},
{
"code": null,
"e": 126552,
"s": 126394,
"text": "For example, the following line causes a runtime error because here the syntax is correct, but at runtime, it is trying to call a method that does not exist."
},
{
"code": null,
"e": 126638,
"s": 126552,
"text": "<script type = \"text/javascript\">\n <!--\n window.printme();\n //-->\n</script>\n"
},
{
"code": null,
"e": 126757,
"s": 126638,
"text": "Exceptions also affect the thread in which they occur, allowing other JavaScript threads to continue normal execution."
},
{
"code": null,
"e": 127013,
"s": 126757,
"text": "Logic errors can be the most difficult type of errors to track down. These errors are not the result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script and you do not get the result you expected."
},
{
"code": null,
"e": 127144,
"s": 127013,
"text": "You cannot catch those errors, because it depends on your business requirement what type of logic you want to put in your program."
},
{
"code": null,
"e": 127327,
"s": 127144,
"text": "The latest versions of JavaScript added exception handling capabilities. JavaScript implements the try...catch...finally construct as well as the throw operator to handle exceptions."
},
{
"code": null,
"e": 127433,
"s": 127327,
"text": "You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors."
},
{
"code": null,
"e": 127482,
"s": 127433,
"text": "Here is the try...catch...finally block syntax −"
},
{
"code": null,
"e": 127831,
"s": 127482,
"text": "<script type = \"text/javascript\">\n <!--\n try {\n // Code to run\n [break;]\n } \n \n catch ( e ) {\n // Code to run if an exception occurs\n [break;]\n }\n \n [ finally {\n // Code that is always executed regardless of \n // an exception occurring\n }]\n //-->\n</script>"
},
{
"code": null,
"e": 128109,
"s": 127831,
"text": "The try block must be followed by either exactly one catch block or one finally block (or one of both). When an exception occurs in the try block, the exception is placed in e and the catch block is executed. The optional finally block executes unconditionally after try/catch."
},
{
"code": null,
"e": 128266,
"s": 128109,
"text": "Here is an example where we are trying to call a non-existing function which in turn is raising an exception. Let us see how it behaves without try...catch−"
},
{
"code": null,
"e": 128722,
"s": 128266,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n function myFunc() {\n var a = 100;\n alert(\"Value of variable a is : \" + a );\n }\n //-->\n </script> \n </head>\n \n <body>\n <p>Click the following to see the result:</p>\n \n <form>\n <input type = \"button\" value = \"Click Me\" onclick = \"myFunc();\" />\n </form> \n </body>\n</html>"
},
{
"code": null,
"e": 128761,
"s": 128722,
"text": "Click the following to see the result:"
},
{
"code": null,
"e": 128935,
"s": 128761,
"text": "Now let us try to catch this exception using try...catch and display a user-friendly message. You can also suppress this message, if you want to hide this error from a user."
},
{
"code": null,
"e": 129531,
"s": 128935,
"text": "<html>\n <head>\n \n <script type = \"text/javascript\">\n <!--\n function myFunc() {\n var a = 100;\n try {\n alert(\"Value of variable a is : \" + a );\n } \n catch ( e ) {\n alert(\"Error: \" + e.description );\n }\n }\n //-->\n </script>\n \n </head>\n <body>\n <p>Click the following to see the result:</p>\n \n <form>\n <input type = \"button\" value = \"Click Me\" onclick = \"myFunc();\" />\n </form>\n \n </body>\n</html>"
},
{
"code": null,
"e": 129570,
"s": 129531,
"text": "Click the following to see the result:"
},
{
"code": null,
"e": 129679,
"s": 129570,
"text": "You can use finally block which will always execute unconditionally after the try/catch. Here is an example."
},
{
"code": null,
"e": 130396,
"s": 129679,
"text": "<html>\n <head>\n \n <script type = \"text/javascript\">\n <!--\n function myFunc() {\n var a = 100;\n \n try {\n alert(\"Value of variable a is : \" + a );\n }\n catch ( e ) {\n alert(\"Error: \" + e.description );\n }\n finally {\n alert(\"Finally block will always execute!\" );\n }\n }\n //-->\n </script>\n \n </head>\n <body>\n <p>Click the following to see the result:</p>\n \n <form>\n <input type = \"button\" value = \"Click Me\" onclick = \"myFunc();\" />\n </form>\n \n </body>\n</html>"
},
{
"code": null,
"e": 130435,
"s": 130396,
"text": "Click the following to see the result:"
},
{
"code": null,
"e": 130607,
"s": 130435,
"text": "You can use throw statement to raise your built-in exceptions or your customized exceptions. Later these exceptions can be captured and you can take an appropriate action."
},
{
"code": null,
"e": 130672,
"s": 130607,
"text": "The following example demonstrates how to use a throw statement."
},
{
"code": null,
"e": 131411,
"s": 130672,
"text": "<html>\n <head>\n \n <script type = \"text/javascript\">\n <!--\n function myFunc() {\n var a = 100;\n var b = 0;\n \n try {\n if ( b == 0 ) {\n throw( \"Divide by zero error.\" ); \n } else {\n var c = a / b;\n }\n }\n catch ( e ) {\n alert(\"Error: \" + e );\n }\n }\n //-->\n </script>\n \n </head>\n <body>\n <p>Click the following to see the result:</p>\n \n <form>\n <input type = \"button\" value = \"Click Me\" onclick = \"myFunc();\" />\n </form>\n \n </body>\n</html>"
},
{
"code": null,
"e": 131450,
"s": 131411,
"text": "Click the following to see the result:"
},
{
"code": null,
"e": 131675,
"s": 131450,
"text": "You can raise an exception in one function using a string, integer, Boolean, or an object and then you can capture that exception either in the same function as we did above, or in another function using a try...catch block."
},
{
"code": null,
"e": 131855,
"s": 131675,
"text": "The onerror event handler was the first feature to facilitate error handling in JavaScript. The error event is fired on the window object whenever an exception occurs on the page."
},
{
"code": null,
"e": 132281,
"s": 131855,
"text": "<html>\n <head>\n \n <script type = \"text/javascript\">\n <!--\n window.onerror = function () {\n alert(\"An error occurred.\");\n }\n //-->\n </script>\n \n </head>\n <body>\n <p>Click the following to see the result:</p>\n \n <form>\n <input type = \"button\" value = \"Click Me\" onclick = \"myFunc();\" />\n </form>\n \n </body>\n</html>"
},
{
"code": null,
"e": 132320,
"s": 132281,
"text": "Click the following to see the result:"
},
{
"code": null,
"e": 132427,
"s": 132320,
"text": "The onerror event handler provides three pieces of information to identify the exact nature of the error −"
},
{
"code": null,
"e": 132511,
"s": 132427,
"text": "Error message − The same message that the browser would display for the given error"
},
{
"code": null,
"e": 132595,
"s": 132511,
"text": "Error message − The same message that the browser would display for the given error"
},
{
"code": null,
"e": 132638,
"s": 132595,
"text": "URL − The file in which the error occurred"
},
{
"code": null,
"e": 132681,
"s": 132638,
"text": "URL − The file in which the error occurred"
},
{
"code": null,
"e": 132749,
"s": 132681,
"text": "Line number− The line number in the given URL that caused the error"
},
{
"code": null,
"e": 132817,
"s": 132749,
"text": "Line number− The line number in the given URL that caused the error"
},
{
"code": null,
"e": 132878,
"s": 132817,
"text": "Here is the example to show how to extract this information."
},
{
"code": null,
"e": 133401,
"s": 132878,
"text": "<html>\n <head>\n \n <script type = \"text/javascript\">\n <!--\n window.onerror = function (msg, url, line) {\n alert(\"Message : \" + msg );\n alert(\"url : \" + url );\n alert(\"Line number : \" + line );\n }\n //-->\n </script>\n \n </head>\n <body>\n <p>Click the following to see the result:</p>\n \n <form>\n <input type = \"button\" value = \"Click Me\" onclick = \"myFunc();\" />\n </form>\n \n </body>\n</html>"
},
{
"code": null,
"e": 133440,
"s": 133401,
"text": "Click the following to see the result:"
},
{
"code": null,
"e": 133518,
"s": 133440,
"text": "You can display extracted information in whatever way you think it is better."
},
{
"code": null,
"e": 133643,
"s": 133518,
"text": "You can use an onerror method, as shown below, to display an error message in case there is any problem in loading an image."
},
{
"code": null,
"e": 133725,
"s": 133643,
"text": "<img src=\"myimage.gif\" onerror=\"alert('An error occurred loading the image.')\" />"
},
{
"code": null,
"e": 133816,
"s": 133725,
"text": "You can use onerror with many HTML tags to display appropriate messages in case of errors."
},
{
"code": null,
"e": 134239,
"s": 133816,
"text": "Form validation normally used to occur at the server, after the client had entered all the necessary data and then pressed the Submit button. If the data entered by a client was incorrect or was simply missing, the server would have to send all the data back to the client and request that the form be resubmitted with correct information. This was really a lengthy process which used to put a lot of burden on the server."
},
{
"code": null,
"e": 134401,
"s": 134239,
"text": "JavaScript provides a way to validate form's data on the client's computer before sending it to the web server. Form validation generally performs two functions."
},
{
"code": null,
"e": 134592,
"s": 134401,
"text": "Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data."
},
{
"code": null,
"e": 134783,
"s": 134592,
"text": "Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data."
},
{
"code": null,
"e": 134957,
"s": 134783,
"text": "Data Format Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test correctness of data."
},
{
"code": null,
"e": 135131,
"s": 134957,
"text": "Data Format Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test correctness of data."
},
{
"code": null,
"e": 135234,
"s": 135131,
"text": "We will take an example to understand the process of validation. Here is a simple form in html format."
},
{
"code": null,
"e": 136765,
"s": 135234,
"text": "<html> \n <head>\n <title>Form Validation</title> \n <script type = \"text/javascript\">\n <!--\n // Form validation code will come here.\n //-->\n </script> \n </head>\n \n <body>\n <form action = \"/cgi-bin/test.cgi\" name = \"myForm\" onsubmit = \"return(validate());\">\n <table cellspacing = \"2\" cellpadding = \"2\" border = \"1\">\n \n <tr>\n <td align = \"right\">Name</td>\n <td><input type = \"text\" name = \"Name\" /></td>\n </tr>\n \n <tr>\n <td align = \"right\">EMail</td>\n <td><input type = \"text\" name = \"EMail\" /></td>\n </tr>\n \n <tr>\n <td align = \"right\">Zip Code</td>\n <td><input type = \"text\" name = \"Zip\" /></td>\n </tr>\n \n <tr>\n <td align = \"right\">Country</td>\n <td>\n <select name = \"Country\">\n <option value = \"-1\" selected>[choose yours]</option>\n <option value = \"1\">USA</option>\n <option value = \"2\">UK</option>\n <option value = \"3\">INDIA</option>\n </select>\n </td>\n </tr>\n \n <tr>\n <td align = \"right\"></td>\n <td><input type = \"submit\" value = \"Submit\" /></td>\n </tr>\n \n </table>\n </form> \n </body>\n</html>"
},
{
"code": null,
"e": 136986,
"s": 136765,
"text": "First let us see how to do a basic form validation. In the above form, we are calling validate() to validate data when onsubmit event is occurring. The following code shows the implementation of this validate() function."
},
{
"code": null,
"e": 137967,
"s": 136986,
"text": "<script type = \"text/javascript\">\n <!--\n // Form validation code will come here.\n function validate() {\n \n if( document.myForm.Name.value == \"\" ) {\n alert( \"Please provide your name!\" );\n document.myForm.Name.focus() ;\n return false;\n }\n if( document.myForm.EMail.value == \"\" ) {\n alert( \"Please provide your Email!\" );\n document.myForm.EMail.focus() ;\n return false;\n }\n if( document.myForm.Zip.value == \"\" || isNaN( document.myForm.Zip.value ) ||\n document.myForm.Zip.value.length != 5 ) {\n \n alert( \"Please provide a zip in the format #####.\" );\n document.myForm.Zip.focus() ;\n return false;\n }\n if( document.myForm.Country.value == \"-1\" ) {\n alert( \"Please provide your country!\" );\n return false;\n }\n return( true );\n }\n //-->\n</script>"
},
{
"code": null,
"e": 138065,
"s": 137967,
"text": "Now we will see how we can validate our entered form data before submitting it to the web server."
},
{
"code": null,
"e": 138336,
"s": 138065,
"text": "The following example shows how to validate an entered email address. An email address must contain at least a ‘@’ sign and a dot (.). Also, the ‘@’ must not be the first character of the email address, and the last dot must at least be one character after the ‘@’ sign."
},
{
"code": null,
"e": 138381,
"s": 138336,
"text": "Try the following code for email validation."
},
{
"code": null,
"e": 138837,
"s": 138381,
"text": "<script type = \"text/javascript\">\n <!--\n function validateEmail() {\n var emailID = document.myForm.EMail.value;\n atpos = emailID.indexOf(\"@\");\n dotpos = emailID.lastIndexOf(\".\");\n \n if (atpos < 1 || ( dotpos - atpos < 2 )) {\n alert(\"Please enter correct email ID\")\n document.myForm.EMail.focus() ;\n return false;\n }\n return( true );\n }\n //-->\n</script>"
},
{
"code": null,
"e": 138943,
"s": 138837,
"text": "You can use JavaScript to create a complex animation having, but not limited to, the following elements −"
},
{
"code": null,
"e": 138953,
"s": 138943,
"text": "Fireworks"
},
{
"code": null,
"e": 138965,
"s": 138953,
"text": "Fade Effect"
},
{
"code": null,
"e": 138985,
"s": 138965,
"text": "Roll-in or Roll-out"
},
{
"code": null,
"e": 139005,
"s": 138985,
"text": "Page-in or Page-out"
},
{
"code": null,
"e": 139022,
"s": 139005,
"text": "Object movements"
},
{
"code": null,
"e": 139111,
"s": 139022,
"text": "You might be interested in existing JavaScript based animation library: Script.Aculo.us."
},
{
"code": null,
"e": 139205,
"s": 139111,
"text": "This tutorial provides a basic understanding of how to use JavaScript to create an animation."
},
{
"code": null,
"e": 139400,
"s": 139205,
"text": "JavaScript can be used to move a number of DOM elements (<img />, <div> or any other HTML element) around the page according to some sort of pattern determined by a logical equation or function."
},
{
"code": null,
"e": 139493,
"s": 139400,
"text": "JavaScript provides the following two functions to be frequently used in animation programs."
},
{
"code": null,
"e": 139594,
"s": 139493,
"text": "setTimeout( function, duration) − This function calls function after duration milliseconds from now."
},
{
"code": null,
"e": 139695,
"s": 139594,
"text": "setTimeout( function, duration) − This function calls function after duration milliseconds from now."
},
{
"code": null,
"e": 139793,
"s": 139695,
"text": "setInterval(function, duration) − This function calls function after every duration milliseconds."
},
{
"code": null,
"e": 139891,
"s": 139793,
"text": "setInterval(function, duration) − This function calls function after every duration milliseconds."
},
{
"code": null,
"e": 139999,
"s": 139891,
"text": "clearTimeout(setTimeout_variable) − This function calls clears any timer set by the setTimeout() functions."
},
{
"code": null,
"e": 140107,
"s": 139999,
"text": "clearTimeout(setTimeout_variable) − This function calls clears any timer set by the setTimeout() functions."
},
{
"code": null,
"e": 140315,
"s": 140107,
"text": "JavaScript can also set a number of attributes of a DOM object including its position on the screen. You can set top and left attribute of an object to position it anywhere on the screen. Here is its syntax."
},
{
"code": null,
"e": 140513,
"s": 140315,
"text": "// Set distance from left edge of the screen.\nobject.style.left = distance in pixels or points; \n\nor\n\n// Set distance from top edge of the screen.\nobject.style.top = distance in pixels or points; \n"
},
{
"code": null,
"e": 140669,
"s": 140513,
"text": "So let's implement one simple animation using DOM object properties and JavaScript functions as follows. The following list contains different DOM methods."
},
{
"code": null,
"e": 140794,
"s": 140669,
"text": "We are using the JavaScript function getElementById() to get a DOM object and then assigning it to a global variable imgObj."
},
{
"code": null,
"e": 140919,
"s": 140794,
"text": "We are using the JavaScript function getElementById() to get a DOM object and then assigning it to a global variable imgObj."
},
{
"code": null,
"e": 141042,
"s": 140919,
"text": "We have defined an initialization function init() to initialize imgObj where we have set its position and left attributes."
},
{
"code": null,
"e": 141165,
"s": 141042,
"text": "We have defined an initialization function init() to initialize imgObj where we have set its position and left attributes."
},
{
"code": null,
"e": 141232,
"s": 141165,
"text": "We are calling initialization function at the time of window load."
},
{
"code": null,
"e": 141299,
"s": 141232,
"text": "We are calling initialization function at the time of window load."
},
{
"code": null,
"e": 141459,
"s": 141299,
"text": "Finally, we are calling moveRight() function to increase the left distance by 10 pixels. You could also set it to a negative value to move it to the left side."
},
{
"code": null,
"e": 141619,
"s": 141459,
"text": "Finally, we are calling moveRight() function to increase the left distance by 10 pixels. You could also set it to a negative value to move it to the left side."
},
{
"code": null,
"e": 141646,
"s": 141619,
"text": "Try the following example."
},
{
"code": null,
"e": 142491,
"s": 141646,
"text": "<html> \n <head>\n <title>JavaScript Animation</title> \n <script type = \"text/javascript\">\n <!--\n var imgObj = null;\n \n function init() {\n imgObj = document.getElementById('myImage');\n imgObj.style.position= 'relative'; \n imgObj.style.left = '0px'; \n }\n function moveRight() {\n imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';\n }\n \n window.onload = init;\n //-->\n </script>\n </head>\n \n <body> \n <form>\n <img id = \"myImage\" src = \"/images/html.gif\" />\n <p>Click button below to move the image to right</p>\n <input type = \"button\" value = \"Click Me\" onclick = \"moveRight();\" />\n </form> \n </body>\n</html>"
},
{
"code": null,
"e": 142537,
"s": 142491,
"text": "Click button below to move the image to right"
},
{
"code": null,
"e": 142700,
"s": 142537,
"text": "In the above example, we saw how an image moves to right with every click. We can automate this process by using the JavaScript function setTimeout() as follows −"
},
{
"code": null,
"e": 142765,
"s": 142700,
"text": "Here we have added more methods. So let's see what is new here −"
},
{
"code": null,
"e": 142854,
"s": 142765,
"text": "The moveRight() function is calling setTimeout() function to set the position of imgObj."
},
{
"code": null,
"e": 142943,
"s": 142854,
"text": "The moveRight() function is calling setTimeout() function to set the position of imgObj."
},
{
"code": null,
"e": 143074,
"s": 142943,
"text": "We have added a new function stop() to clear the timer set by setTimeout() function and to set the object at its initial position."
},
{
"code": null,
"e": 143205,
"s": 143074,
"text": "We have added a new function stop() to clear the timer set by setTimeout() function and to set the object at its initial position."
},
{
"code": null,
"e": 143237,
"s": 143205,
"text": "Try the following example code."
},
{
"code": null,
"e": 144380,
"s": 143237,
"text": "<html> \n <head>\n <title>JavaScript Animation</title> \n <script type = \"text/javascript\">\n <!--\n var imgObj = null;\n var animate ;\n \n function init() {\n imgObj = document.getElementById('myImage');\n imgObj.style.position= 'relative'; \n imgObj.style.left = '0px'; \n }\n function moveRight() {\n imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';\n animate = setTimeout(moveRight,20); // call moveRight in 20msec\n }\n function stop() {\n clearTimeout(animate);\n imgObj.style.left = '0px'; \n }\n \n window.onload = init;\n //-->\n </script>\n </head>\n \n <body> \n <form>\n <img id = \"myImage\" src = \"/images/html.gif\" />\n <p>Click the buttons below to handle animation</p>\n <input type = \"button\" value = \"Start\" onclick = \"moveRight();\" />\n <input type = \"button\" value = \"Stop\" onclick = \"stop();\" />\n </form> \n </body>\n</html>"
},
{
"code": null,
"e": 144424,
"s": 144380,
"text": "Click the buttons below to handle animation"
},
{
"code": null,
"e": 144492,
"s": 144424,
"text": "Here is a simple example showing image rollover with a mouse event."
},
{
"code": null,
"e": 144547,
"s": 144492,
"text": "Let's see what we are using in the following example −"
},
{
"code": null,
"e": 144715,
"s": 144547,
"text": "At the time of loading this page, the ‘if’ statement checks for the existence of the image object. If the image object is unavailable, this block will not be executed."
},
{
"code": null,
"e": 144883,
"s": 144715,
"text": "At the time of loading this page, the ‘if’ statement checks for the existence of the image object. If the image object is unavailable, this block will not be executed."
},
{
"code": null,
"e": 144962,
"s": 144883,
"text": "The Image() constructor creates and preloads a new image object called image1."
},
{
"code": null,
"e": 145041,
"s": 144962,
"text": "The Image() constructor creates and preloads a new image object called image1."
},
{
"code": null,
"e": 145131,
"s": 145041,
"text": "The src property is assigned the name of the external image file called /images/html.gif."
},
{
"code": null,
"e": 145221,
"s": 145131,
"text": "The src property is assigned the name of the external image file called /images/html.gif."
},
{
"code": null,
"e": 145308,
"s": 145221,
"text": "Similarly, we have created image2 object and assigned /images/http.gif in this object."
},
{
"code": null,
"e": 145395,
"s": 145308,
"text": "Similarly, we have created image2 object and assigned /images/http.gif in this object."
},
{
"code": null,
"e": 145516,
"s": 145395,
"text": "The # (hash mark) disables the link so that the browser does not try to go to a URL when clicked. This link is an image."
},
{
"code": null,
"e": 145637,
"s": 145516,
"text": "The # (hash mark) disables the link so that the browser does not try to go to a URL when clicked. This link is an image."
},
{
"code": null,
"e": 145825,
"s": 145637,
"text": "The onMouseOver event handler is triggered when the user's mouse moves onto the link, and the onMouseOut event handler is triggered when the user's mouse moves away from the link (image)."
},
{
"code": null,
"e": 146013,
"s": 145825,
"text": "The onMouseOver event handler is triggered when the user's mouse moves onto the link, and the onMouseOut event handler is triggered when the user's mouse moves away from the link (image)."
},
{
"code": null,
"e": 146191,
"s": 146013,
"text": "When the mouse moves over the image, the HTTP image changes from the first image to the second one. When the mouse is moved away from the image, the original image is displayed."
},
{
"code": null,
"e": 146369,
"s": 146191,
"text": "When the mouse moves over the image, the HTTP image changes from the first image to the second one. When the mouse is moved away from the image, the original image is displayed."
},
{
"code": null,
"e": 146469,
"s": 146369,
"text": "When the mouse is moved away from the link, the initial image html.gif will reappear on the screen."
},
{
"code": null,
"e": 146569,
"s": 146469,
"text": "When the mouse is moved away from the link, the initial image html.gif will reappear on the screen."
},
{
"code": null,
"e": 147324,
"s": 146569,
"text": "<html>\n \n <head>\n <title>Rollover with a Mouse Events</title>\n \n <script type = \"text/javascript\">\n <!--\n if(document.images) {\n var image1 = new Image(); // Preload an image\n image1.src = \"/images/html.gif\";\n var image2 = new Image(); // Preload second image\n image2.src = \"/images/http.gif\";\n }\n //-->\n </script>\n </head>\n \n <body>\n <p>Move your mouse over the image to see the result</p>\n \n <a href = \"#\" onMouseOver = \"document.myImage.src = image2.src;\"\n onMouseOut = \"document.myImage.src = image1.src;\">\n <img name = \"myImage\" src = \"/images/html.gif\" />\n </a>\n </body>\n</html>"
},
{
"code": null,
"e": 147373,
"s": 147324,
"text": "Move your mouse over the image to see the result"
},
{
"code": null,
"e": 147615,
"s": 147373,
"text": "The JavaScript navigator object includes a child object called plugins. This object is an array, with one entry for each plug-in installed on the browser. The navigator.plugins object is supported only by Netscape, Firefox, and Mozilla only."
},
{
"code": null,
"e": 147706,
"s": 147615,
"text": "Here is an example that shows how to list down all the plug-on installed in your browser −"
},
{
"code": null,
"e": 148509,
"s": 147706,
"text": "<html>\n <head>\n <title>List of Plug-Ins</title>\n </head>\n \n <body>\n <table border = \"1\">\n <tr>\n <th>Plug-in Name</th>\n <th>Filename</th>\n <th>Description</th>\n </tr>\n \n <script language = \"JavaScript\" type = \"text/javascript\">\n for (i = 0; i<navigator.plugins.length; i++) {\n document.write(\"<tr><td>\");\n document.write(navigator.plugins[i].name);\n document.write(\"</td><td>\");\n document.write(navigator.plugins[i].filename);\n document.write(\"</td><td>\");\n document.write(navigator.plugins[i].description);\n document.write(\"</td></tr>\");\n }\n </script>\n </table> \n </body>\n</html>"
},
{
"code": null,
"e": 148591,
"s": 148509,
"text": "Each plug-in has an entry in the array. Each entry has the following properties −"
},
{
"code": null,
"e": 148626,
"s": 148591,
"text": "name − is the name of the plug-in."
},
{
"code": null,
"e": 148661,
"s": 148626,
"text": "name − is the name of the plug-in."
},
{
"code": null,
"e": 148735,
"s": 148661,
"text": "filename − is the executable file that was loaded to install the plug-in."
},
{
"code": null,
"e": 148809,
"s": 148735,
"text": "filename − is the executable file that was loaded to install the plug-in."
},
{
"code": null,
"e": 148883,
"s": 148809,
"text": "description − is a description of the plug-in, supplied by the developer."
},
{
"code": null,
"e": 148957,
"s": 148883,
"text": "description − is a description of the plug-in, supplied by the developer."
},
{
"code": null,
"e": 149041,
"s": 148957,
"text": "mimeTypes − is an array with one entry for each MIME type supported by the plug-in."
},
{
"code": null,
"e": 149125,
"s": 149041,
"text": "mimeTypes − is an array with one entry for each MIME type supported by the plug-in."
},
{
"code": null,
"e": 149309,
"s": 149125,
"text": "You can use these properties in a script to find out the installed plug-ins, and then using JavaScript, you can play appropriate multimedia file. Take a look at the following example."
},
{
"code": null,
"e": 149778,
"s": 149309,
"text": "<html> \n <head>\n <title>Using Plug-Ins</title>\n </head>\n \n <body> \n <script language = \"JavaScript\" type = \"text/javascript\">\n media = navigator.mimeTypes[\"video/quicktime\"];\n \n if (media) {\n document.write(\"<embed src = 'quick.mov' height = 100 width = 100>\");\n } else {\n document.write(\"<img src = 'quick.gif' height = 100 width = 100>\");\n }\n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 149848,
"s": 149778,
"text": "NOTE − Here we are using HTML <embed> tag to embed a multimedia file."
},
{
"code": null,
"e": 149918,
"s": 149848,
"text": "Let us take one real example which works in almost all the browsers −"
},
{
"code": null,
"e": 151193,
"s": 149918,
"text": "<html> \n <head>\n <title>Using Embeded Object</title>\n \n <script type = \"text/javascript\">\n <!--\n function play() {\n if (!document.demo.IsPlaying()) {\n document.demo.Play();\n }\n }\n function stop() {\n if (document.demo.IsPlaying()) {\n document.demo.StopPlay();\n }\n }\n function rewind() {\n if (document.demo.IsPlaying()) {\n document.demo.StopPlay();\n }\n document.demo.Rewind();\n }\n //-->\n </script>\n </head>\n \n <body> \n <embed id = \"demo\" name = \"demo\"\n src = \"http://www.amrood.com/games/kumite.swf\"\n width = \"318\" height = \"300\" play = \"false\" loop = \"false\"\n pluginspage = \"http://www.macromedia.com/go/getflashplayer\"\n swliveconnect = \"true\">\n \n <form name = \"form\" id = \"form\" action = \"#\" method = \"get\">\n <input type = \"button\" value = \"Start\" onclick = \"play();\" />\n <input type = \"button\" value = \"Stop\" onclick = \"stop();\" />\n <input type = \"button\" value = \"Rewind\" onclick = \"rewind();\" />\n </form> \n </body>\n</html>"
},
{
"code": null,
"e": 151245,
"s": 151193,
"text": "If you are using Mozilla, Firefox or Netscape, then"
},
{
"code": null,
"e": 151366,
"s": 151245,
"text": "Every now and then, developers commit mistakes while coding. A mistake in a program or a script is referred to as a bug."
},
{
"code": null,
"e": 151556,
"s": 151366,
"text": "The process of finding and fixing bugs is called debugging and is a normal part of the development process. This section covers tools and techniques that can help you with debugging tasks.."
},
{
"code": null,
"e": 151750,
"s": 151556,
"text": "The most basic way to track down errors is by turning on error information in your browser. By default, Internet Explorer shows an error icon in the status bar when an error occurs on the page."
},
{
"code": null,
"e": 151862,
"s": 151750,
"text": "Double-clicking this icon takes you to a dialog box showing information about the specific error that occurred."
},
{
"code": null,
"e": 152007,
"s": 151862,
"text": "Since this icon is easy to overlook, Internet Explorer gives you the option to automatically show the Error dialog box whenever an error occurs."
},
{
"code": null,
"e": 152183,
"s": 152007,
"text": "To enable this option, select Tools → Internet Options → Advanced tab. and then finally check the \"Display a Notification About Every Script Error\" box option as shown below −"
},
{
"code": null,
"e": 152390,
"s": 152183,
"text": "Other browsers like Firefox, Netscape, and Mozilla send error messages to a special window called the JavaScript Console or Error Consol. To view the console, select Tools → Error Consol or Web Development."
},
{
"code": null,
"e": 152551,
"s": 152390,
"text": "Unfortunately, since these browsers give no visual indication when an error occurs, you must keep the Console open and watch for errors as your script executes."
},
{
"code": null,
"e": 152765,
"s": 152551,
"text": "Error notifications that show up on Console or through Internet Explorer dialog boxes are the result of both syntax and runtime errors. These error notification include the line number at which the error occurred."
},
{
"code": null,
"e": 152906,
"s": 152765,
"text": "If you are using Firefox, then you can click on the error available in the error console to go to the exact line in the script having error."
},
{
"code": null,
"e": 152956,
"s": 152906,
"text": "There are various ways to debug your JavaScript −"
},
{
"code": null,
"e": 153280,
"s": 152956,
"text": "One way to check your JavaScript code for strange bugs is to run it through a program that checks it to make sure it is valid and that it follows the official syntax rules of the language. These programs are called validating parsers or just validators for short, and often come with commercial HTML and JavaScript editors."
},
{
"code": null,
"e": 153433,
"s": 153280,
"text": "The most convenient validator for JavaScript is Douglas Crockford's JavaScript Lint, which is available for free at Douglas Crockford's JavaScript Lint."
},
{
"code": null,
"e": 153810,
"s": 153433,
"text": "Simply visit that web page, paste your JavaScript (Only JavaScript) code into the text area provided, and click the jslint button. This program will parse through your JavaScript code, ensuring that all the variable and function definitions follow the correct syntax. It will also check JavaScript statements, such as if and while, to ensure they too follow the correct format"
},
{
"code": null,
"e": 153950,
"s": 153810,
"text": "You can use the alert() or document.write() methods in your program to debug your code. For example, you might write something as follows −"
},
{
"code": null,
"e": 154203,
"s": 153950,
"text": "var debugging = true;\nvar whichImage = \"widget\";\n\nif( debugging )\n alert( \"Calls swapImage() with argument: \" + whichImage );\n var swapStatus = swapImage( whichImage );\n\nif( debugging )\n alert( \"Exits swapImage() with swapStatus=\" + swapStatus );"
},
{
"code": null,
"e": 154325,
"s": 154203,
"text": "By examining the content and order of the alert() as they appear, you can examine the health of your program very easily."
},
{
"code": null,
"e": 154608,
"s": 154325,
"text": "A debugger is an application that places all aspects of script execution under the control of the programmer. Debuggers provide fine-grained control over the state of the script through an interface that allows you to examine and set values as well as control the flow of execution."
},
{
"code": null,
"e": 154932,
"s": 154608,
"text": "Once a script has been loaded into a debugger, it can be run one line at a time or instructed to halt at certain breakpoints. Once execution is halted, the programmer can examine the state of the script and its variables in order to determine if something is amiss. You can also watch variables for changes in their values."
},
{
"code": null,
"e": 155106,
"s": 154932,
"text": "The latest version of the Mozilla JavaScript Debugger (code-named Venkman) for both Mozilla and Netscape browsers can be downloaded at http://www.hacksrus.com/~ginda/venkman"
},
{
"code": null,
"e": 155230,
"s": 155106,
"text": "You can keep the following tips in mind to reduce the number of errors in your scripts and simplify the debugging process −"
},
{
"code": null,
"e": 155382,
"s": 155230,
"text": "Use plenty of comments. Comments enable you to explain why you wrote the script the way you did and to explain particularly difficult sections of code."
},
{
"code": null,
"e": 155534,
"s": 155382,
"text": "Use plenty of comments. Comments enable you to explain why you wrote the script the way you did and to explain particularly difficult sections of code."
},
{
"code": null,
"e": 155728,
"s": 155534,
"text": "Always use indentation to make your code easy to read. Indenting statements also makes it easier for you to match up beginning and ending tags, curly braces, and other HTML and script elements."
},
{
"code": null,
"e": 155922,
"s": 155728,
"text": "Always use indentation to make your code easy to read. Indenting statements also makes it easier for you to match up beginning and ending tags, curly braces, and other HTML and script elements."
},
{
"code": null,
"e": 156100,
"s": 155922,
"text": "Write modular code. Whenever possible, group your statements into functions. Functions let you group related statements, and test and reuse portions of code with minimal effort."
},
{
"code": null,
"e": 156278,
"s": 156100,
"text": "Write modular code. Whenever possible, group your statements into functions. Functions let you group related statements, and test and reuse portions of code with minimal effort."
},
{
"code": null,
"e": 156475,
"s": 156278,
"text": "Be consistent in the way you name your variables and functions. Try using names that are long enough to be meaningful and that describe the contents of the variable or the purpose of the function."
},
{
"code": null,
"e": 156672,
"s": 156475,
"text": "Be consistent in the way you name your variables and functions. Try using names that are long enough to be meaningful and that describe the contents of the variable or the purpose of the function."
},
{
"code": null,
"e": 156845,
"s": 156672,
"text": "Use consistent syntax when naming variables and functions. In other words, keep them all lowercase or all uppercase; if you prefer Camel-Back notation, use it consistently."
},
{
"code": null,
"e": 157018,
"s": 156845,
"text": "Use consistent syntax when naming variables and functions. In other words, keep them all lowercase or all uppercase; if you prefer Camel-Back notation, use it consistently."
},
{
"code": null,
"e": 157219,
"s": 157018,
"text": "Test long scripts in a modular fashion. In other words, do not try to write the entire script before testing any portion of it. Write a piece and get it to work before adding the next portion of code."
},
{
"code": null,
"e": 157420,
"s": 157219,
"text": "Test long scripts in a modular fashion. In other words, do not try to write the entire script before testing any portion of it. Write a piece and get it to work before adding the next portion of code."
},
{
"code": null,
"e": 157504,
"s": 157420,
"text": "Use descriptive variable and function names and avoid using single-character names."
},
{
"code": null,
"e": 157588,
"s": 157504,
"text": "Use descriptive variable and function names and avoid using single-character names."
},
{
"code": null,
"e": 157762,
"s": 157588,
"text": "Watch your quotation marks. Remember that quotation marks are used in pairs around strings and that both quotation marks must be of the same style (either single or double)."
},
{
"code": null,
"e": 157936,
"s": 157762,
"text": "Watch your quotation marks. Remember that quotation marks are used in pairs around strings and that both quotation marks must be of the same style (either single or double)."
},
{
"code": null,
"e": 158015,
"s": 157936,
"text": "Watch your equal signs. You should not used a single = for comparison purpose."
},
{
"code": null,
"e": 158094,
"s": 158015,
"text": "Watch your equal signs. You should not used a single = for comparison purpose."
},
{
"code": null,
"e": 158146,
"s": 158094,
"text": "Declare variables explicitly using the var keyword."
},
{
"code": null,
"e": 158198,
"s": 158146,
"text": "Declare variables explicitly using the var keyword."
},
{
"code": null,
"e": 158389,
"s": 158198,
"text": "You can use JavaScript to create client-side image map. Client-side image maps are enabled by the usemap attribute for the <img /> tag and defined by special <map> and <area> extension tags."
},
{
"code": null,
"e": 158703,
"s": 158389,
"text": "The image that is going to form the map is inserted into the page using the <img /> element as normal, except that it carries an extra attribute called usemap. The value of the usemap attribute is the value of the name attribute on the <map> element, which you are about to meet, preceded by a pound or hash sign."
},
{
"code": null,
"e": 159085,
"s": 158703,
"text": "The <map> element actually creates the map for the image and usually follows directly after the <img /> element. It acts as a container for the <area /> elements that actually define the clickable hotspots. The <map> element carries only one attribute, the name attribute, which is the name that identifies the map. This is how the <img /> element knows which <map> element to use."
},
{
"code": null,
"e": 159198,
"s": 159085,
"text": "The <area> element specifies the shape and the coordinates that define the boundaries of each clickable hotspot."
},
{
"code": null,
"e": 159344,
"s": 159198,
"text": "The following code combines imagemaps and JavaScript to produce a message in a text box when the mouse is moved over different parts of an image."
},
{
"code": null,
"e": 160728,
"s": 159344,
"text": "<html> \n <head>\n <title>Using JavaScript Image Map</title>\n \n <script type = \"text/javascript\">\n <!--\n function showTutorial(name) {\n document.myform.stage.value = name\n }\n //-->\n </script>\n </head>\n \n <body>\n <form name = \"myform\">\n <input type = \"text\" name = \"stage\" size = \"20\" />\n </form>\n \n <!-- Create Mappings -->\n <img src = \"/images/usemap.gif\" alt = \"HTML Map\" border = \"0\" usemap = \"#tutorials\"/>\n \n <map name = \"tutorials\">\n <area shape=\"poly\" \n coords = \"74,0,113,29,98,72,52,72,38,27\"\n href = \"/perl/index.htm\" alt = \"Perl Tutorial\"\n target = \"_self\" \n onMouseOver = \"showTutorial('perl')\" \n onMouseOut = \"showTutorial('')\"/>\n \n <area shape = \"rect\" \n coords = \"22,83,126,125\"\n href = \"/html/index.htm\" alt = \"HTML Tutorial\" \n target = \"_self\" \n onMouseOver = \"showTutorial('html')\" \n onMouseOut = \"showTutorial('')\"/>\n \n <area shape = \"circle\" \n coords = \"73,168,32\"\n href = \"/php/index.htm\" alt = \"PHP Tutorial\"\n target = \"_self\" \n onMouseOver = \"showTutorial('php')\" \n onMouseOut = \"showTutorial('')\"/>\n </map>\n </body>\n</html>"
},
{
"code": null,
"e": 160806,
"s": 160728,
"text": "You can feel the map concept by placing the mouse cursor on the image object."
},
{
"code": null,
"e": 161000,
"s": 160806,
"text": "It is important to understand the differences between different browsers in order to handle each in the way it is expected. So it is important to know which browser your web page is running in."
},
{
"code": null,
"e": 161110,
"s": 161000,
"text": "To get information about the browser your webpage is currently running in, use the built-in navigator object."
},
{
"code": null,
"e": 161255,
"s": 161110,
"text": "There are several Navigator related properties that you can use in your Web page. The following is a list of the names and descriptions of each."
},
{
"code": null,
"e": 161267,
"s": 161255,
"text": "appCodeName"
},
{
"code": null,
"e": 161414,
"s": 161267,
"text": "This property is a string that contains the code name of the browser, Netscape for Netscape and Microsoft Internet Explorer for Internet Explorer."
},
{
"code": null,
"e": 161425,
"s": 161414,
"text": "appVersion"
},
{
"code": null,
"e": 161568,
"s": 161425,
"text": "This property is a string that contains the version of the browser as well as other useful information such as its language and compatibility."
},
{
"code": null,
"e": 161577,
"s": 161568,
"text": "language"
},
{
"code": null,
"e": 161689,
"s": 161577,
"text": "This property contains the two-letter abbreviation for the language that is used by the browser. Netscape only."
},
{
"code": null,
"e": 161700,
"s": 161689,
"text": "mimTypes[]"
},
{
"code": null,
"e": 161795,
"s": 161700,
"text": "This property is an array that contains all MIME types supported by the client. Netscape only."
},
{
"code": null,
"e": 161806,
"s": 161795,
"text": "platform[]"
},
{
"code": null,
"e": 161939,
"s": 161806,
"text": "This property is a string that contains the platform for which the browser was compiled.\"Win32\" for 32-bit Windows operating systems"
},
{
"code": null,
"e": 161949,
"s": 161939,
"text": "plugins[]"
},
{
"code": null,
"e": 162058,
"s": 161949,
"text": "This property is an array containing all the plug-ins that have been installed on the client. Netscape only."
},
{
"code": null,
"e": 162070,
"s": 162058,
"text": "userAgent[]"
},
{
"code": null,
"e": 162221,
"s": 162070,
"text": "This property is a string that contains the code name and version of the browser. This value is sent to the originating server to identify the client."
},
{
"code": null,
"e": 162315,
"s": 162221,
"text": "There are several Navigator-specific methods. Here is a list of their names and descriptions."
},
{
"code": null,
"e": 162329,
"s": 162315,
"text": "javaEnabled()"
},
{
"code": null,
"e": 162473,
"s": 162329,
"text": "This method determines if JavaScript is enabled in the client. If JavaScript is enabled, this method returns true; otherwise, it returns false."
},
{
"code": null,
"e": 162490,
"s": 162473,
"text": "plugings.refresh"
},
{
"code": null,
"e": 162618,
"s": 162490,
"text": "This method makes newly installed plug-ins available and populates the plugins array with all new plug-in names. Netscape only."
},
{
"code": null,
"e": 162641,
"s": 162618,
"text": "preference(name,value)"
},
{
"code": null,
"e": 162862,
"s": 162641,
"text": "This method allows a signed script to get and set some Netscape preferences. If the second parameter is omitted, this method will return the value of the specified preference; otherwise, it sets the value. Netscape only."
},
{
"code": null,
"e": 162877,
"s": 162862,
"text": "taintEnabled()"
},
{
"code": null,
"e": 162948,
"s": 162877,
"text": "This method returns true if data tainting is enabled; false otherwise."
},
{
"code": null,
"e": 163090,
"s": 162948,
"text": "There is a simple JavaScript which can be used to find out the name of a browser and then accordingly an HTML page can be served to the user."
},
{
"code": null,
"e": 164475,
"s": 163090,
"text": "<html> \n <head>\n <title>Browser Detection Example</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n <!--\n var userAgent = navigator.userAgent;\n var opera = (userAgent.indexOf('Opera') != -1);\n var ie = (userAgent.indexOf('MSIE') != -1);\n var gecko = (userAgent.indexOf('Gecko') != -1);\n var netscape = (userAgent.indexOf('Mozilla') != -1);\n var version = navigator.appVersion;\n \n if (opera) {\n document.write(\"Opera based browser\");\n // Keep your opera specific URL here.\n } else if (gecko) {\n document.write(\"Mozilla based browser\");\n // Keep your gecko specific URL here.\n } else if (ie) {\n document.write(\"IE based browser\");\n // Keep your IE specific URL here.\n } else if (netscape) {\n document.write(\"Netscape based browser\");\n // Keep your Netscape specific URL here.\n } else {\n document.write(\"Unknown browser\");\n }\n \n // You can include version to along with any above condition.\n document.write(\"<br /> Browser version info : \" + version );\n //-->\n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 164510,
"s": 164475,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 164524,
"s": 164510,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 164558,
"s": 164524,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 164572,
"s": 164558,
"text": " Lets Kode It"
},
{
"code": null,
"e": 164607,
"s": 164572,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 164624,
"s": 164607,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 164659,
"s": 164624,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 164676,
"s": 164659,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 164709,
"s": 164676,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 164737,
"s": 164709,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 164771,
"s": 164737,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 164799,
"s": 164771,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 164806,
"s": 164799,
"text": " Print"
},
{
"code": null,
"e": 164817,
"s": 164806,
"text": " Add Notes"
}
] |
Five Regression Python Modules That Every Data Scientist Must Know | by Damian Ejlli | Towards Data Science
|
Regression is a very important concept in statistical modelling, data science, and machine learning that helps establish a possible relationship between an independent variable (or predictor), x, with a dependent variable (or simply output) y(x) by using specific mathematical minimisation criteria. There are several types of regression that are used in different situations and one of the most common is linear regression. Other types of regression include logistic regression, non-linear regression, etc.
In Python, there are several libraries and corresponding modules that can be used to perform regression depending on a specific problem that one encounters and its complexity. In this article, I will summarise the five most important modules and libraries in Python that one can use to perform regression and also will discuss some of their limitations. Here I assume that the reader knows Python and some of its most important libraries.
NumPy that stands for Numerical Python is probably the most important and efficient Python library for numerical calculations involving arrays. In addition to several operations for numerical calculations, NumPy has also a module that can perform simple linear regression and polynomial regression. To make things more clear it is better to give a specific example involving NumPy arrays that represent realistic data as below:
import numpy as npx = np.array([ 56755.72171242, 44178.04737774, 40991.80813814, 8814.00098681, 43585.51198178, 13574.17183072, 6175.8760297 , 17829.69832237, 53254.85637009, 17522.23018625, 42784.69836164, 36638.18492916, 41086.72967373, 18167.77372717, 12706.89121489, 52564.42917946, 61995.42280258, 35776.79516181, 30230.22630213, 34524.46986093, 13774.60527391, 14258.22933451, 101376.49657434, 9616.64500569, 45175.23189338, 38615.99518491, 74355.51585756, 12578.49547344, 19242.3664711 , 16310.988409 , 20881.76692993, 5734.63362915, 25732.01836475, 51545.48360953, 82081.59716162, 11006.2497364 , 44974.83187718, 56839.38177423])y = np.array([7.3, 7.1, 6.9, 6.4, 7.4, 6.5, 6.3, 6.7, 7.6, 5.7, 7.6, 6.5, 7.0, 5.4, 5.6, 7.5, 7.0, 7.2, 6.0, 5.9, 5.9, 5.9, 6.9, 6.5, 7.4, 7.3, 7.6, 6.1, 5.4, 6.2, 5.9, 4.7, 6.3, 7.3, 7.5, 5.5, 6.8, 6.9])
The NumPy array x represents the GDP per capita in USD for a given country and the array y represents the life satisfaction value of people in a given country. The life satisfaction value is in the range [0, 10] where a value of 10 corresponds to a maximum satisfaction while a value of 0 is the total absence of satisfaction. The details of what is the relation between life satisfaction and GDP per capita for several countries can be found on my GitHub page.
As mentioned above, the NumPy library has an option that gives the user the possibility to perform a linear regression (simple and polynomial) by using the least square method as minimization criteria. The module that does this regression is polyfit: np.polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False). The x array is of shape (M, ) while the y array is of shape (M, K) where M and K are positive natural numbers. In addition, np.polyfit() gives the possibility to specify the degree of polynomial regression with the “deg = n” and also can calculate the covariance matrix that gives important information about the coefficients of the polynomial regression. polyfit, fits the data by using the least square method and internally memorises the coefficients of the linear regression found during the fitting procedure. To plot the linear regression function one needs to convert the already found polynomial coefficients into a polynomial function through the function np.poly1d().
As an example, now I use the np.polyfit() function to perform a simple linear regression (n = 1) on the x and y arrays above and plot the result. I use the following Python code:
[In]: import matplotlib.pyplot as plt[In]: p = np.poly1d(np.polyfit(x, y, 1))[In]: x_line = np.linspace(np.amin(x), np.amax(x), 200)[In]: plt.scatter(x, y)[In]: plt.plot(x_line, p(x_line))[In]: plt.show()
You can run the above Python code in your computer to show the plot of the simple linear regression, however, here I do not show the plot for sake of clarity. Moreover, polyfit gives the user the possibility to know the coefficients of the linear regression. Indeed, if you display the variable p in the above code you will get the following linear regression line with the equation:
[In]: print(p)[Out]: 2.4e-05 x + 5.742
So, the linear regression with np.polyfit() gave as a result a linear regression line (y(x) = a + bx) with intercept, a=5.741 (precise value), and slope, b =2.39e-05 (precise value). The print(p) command gives an approximate value display.
The polyfit module is very useful for fitting simple linear regression and polynomial regression of degree n. However, it does not give the user the possibility to use linear regression with multiple predictor variables, namely multivariate regression. So, it is not possible to use np.polyfit() for mixed interaction terms but only for self-interaction terms. In addition, it does not give the user the possibility to directly calculate: the coefficient of determination R2 to assess the goodness of the fit, the Pearson correlation coefficient r, the p-value of hypothesis testing, and sample errors associated with the regression coefficients.
SciPy is a Python library that stands for Scientific Python. It is the most important library for scientific computing that is used in academia and the scientific industry. This library contains several modules that are used for specific purposes. Among these modules, the scipy.stats() module, is the most important one regarding statistical modelling in general. The scipy.stats() module has a submodule completely dedicated to linear regression which goes under the syntax: scipy.stats.linregress() and uses the least square method as a minimisation criteria.
Now to see linregress in action, I use again the arrays x and y as above and use the following Python code:
[In]: import scipy as sp[In]: regr_results = sp.stats.linregress(x, y)[In]: print(regr_results)[Out]: LinregressResult(slope=2.3996299825729513e-05, intercept=5.741754353755326, rvalue=0.720287195322656, pvalue=3.4265564700646986e-07, stderr=3.851624914535862e-06, intercept_stderr=0.15853194959552008)
As you can see from the above Python code, the linregress module gives as an output the results of the linear regression, where the intercept value is, a = 5.741 and, the slope value is b = 2.39e-05. These values of a and b are the same as those found by using the polyfit module of NumPy as in the previous section. In addition, linregress evaluates the Pearson correlation coefficient r (with value of rvalue = 0.72), the p-value (pvalue = 3.42e-06), the standard deviation of the slope b (stderr = 3.85e-06), and the standard error of the intercept term a (intercept_stderr = 0.15). Explicit calculations and Python codes can be found in my GitHub page.
The linregress module gives additional results of the linear regression to the polyfit module as shown above. The only disadvantage of linregress is that does not support multivariate regression. It only supports simple linear regression. In addition, it does not give to the user the option to directly predict new values for features not used in the least square method like the scikit-learn library as in section 5 below.
The statsmodels library/module is an extension of the scipy.stats module that is mainly used for fitting a model to a given dataset. This module is probably the most complete one regarding regression in general and also linear regression in particular. This module is quite flexible and it gives the user several options to perform specific statistical calculations.
As I did in sections 2 and 3, I use the statsmodel to perform a simple linear regression by using the x, and y arrays as above and using the least square method as minimisation criteria with the OLS module. I use the following Python code:
[In]: import statsmodels.api as sm[In]: x = sm.add_constant(x) # Adds an intercept term to the simple linear regression formula[In]: lin_model = sm.OLS(y, x)[In]: regr_results = lin_model.fit()[In]: print(regr_results.results)[Out]: [5.74175435e+00 2.39962998e-05]
After printing the results with the above code, I get the following values for intercept a = 5.741 and slope b = 2.39e-05 of the simple linear regression on x and y arrays. The OLS module implicitly uses the least square minimisation method for calculating the regression coefficients. One can note that the values of a and b coincide with those previously found in sections 1 and 2 with other methods.
A more detailed description of the regression results can be obtained with the python command print(regr_results.summary()) where the results table is shown in Fig. 2. As you can see, the summary table gives a detailed information of the linear regression results that include: the coefficient of determination R2, the value of the intercept a and its standard deviation, the value of the slope b and its standard deviation, the value of the t score, the p-value, the confidence interval, etc.
The OLS module and its equivalent module, ols (I do not explicitly discuss about ols module in this article) have an advantage to the linregress module since they can perform multivariate linear regression. On the other hand, the disadvantage of the module ols, is that it does not have the option to directly predict new values y for new values of predictors x_i (at least not known to me). Also, another disadvantage of the OLS module is that one has to add explicitly a constant term for the linear regression with the command sm.add_constant(). The linear_model.OLS module, on the other hand, gives the user the possibility to predict new values given a design matrix similar to the LinearRegression module of scikit-learn.
scikit-learn is one of the best Python libraries for statistical/machine learning and it is adapted for fitting and making predictions. It gives the user different options for numerical calculations and statistical modelling. Its most important sub-module for linear regression is LinearRegression. It uses the least square method as minimisation criteria to find the parameters of the linear regression.
As I did in the previous sections, I use the arrays x and y as above for simple linear regression. I use the following Python code:
[In]: from sklearn import linear_model[In]: linmodel = linear_model.LinearRegression(fit_intercept=True) [In]: linmodel.fit(x.reshape(-1, 1), y)[Out]: LinearRegression()
The above Python code uses linear regression to fit the data contained in the x and y arrays. If now one needs to get some of the parameters from the fit, it is necessary to write an additional code. For example, I want to see the values of intercept a and slope b of the fitting procedure. To do this, I run the following Python code:
[In]: (slope, intercept) = (linmodel.coef_[0], linmodel.intercept_)[In]: print(slope, intercept)[Out]: 2.3996299825729496e-05 5.741754353755327
As you can see, the LinearRegression module gives the same values of intercept a and slope b as previously found by using other methods. In addition, it is also possible to calculate the coefficient of determination R2 with the Python command: print(linmodel.score(x.reshape(-1, 1), y)) which gives a value of R2 = 0.518 that is the same as that given by using OLS module results of Fig. 2.
The advantage of the LinearRegression module is that it gives the user the possibility to directly predict new values for new data with the linmodel.predict() command. This function makes the LinearRegression module very appealing for statistical/machine learning. As the OLS module, the LinearRegression module can also perform multivariate linear regression if needed. The disadvantage of LinearRegression module is that it does not have a summary table of the regression results as the OLS module and it forces the user to explicitly write new commands to get important statistical information. Also, it can be quite cumbersome to use the LinearRegression module for polynomial regression since one needs to calculate the design matrix X before getting the regression results. One can see this explicitly in my previous article.
The seaborn Python library is a very important library for visualisation of statistical results. Technically, it is not a library that can be used to calculate the regression parameters as I showed in the previous sections, but it can be used to graphically visualise the regression lines and confidence regions in a plot. For example, if I want to plot the simple linear regression line obtained in the previous sections, I need to run the following Python code:
[In]: import seaborn as sns[In]: import matplotlib.pyplot as plt[In]: fig, ax = plt.subplots(figsize=(10, 6))sns.regplot(x = x, y = y, ci=95, order=1,line_kws={'label': 'Linear regression line: $Y(X)=5.74+2.39\cdot 10^{-5} X$', 'color': 'm'}, seed=1,truncate=False, label="Original data")ax.set_xlabel("GDP per capita 2015 (USD)")ax.set_ylabel("Life Satisfaction Value")ax.set_xticks([1000, 10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000, 90000, 100000])ax.set_yticks(np.arange(3.0, 10.5, 0.5))ax.legend(loc="upper left")
The result of the above code gives exactly Fig. 1 as shown at the top of this article. The regplot module of seaborn internally calculates the values of the linear regression parameters and it plots the linear regression line with the 95% confidence zone (I set the parameter “ci=95” in the above code) of the linear regression parameters. Also, the regplot module can perform graphical visulalization of multivariate linear regression and logistic regression since this module is strongly based on the statsmodel library. The only disadvantage of seaborn in general is that it does not give to the user the possibility to directly see the regression results with a specific Python command.
In this article, I summarised the most import python libraries and their modules for regression and I gave specific examples for linear regression. The advantage of a module over another one depends on a specific problem that the user faces. For simple linear regression and polynomial regression, the polyfit and linregress modules are the easiest to use and very handy. On the other hand for detailed statistical results of linear regression, the OLS and ols modules are probably the best since they are not difficult to use and give plenty of regression results in a summary table. Also, the OLS sub-module of the linear_model, gives the user the possibility to make prediction as well with the help of the linear_model.OLS module. For statistical/machine learning, the LinearRegression module of the scikit-learn Python library is one of the best since it can be used to make predictions, a functionality that the majority of other mentioned modules above do not have. If ones desires to plot the results of a statistical procedure directly without information of the fitting parameter values, then the regplot module of seaborn is one of the best.
In my summary of the best Python modules for regression, I did not include the Pandas library even though it is possible to calculate some parameters of linear regression explicitly such as the Pearson coefficient r etc., see my GitHub page for details. Also, the lsqt module of NumPy gives the possibility to do some regression but both Pandas library and lsqt module are at an inferior level compared to the modules mentioned in the above sections.
|
[
{
"code": null,
"e": 680,
"s": 172,
"text": "Regression is a very important concept in statistical modelling, data science, and machine learning that helps establish a possible relationship between an independent variable (or predictor), x, with a dependent variable (or simply output) y(x) by using specific mathematical minimisation criteria. There are several types of regression that are used in different situations and one of the most common is linear regression. Other types of regression include logistic regression, non-linear regression, etc."
},
{
"code": null,
"e": 1119,
"s": 680,
"text": "In Python, there are several libraries and corresponding modules that can be used to perform regression depending on a specific problem that one encounters and its complexity. In this article, I will summarise the five most important modules and libraries in Python that one can use to perform regression and also will discuss some of their limitations. Here I assume that the reader knows Python and some of its most important libraries."
},
{
"code": null,
"e": 1547,
"s": 1119,
"text": "NumPy that stands for Numerical Python is probably the most important and efficient Python library for numerical calculations involving arrays. In addition to several operations for numerical calculations, NumPy has also a module that can perform simple linear regression and polynomial regression. To make things more clear it is better to give a specific example involving NumPy arrays that represent realistic data as below:"
},
{
"code": null,
"e": 2421,
"s": 1547,
"text": "import numpy as npx = np.array([ 56755.72171242, 44178.04737774, 40991.80813814, 8814.00098681, 43585.51198178, 13574.17183072, 6175.8760297 , 17829.69832237, 53254.85637009, 17522.23018625, 42784.69836164, 36638.18492916, 41086.72967373, 18167.77372717, 12706.89121489, 52564.42917946, 61995.42280258, 35776.79516181, 30230.22630213, 34524.46986093, 13774.60527391, 14258.22933451, 101376.49657434, 9616.64500569, 45175.23189338, 38615.99518491, 74355.51585756, 12578.49547344, 19242.3664711 , 16310.988409 , 20881.76692993, 5734.63362915, 25732.01836475, 51545.48360953, 82081.59716162, 11006.2497364 , 44974.83187718, 56839.38177423])y = np.array([7.3, 7.1, 6.9, 6.4, 7.4, 6.5, 6.3, 6.7, 7.6, 5.7, 7.6, 6.5, 7.0, 5.4, 5.6, 7.5, 7.0, 7.2, 6.0, 5.9, 5.9, 5.9, 6.9, 6.5, 7.4, 7.3, 7.6, 6.1, 5.4, 6.2, 5.9, 4.7, 6.3, 7.3, 7.5, 5.5, 6.8, 6.9])"
},
{
"code": null,
"e": 2883,
"s": 2421,
"text": "The NumPy array x represents the GDP per capita in USD for a given country and the array y represents the life satisfaction value of people in a given country. The life satisfaction value is in the range [0, 10] where a value of 10 corresponds to a maximum satisfaction while a value of 0 is the total absence of satisfaction. The details of what is the relation between life satisfaction and GDP per capita for several countries can be found on my GitHub page."
},
{
"code": null,
"e": 3878,
"s": 2883,
"text": "As mentioned above, the NumPy library has an option that gives the user the possibility to perform a linear regression (simple and polynomial) by using the least square method as minimization criteria. The module that does this regression is polyfit: np.polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False). The x array is of shape (M, ) while the y array is of shape (M, K) where M and K are positive natural numbers. In addition, np.polyfit() gives the possibility to specify the degree of polynomial regression with the “deg = n” and also can calculate the covariance matrix that gives important information about the coefficients of the polynomial regression. polyfit, fits the data by using the least square method and internally memorises the coefficients of the linear regression found during the fitting procedure. To plot the linear regression function one needs to convert the already found polynomial coefficients into a polynomial function through the function np.poly1d()."
},
{
"code": null,
"e": 4057,
"s": 3878,
"text": "As an example, now I use the np.polyfit() function to perform a simple linear regression (n = 1) on the x and y arrays above and plot the result. I use the following Python code:"
},
{
"code": null,
"e": 4262,
"s": 4057,
"text": "[In]: import matplotlib.pyplot as plt[In]: p = np.poly1d(np.polyfit(x, y, 1))[In]: x_line = np.linspace(np.amin(x), np.amax(x), 200)[In]: plt.scatter(x, y)[In]: plt.plot(x_line, p(x_line))[In]: plt.show()"
},
{
"code": null,
"e": 4646,
"s": 4262,
"text": "You can run the above Python code in your computer to show the plot of the simple linear regression, however, here I do not show the plot for sake of clarity. Moreover, polyfit gives the user the possibility to know the coefficients of the linear regression. Indeed, if you display the variable p in the above code you will get the following linear regression line with the equation:"
},
{
"code": null,
"e": 4685,
"s": 4646,
"text": "[In]: print(p)[Out]: 2.4e-05 x + 5.742"
},
{
"code": null,
"e": 4925,
"s": 4685,
"text": "So, the linear regression with np.polyfit() gave as a result a linear regression line (y(x) = a + bx) with intercept, a=5.741 (precise value), and slope, b =2.39e-05 (precise value). The print(p) command gives an approximate value display."
},
{
"code": null,
"e": 5572,
"s": 4925,
"text": "The polyfit module is very useful for fitting simple linear regression and polynomial regression of degree n. However, it does not give the user the possibility to use linear regression with multiple predictor variables, namely multivariate regression. So, it is not possible to use np.polyfit() for mixed interaction terms but only for self-interaction terms. In addition, it does not give the user the possibility to directly calculate: the coefficient of determination R2 to assess the goodness of the fit, the Pearson correlation coefficient r, the p-value of hypothesis testing, and sample errors associated with the regression coefficients."
},
{
"code": null,
"e": 6135,
"s": 5572,
"text": "SciPy is a Python library that stands for Scientific Python. It is the most important library for scientific computing that is used in academia and the scientific industry. This library contains several modules that are used for specific purposes. Among these modules, the scipy.stats() module, is the most important one regarding statistical modelling in general. The scipy.stats() module has a submodule completely dedicated to linear regression which goes under the syntax: scipy.stats.linregress() and uses the least square method as a minimisation criteria."
},
{
"code": null,
"e": 6243,
"s": 6135,
"text": "Now to see linregress in action, I use again the arrays x and y as above and use the following Python code:"
},
{
"code": null,
"e": 6546,
"s": 6243,
"text": "[In]: import scipy as sp[In]: regr_results = sp.stats.linregress(x, y)[In]: print(regr_results)[Out]: LinregressResult(slope=2.3996299825729513e-05, intercept=5.741754353755326, rvalue=0.720287195322656, pvalue=3.4265564700646986e-07, stderr=3.851624914535862e-06, intercept_stderr=0.15853194959552008)"
},
{
"code": null,
"e": 7203,
"s": 6546,
"text": "As you can see from the above Python code, the linregress module gives as an output the results of the linear regression, where the intercept value is, a = 5.741 and, the slope value is b = 2.39e-05. These values of a and b are the same as those found by using the polyfit module of NumPy as in the previous section. In addition, linregress evaluates the Pearson correlation coefficient r (with value of rvalue = 0.72), the p-value (pvalue = 3.42e-06), the standard deviation of the slope b (stderr = 3.85e-06), and the standard error of the intercept term a (intercept_stderr = 0.15). Explicit calculations and Python codes can be found in my GitHub page."
},
{
"code": null,
"e": 7628,
"s": 7203,
"text": "The linregress module gives additional results of the linear regression to the polyfit module as shown above. The only disadvantage of linregress is that does not support multivariate regression. It only supports simple linear regression. In addition, it does not give to the user the option to directly predict new values for features not used in the least square method like the scikit-learn library as in section 5 below."
},
{
"code": null,
"e": 7995,
"s": 7628,
"text": "The statsmodels library/module is an extension of the scipy.stats module that is mainly used for fitting a model to a given dataset. This module is probably the most complete one regarding regression in general and also linear regression in particular. This module is quite flexible and it gives the user several options to perform specific statistical calculations."
},
{
"code": null,
"e": 8235,
"s": 7995,
"text": "As I did in sections 2 and 3, I use the statsmodel to perform a simple linear regression by using the x, and y arrays as above and using the least square method as minimisation criteria with the OLS module. I use the following Python code:"
},
{
"code": null,
"e": 8500,
"s": 8235,
"text": "[In]: import statsmodels.api as sm[In]: x = sm.add_constant(x) # Adds an intercept term to the simple linear regression formula[In]: lin_model = sm.OLS(y, x)[In]: regr_results = lin_model.fit()[In]: print(regr_results.results)[Out]: [5.74175435e+00 2.39962998e-05]"
},
{
"code": null,
"e": 8903,
"s": 8500,
"text": "After printing the results with the above code, I get the following values for intercept a = 5.741 and slope b = 2.39e-05 of the simple linear regression on x and y arrays. The OLS module implicitly uses the least square minimisation method for calculating the regression coefficients. One can note that the values of a and b coincide with those previously found in sections 1 and 2 with other methods."
},
{
"code": null,
"e": 9397,
"s": 8903,
"text": "A more detailed description of the regression results can be obtained with the python command print(regr_results.summary()) where the results table is shown in Fig. 2. As you can see, the summary table gives a detailed information of the linear regression results that include: the coefficient of determination R2, the value of the intercept a and its standard deviation, the value of the slope b and its standard deviation, the value of the t score, the p-value, the confidence interval, etc."
},
{
"code": null,
"e": 10125,
"s": 9397,
"text": "The OLS module and its equivalent module, ols (I do not explicitly discuss about ols module in this article) have an advantage to the linregress module since they can perform multivariate linear regression. On the other hand, the disadvantage of the module ols, is that it does not have the option to directly predict new values y for new values of predictors x_i (at least not known to me). Also, another disadvantage of the OLS module is that one has to add explicitly a constant term for the linear regression with the command sm.add_constant(). The linear_model.OLS module, on the other hand, gives the user the possibility to predict new values given a design matrix similar to the LinearRegression module of scikit-learn."
},
{
"code": null,
"e": 10530,
"s": 10125,
"text": "scikit-learn is one of the best Python libraries for statistical/machine learning and it is adapted for fitting and making predictions. It gives the user different options for numerical calculations and statistical modelling. Its most important sub-module for linear regression is LinearRegression. It uses the least square method as minimisation criteria to find the parameters of the linear regression."
},
{
"code": null,
"e": 10662,
"s": 10530,
"text": "As I did in the previous sections, I use the arrays x and y as above for simple linear regression. I use the following Python code:"
},
{
"code": null,
"e": 10832,
"s": 10662,
"text": "[In]: from sklearn import linear_model[In]: linmodel = linear_model.LinearRegression(fit_intercept=True) [In]: linmodel.fit(x.reshape(-1, 1), y)[Out]: LinearRegression()"
},
{
"code": null,
"e": 11168,
"s": 10832,
"text": "The above Python code uses linear regression to fit the data contained in the x and y arrays. If now one needs to get some of the parameters from the fit, it is necessary to write an additional code. For example, I want to see the values of intercept a and slope b of the fitting procedure. To do this, I run the following Python code:"
},
{
"code": null,
"e": 11312,
"s": 11168,
"text": "[In]: (slope, intercept) = (linmodel.coef_[0], linmodel.intercept_)[In]: print(slope, intercept)[Out]: 2.3996299825729496e-05 5.741754353755327"
},
{
"code": null,
"e": 11703,
"s": 11312,
"text": "As you can see, the LinearRegression module gives the same values of intercept a and slope b as previously found by using other methods. In addition, it is also possible to calculate the coefficient of determination R2 with the Python command: print(linmodel.score(x.reshape(-1, 1), y)) which gives a value of R2 = 0.518 that is the same as that given by using OLS module results of Fig. 2."
},
{
"code": null,
"e": 12535,
"s": 11703,
"text": "The advantage of the LinearRegression module is that it gives the user the possibility to directly predict new values for new data with the linmodel.predict() command. This function makes the LinearRegression module very appealing for statistical/machine learning. As the OLS module, the LinearRegression module can also perform multivariate linear regression if needed. The disadvantage of LinearRegression module is that it does not have a summary table of the regression results as the OLS module and it forces the user to explicitly write new commands to get important statistical information. Also, it can be quite cumbersome to use the LinearRegression module for polynomial regression since one needs to calculate the design matrix X before getting the regression results. One can see this explicitly in my previous article."
},
{
"code": null,
"e": 12999,
"s": 12535,
"text": "The seaborn Python library is a very important library for visualisation of statistical results. Technically, it is not a library that can be used to calculate the regression parameters as I showed in the previous sections, but it can be used to graphically visualise the regression lines and confidence regions in a plot. For example, if I want to plot the simple linear regression line obtained in the previous sections, I need to run the following Python code:"
},
{
"code": null,
"e": 13529,
"s": 12999,
"text": "[In]: import seaborn as sns[In]: import matplotlib.pyplot as plt[In]: fig, ax = plt.subplots(figsize=(10, 6))sns.regplot(x = x, y = y, ci=95, order=1,line_kws={'label': 'Linear regression line: $Y(X)=5.74+2.39\\cdot 10^{-5} X$', 'color': 'm'}, seed=1,truncate=False, label=\"Original data\")ax.set_xlabel(\"GDP per capita 2015 (USD)\")ax.set_ylabel(\"Life Satisfaction Value\")ax.set_xticks([1000, 10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000, 90000, 100000])ax.set_yticks(np.arange(3.0, 10.5, 0.5))ax.legend(loc=\"upper left\")"
},
{
"code": null,
"e": 14220,
"s": 13529,
"text": "The result of the above code gives exactly Fig. 1 as shown at the top of this article. The regplot module of seaborn internally calculates the values of the linear regression parameters and it plots the linear regression line with the 95% confidence zone (I set the parameter “ci=95” in the above code) of the linear regression parameters. Also, the regplot module can perform graphical visulalization of multivariate linear regression and logistic regression since this module is strongly based on the statsmodel library. The only disadvantage of seaborn in general is that it does not give to the user the possibility to directly see the regression results with a specific Python command."
},
{
"code": null,
"e": 15373,
"s": 14220,
"text": "In this article, I summarised the most import python libraries and their modules for regression and I gave specific examples for linear regression. The advantage of a module over another one depends on a specific problem that the user faces. For simple linear regression and polynomial regression, the polyfit and linregress modules are the easiest to use and very handy. On the other hand for detailed statistical results of linear regression, the OLS and ols modules are probably the best since they are not difficult to use and give plenty of regression results in a summary table. Also, the OLS sub-module of the linear_model, gives the user the possibility to make prediction as well with the help of the linear_model.OLS module. For statistical/machine learning, the LinearRegression module of the scikit-learn Python library is one of the best since it can be used to make predictions, a functionality that the majority of other mentioned modules above do not have. If ones desires to plot the results of a statistical procedure directly without information of the fitting parameter values, then the regplot module of seaborn is one of the best."
}
] |
Find all Ramanujan Numbers that can be formed by numbers upto L - GeeksforGeeks
|
11 Jun, 2021
Given a positive integer L, the task is to find all the Ramanujan Numbers that can be generated by any set of quadruples (a, b, c, d), where 0 < a, b, c, d ≤ L.
Ramanujan Numbers are the numbers that can be expressed as sum of two cubes in two different ways. Therefore, Ramanujan Number (N) = a3 + b3 = c3 + d3.
Examples:
Input: L = 20Output: 1729, 4104Explanation:The number 1729 can be expressed as 123 + 13 and 103 + 93.The number 4104 can be expressed as 163 + 23 and 153 + 93.
Input: L = 30Output: 1729, 4104, 13832, 20683
Naive Approach: The simplest approach is to check for all combination of quadruples (a, b, c, d) from the range [1, L] consisting of distinct elements that satisfy the equation a3 + b3 = c3 + d3. For elements found to be satisfying the conditions, store the Ramanujan Numbers as 3 + b3. Finally, after checking for all possible combinations, print all the stored numbers.
Below is the implementation of the above approach:
C++
Java
Python3
Javascript
// CPP program for the above approach#include<bits/stdc++.h>using namespace std; // Function to find Ramanujan numbers// made up of cubes of numbers up to Lmap<int,vector<int>> ramanujan_On4(int limit){ map<int,vector<int>> dictionary; // Generate all quadruples a, b, c, d // of integers from the range [1, L] for(int a = 0; a < limit; a++) { for(int b = 0; b < limit; b++) { for(int c = 0; c < limit; c++) { for(int d = 0; d < limit; d++) { // Condition // 2: // a, b, c, d are not equal if ((a != b) and (a != c) and (a != d) and (b != c) and (b != d) and (c != d)){ int x = pow(a, 3) + pow(b, 3); int y = pow(c, 3) + pow(d, 3); if ((x) == (y)) { int number = pow(a, 3) + pow(b, 3); dictionary[number] = {a, b, c, d}; } } } } }} // Return all the possible number return dictionary;} // Driver Codeint main(){ // Given range Lint L = 30;map<int, vector<int>> ra1_dict = ramanujan_On4(L); // Print all the generated numbersfor(auto x:ra1_dict){ cout << x.first << ": ("; // sort(x.second.begin(),x.second.end()); for(int i = x.second.size() - 1; i >= 0; i--) { if(i == 0) cout << x.second[i] << ")"; else cout << x.second[i] << ", "; } cout << endl;}} // This code is contributed by SURENDRA_GANGWAR.
// Java program for the above approachimport java.util.*;import java.lang.*; class GFG{ static Map<Integer, List<Integer>> ra1_dict; // Function to find Ramanujan numbers// made up of cubes of numbers up to Lstatic void ramanujan_On4(int limit){ // Generate all quadruples a, b, c, d // of integers from the range [1, L] for(int a = 0; a < limit; a++) { for(int b = 0; b < limit; b++) { for(int c = 0; c < limit; c++) { for(int d = 0; d < limit; d++) { // Condition // 2: // a, b, c, d are not equal if ((a != b) && (a != c) && (a != d) && (b != c) && (b != d) && (c != d)) { int x = (int)Math.pow(a, 3) + (int) Math.pow(b, 3); int y = (int)Math.pow(c, 3) + (int) Math.pow(d, 3); if ((x) == (y)) { int number = (int)Math.pow(a, 3) + (int) Math.pow(b, 3); ra1_dict.put(number, new ArrayList<>( Arrays.asList(a, b, c, d))); } } } } } }} // Driver codepublic static void main(String[] args){ // Given range L int L = 30; ra1_dict = new HashMap<>(); ramanujan_On4(L); // Print all the generated numbers for(Map.Entry<Integer, List<Integer>> x: ra1_dict.entrySet()) { System.out.print(x.getKey() + ": ("); // sort(x.second.begin(),x.second.end()); for(int i = x.getValue().size() - 1; i >= 0; i--) { if (i == 0) System.out.print(x.getValue().get(i) + ")"); else System.out.print(x.getValue().get(i) + ", "); } System.out.println(); }}} // This code is contributed by offbeat
# Python program for the above approachimport time # Function to find Ramanujan numbers# made up of cubes of numbers up to Ldef ramanujan_On4(limit): dictionary = dict() # Generate all quadruples a, b, c, d # of integers from the range [1, L] for a in range(0, limit): for b in range(0, limit): for c in range(0, limit): for d in range(0, limit): # Condition # 2: # a, b, c, d are not equal if ((a != b) and (a != c) and (a != d) and (b != c) and (b != d) and (c != d)): x = a ** 3 + b ** 3 y = c ** 3 + d ** 3 if (x) == (y): number = a ** 3 + b ** 3 dictionary[number] = a, b, c, d # Return all the possible number return dictionary # Driver Code # Given range LL = 30ra1_dict = ramanujan_On4(L) # Print all the generated numbersfor i in sorted(ra1_dict): print(f'{i}: {ra1_dict[i]}', end ='\n')
<script> // JavaScript program for the above approach // Function to find Ramanujan numbers // made up of cubes of numbers up to L function ramanujan_On4(limit) { var dictionary = {}; // Generate all quadruples a, b, c, d // of integers from the range [1, L] for (var a = 0; a < limit; a++) { for (var b = 0; b < limit; b++) { for (var c = 0; c < limit; c++) { for (var d = 0; d < limit; d++) { // Condition // 2: // a, b, c, d are not equal if ( a !== b && a !== c && a !== d && b !== c && b !== d && c !== d ) { var x = Math.pow(a, 3) + Math.pow(b, 3); var y = Math.pow(c, 3) + Math.pow(d, 3); if (x == y) { var number = Math.pow(a, 3) + Math.pow(b, 3); dictionary[number] = [" " + a, " " + b, " " + c, d]; } } } } } } return dictionary; } // Driver code // Given range L var L = 30; var ra1_dict = ramanujan_On4(L); var temp = Object.keys(ra1_dict) .sort() .reduce((r, k) => ((r[k] = ra1_dict[k]), r), {}); // Print all the generated numbers for (const [key, value] of Object.entries(temp)) { document.write(key + ": (" + value.reverse() + ")" + "<br>"); } </script>
1729: (9, 10, 1, 12)
4104: (9, 15, 2, 16)
13832: (18, 20, 2, 24)
20683: (19, 24, 10, 27)
Time Complexity: O(L4)Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized by using Hashing. Follow the steps below to solve the problem:
Initialize an array, say ans[], to stores all the possible Ramanujan Numbers that satisfy the given conditions.
Precompute and store the cubes of all numbers from the range [1, L] in an auxiliary array arr[].
Initialize a HashMap, say M, that stores the sum of all possible combinations of a pair of cubes generated from the array arr[].
Now, generate all possible pairs(i, j) of the array arr[] and if the sum of pairs doesn’t exist in the array, then mark the occurrence of the current sum of pairs in the Map. Otherwise, add the current sum to the array ans[] as it is one of the Ramanujan Numbers.
After completing the above steps, print the numbers stored in the array ans[].
Below is the implementation of the above approach:
Python3
# Python program for the above approachfrom array import *import time # Function to find Ramanujan numbers# made up of cubes of numbers up to Ldef ramanujan_On2(limit): cubes = array('i', []) # Stores the sum of pairs of cubes dict_sum_pairs = dict() # Stores the Ramanujan Numbers dict_ramnujan_nums = dict() sum_pairs = 0 # Stores the cubes from 1 to L for i in range(0, limit): cubes.append(i ** 3) # Generate all pairs (a, b) # from the range [0, L] for a in range(0, limit): for b in range(a + 1, limit): a3, b3 = cubes[a], cubes[b] # Find the sum of pairs sum_pairs = a3 + b3 # Append to dictionary if sum_pairs in dict_sum_pairs: # If the current sum is in # the dictionary, then store # the current number c, d = dict_sum_pairs.get(sum_pairs) dict_ramnujan_nums[sum_pairs] = a, b, c, d # Otherwise append the current # sum pairs to the sum pairs # dictionary else: dict_sum_pairs[sum_pairs] = a, b # Return the possible Ramanujan # Numbers return dict_ramnujan_nums # Driver Code # Given range LL = 30r_dict = ramanujan_On2(L) # Print all the numbersfor d in sorted(r_dict): print(f'{d}: {r_dict[d]}', end ='\n')
1729: (9, 10, 1, 12)
4104: (9, 15, 2, 16)
13832: (18, 20, 2, 24)
20683: (19, 24, 10, 27)
Time Complexity: O(L2)Auxiliary Space: O(L2)
SURENDRA_GANGWAR
offbeat
rdtank
maths-perfect-cube
Numbers
Mathematical
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Program to print prime numbers from 1 to N.
Program to multiply two matrices
Fizz Buzz Implementation
Complexity Analysis of Binary Search
Check if a number is Palindrome
Modular multiplicative inverse
Find Union and Intersection of two unsorted arrays
Count ways to reach the n'th stair
Find first and last digits of a number
|
[
{
"code": null,
"e": 24718,
"s": 24690,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 24879,
"s": 24718,
"text": "Given a positive integer L, the task is to find all the Ramanujan Numbers that can be generated by any set of quadruples (a, b, c, d), where 0 < a, b, c, d ≤ L."
},
{
"code": null,
"e": 25033,
"s": 24879,
"text": "Ramanujan Numbers are the numbers that can be expressed as sum of two cubes in two different ways. Therefore, Ramanujan Number (N) = a3 + b3 = c3 + d3. "
},
{
"code": null,
"e": 25043,
"s": 25033,
"text": "Examples:"
},
{
"code": null,
"e": 25203,
"s": 25043,
"text": "Input: L = 20Output: 1729, 4104Explanation:The number 1729 can be expressed as 123 + 13 and 103 + 93.The number 4104 can be expressed as 163 + 23 and 153 + 93."
},
{
"code": null,
"e": 25249,
"s": 25203,
"text": "Input: L = 30Output: 1729, 4104, 13832, 20683"
},
{
"code": null,
"e": 25621,
"s": 25249,
"text": "Naive Approach: The simplest approach is to check for all combination of quadruples (a, b, c, d) from the range [1, L] consisting of distinct elements that satisfy the equation a3 + b3 = c3 + d3. For elements found to be satisfying the conditions, store the Ramanujan Numbers as 3 + b3. Finally, after checking for all possible combinations, print all the stored numbers."
},
{
"code": null,
"e": 25672,
"s": 25621,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25676,
"s": 25672,
"text": "C++"
},
{
"code": null,
"e": 25681,
"s": 25676,
"text": "Java"
},
{
"code": null,
"e": 25689,
"s": 25681,
"text": "Python3"
},
{
"code": null,
"e": 25700,
"s": 25689,
"text": "Javascript"
},
{
"code": "// CPP program for the above approach#include<bits/stdc++.h>using namespace std; // Function to find Ramanujan numbers// made up of cubes of numbers up to Lmap<int,vector<int>> ramanujan_On4(int limit){ map<int,vector<int>> dictionary; // Generate all quadruples a, b, c, d // of integers from the range [1, L] for(int a = 0; a < limit; a++) { for(int b = 0; b < limit; b++) { for(int c = 0; c < limit; c++) { for(int d = 0; d < limit; d++) { // Condition // 2: // a, b, c, d are not equal if ((a != b) and (a != c) and (a != d) and (b != c) and (b != d) and (c != d)){ int x = pow(a, 3) + pow(b, 3); int y = pow(c, 3) + pow(d, 3); if ((x) == (y)) { int number = pow(a, 3) + pow(b, 3); dictionary[number] = {a, b, c, d}; } } } } }} // Return all the possible number return dictionary;} // Driver Codeint main(){ // Given range Lint L = 30;map<int, vector<int>> ra1_dict = ramanujan_On4(L); // Print all the generated numbersfor(auto x:ra1_dict){ cout << x.first << \": (\"; // sort(x.second.begin(),x.second.end()); for(int i = x.second.size() - 1; i >= 0; i--) { if(i == 0) cout << x.second[i] << \")\"; else cout << x.second[i] << \", \"; } cout << endl;}} // This code is contributed by SURENDRA_GANGWAR.",
"e": 27364,
"s": 25700,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;import java.lang.*; class GFG{ static Map<Integer, List<Integer>> ra1_dict; // Function to find Ramanujan numbers// made up of cubes of numbers up to Lstatic void ramanujan_On4(int limit){ // Generate all quadruples a, b, c, d // of integers from the range [1, L] for(int a = 0; a < limit; a++) { for(int b = 0; b < limit; b++) { for(int c = 0; c < limit; c++) { for(int d = 0; d < limit; d++) { // Condition // 2: // a, b, c, d are not equal if ((a != b) && (a != c) && (a != d) && (b != c) && (b != d) && (c != d)) { int x = (int)Math.pow(a, 3) + (int) Math.pow(b, 3); int y = (int)Math.pow(c, 3) + (int) Math.pow(d, 3); if ((x) == (y)) { int number = (int)Math.pow(a, 3) + (int) Math.pow(b, 3); ra1_dict.put(number, new ArrayList<>( Arrays.asList(a, b, c, d))); } } } } } }} // Driver codepublic static void main(String[] args){ // Given range L int L = 30; ra1_dict = new HashMap<>(); ramanujan_On4(L); // Print all the generated numbers for(Map.Entry<Integer, List<Integer>> x: ra1_dict.entrySet()) { System.out.print(x.getKey() + \": (\"); // sort(x.second.begin(),x.second.end()); for(int i = x.getValue().size() - 1; i >= 0; i--) { if (i == 0) System.out.print(x.getValue().get(i) + \")\"); else System.out.print(x.getValue().get(i) + \", \"); } System.out.println(); }}} // This code is contributed by offbeat",
"e": 29439,
"s": 27364,
"text": null
},
{
"code": "# Python program for the above approachimport time # Function to find Ramanujan numbers# made up of cubes of numbers up to Ldef ramanujan_On4(limit): dictionary = dict() # Generate all quadruples a, b, c, d # of integers from the range [1, L] for a in range(0, limit): for b in range(0, limit): for c in range(0, limit): for d in range(0, limit): # Condition # 2: # a, b, c, d are not equal if ((a != b) and (a != c) and (a != d) and (b != c) and (b != d) and (c != d)): x = a ** 3 + b ** 3 y = c ** 3 + d ** 3 if (x) == (y): number = a ** 3 + b ** 3 dictionary[number] = a, b, c, d # Return all the possible number return dictionary # Driver Code # Given range LL = 30ra1_dict = ramanujan_On4(L) # Print all the generated numbersfor i in sorted(ra1_dict): print(f'{i}: {ra1_dict[i]}', end ='\\n')",
"e": 30525,
"s": 29439,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to find Ramanujan numbers // made up of cubes of numbers up to L function ramanujan_On4(limit) { var dictionary = {}; // Generate all quadruples a, b, c, d // of integers from the range [1, L] for (var a = 0; a < limit; a++) { for (var b = 0; b < limit; b++) { for (var c = 0; c < limit; c++) { for (var d = 0; d < limit; d++) { // Condition // 2: // a, b, c, d are not equal if ( a !== b && a !== c && a !== d && b !== c && b !== d && c !== d ) { var x = Math.pow(a, 3) + Math.pow(b, 3); var y = Math.pow(c, 3) + Math.pow(d, 3); if (x == y) { var number = Math.pow(a, 3) + Math.pow(b, 3); dictionary[number] = [\" \" + a, \" \" + b, \" \" + c, d]; } } } } } } return dictionary; } // Driver code // Given range L var L = 30; var ra1_dict = ramanujan_On4(L); var temp = Object.keys(ra1_dict) .sort() .reduce((r, k) => ((r[k] = ra1_dict[k]), r), {}); // Print all the generated numbers for (const [key, value] of Object.entries(temp)) { document.write(key + \": (\" + value.reverse() + \")\" + \"<br>\"); } </script>",
"e": 32152,
"s": 30525,
"text": null
},
{
"code": null,
"e": 32241,
"s": 32152,
"text": "1729: (9, 10, 1, 12)\n4104: (9, 15, 2, 16)\n13832: (18, 20, 2, 24)\n20683: (19, 24, 10, 27)"
},
{
"code": null,
"e": 32287,
"s": 32243,
"text": "Time Complexity: O(L4)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 32411,
"s": 32287,
"text": "Efficient Approach: The above approach can also be optimized by using Hashing. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 32523,
"s": 32411,
"text": "Initialize an array, say ans[], to stores all the possible Ramanujan Numbers that satisfy the given conditions."
},
{
"code": null,
"e": 32620,
"s": 32523,
"text": "Precompute and store the cubes of all numbers from the range [1, L] in an auxiliary array arr[]."
},
{
"code": null,
"e": 32749,
"s": 32620,
"text": "Initialize a HashMap, say M, that stores the sum of all possible combinations of a pair of cubes generated from the array arr[]."
},
{
"code": null,
"e": 33013,
"s": 32749,
"text": "Now, generate all possible pairs(i, j) of the array arr[] and if the sum of pairs doesn’t exist in the array, then mark the occurrence of the current sum of pairs in the Map. Otherwise, add the current sum to the array ans[] as it is one of the Ramanujan Numbers."
},
{
"code": null,
"e": 33092,
"s": 33013,
"text": "After completing the above steps, print the numbers stored in the array ans[]."
},
{
"code": null,
"e": 33143,
"s": 33092,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 33151,
"s": 33143,
"text": "Python3"
},
{
"code": "# Python program for the above approachfrom array import *import time # Function to find Ramanujan numbers# made up of cubes of numbers up to Ldef ramanujan_On2(limit): cubes = array('i', []) # Stores the sum of pairs of cubes dict_sum_pairs = dict() # Stores the Ramanujan Numbers dict_ramnujan_nums = dict() sum_pairs = 0 # Stores the cubes from 1 to L for i in range(0, limit): cubes.append(i ** 3) # Generate all pairs (a, b) # from the range [0, L] for a in range(0, limit): for b in range(a + 1, limit): a3, b3 = cubes[a], cubes[b] # Find the sum of pairs sum_pairs = a3 + b3 # Append to dictionary if sum_pairs in dict_sum_pairs: # If the current sum is in # the dictionary, then store # the current number c, d = dict_sum_pairs.get(sum_pairs) dict_ramnujan_nums[sum_pairs] = a, b, c, d # Otherwise append the current # sum pairs to the sum pairs # dictionary else: dict_sum_pairs[sum_pairs] = a, b # Return the possible Ramanujan # Numbers return dict_ramnujan_nums # Driver Code # Given range LL = 30r_dict = ramanujan_On2(L) # Print all the numbersfor d in sorted(r_dict): print(f'{d}: {r_dict[d]}', end ='\\n')",
"e": 34539,
"s": 33151,
"text": null
},
{
"code": null,
"e": 34628,
"s": 34539,
"text": "1729: (9, 10, 1, 12)\n4104: (9, 15, 2, 16)\n13832: (18, 20, 2, 24)\n20683: (19, 24, 10, 27)"
},
{
"code": null,
"e": 34675,
"s": 34630,
"text": "Time Complexity: O(L2)Auxiliary Space: O(L2)"
},
{
"code": null,
"e": 34692,
"s": 34675,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 34700,
"s": 34692,
"text": "offbeat"
},
{
"code": null,
"e": 34707,
"s": 34700,
"text": "rdtank"
},
{
"code": null,
"e": 34726,
"s": 34707,
"text": "maths-perfect-cube"
},
{
"code": null,
"e": 34734,
"s": 34726,
"text": "Numbers"
},
{
"code": null,
"e": 34747,
"s": 34734,
"text": "Mathematical"
},
{
"code": null,
"e": 34760,
"s": 34747,
"text": "Mathematical"
},
{
"code": null,
"e": 34768,
"s": 34760,
"text": "Numbers"
},
{
"code": null,
"e": 34866,
"s": 34768,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34898,
"s": 34866,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 34942,
"s": 34898,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 34975,
"s": 34942,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 35000,
"s": 34975,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 35037,
"s": 35000,
"text": "Complexity Analysis of Binary Search"
},
{
"code": null,
"e": 35069,
"s": 35037,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 35100,
"s": 35069,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 35151,
"s": 35100,
"text": "Find Union and Intersection of two unsorted arrays"
},
{
"code": null,
"e": 35186,
"s": 35151,
"text": "Count ways to reach the n'th stair"
}
] |
Matplotlib – Plot over an image background in Python
|
To plot over an image background, we can take the following steps−
Read an image from a file into an array.
Create a figure (fig) and add a set of subplots (ax) with extent [0, 300, 0, 300].
Create an array x of range (300).
Plot x using plot() method with linestyle=dotted, linewidth=2, and color=red.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
im = plt.imread("bird.jpg")
fig, ax = plt.subplots()
im = ax.imshow(im, extent=[0, 300, 0, 300])
x = np.array(range(300))
ax.plot(x, x, ls='dotted', linewidth=2, color='red')
plt.show()
|
[
{
"code": null,
"e": 1129,
"s": 1062,
"text": "To plot over an image background, we can take the following steps−"
},
{
"code": null,
"e": 1170,
"s": 1129,
"text": "Read an image from a file into an array."
},
{
"code": null,
"e": 1253,
"s": 1170,
"text": "Create a figure (fig) and add a set of subplots (ax) with extent [0, 300, 0, 300]."
},
{
"code": null,
"e": 1287,
"s": 1253,
"text": "Create an array x of range (300)."
},
{
"code": null,
"e": 1365,
"s": 1287,
"text": "Plot x using plot() method with linestyle=dotted, linewidth=2, and color=red."
},
{
"code": null,
"e": 1407,
"s": 1365,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1736,
"s": 1407,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nim = plt.imread(\"bird.jpg\")\nfig, ax = plt.subplots()\nim = ax.imshow(im, extent=[0, 300, 0, 300])\nx = np.array(range(300))\nax.plot(x, x, ls='dotted', linewidth=2, color='red')\nplt.show()"
}
] |
stack top() in C++ STL
|
In this article, we will be discussing the working, syntax, and examples of
stack::top() function in C++ STL.
Stacks are the data structure that stores the data in LIFO (Last In First Out) where we do insertion and deletion from the top of the last element inserted. Like a stack of plates, if we want to push a new plate into the stack we insert on the top and if we want to remove the plate from the stack, we then also remove it
from the top.
stack::top() function is an inbuilt function in C++ STL, which is defined in <stack>
header file. top() is used to access the element at the top of the stack container. In a stack, the top element is the element that is inserted at the last or most recently inserted element.
stack_name.top();
The function accepts no parameter(s) −
This function returns a reference of the element at the top of the stack container.
Input
std::stack<int> odd;
odd.emplace(1);
odd.emplace(3);
odd.emplace(5);
odd.top();
Output
5
Live Demo
#include <iostream>
#include <stack&lgt;
using namespace std;
int main(){
stack<int> stck_1, stck_2;
//inserting elements to stack 1
stck_1.push(1);
stck_1.push(2);
stck_1.push(3);
stck_1.push(4);
//swapping elements of stack 1 in stack 2 and vice-versa
cout<<"The top element in stack using TOP(): "<<stck_1.top();
cout<<"\nElements in stack are: ";
while (!stck_1.empty()){
cout<<stck_1.top()<<" ";
stck_1.pop();
}
return 0;
}
If we run the above code it will generate the following output −
The top element in stack using TOP(): 4
Elements in stack are: 4 3 2 1
|
[
{
"code": null,
"e": 1172,
"s": 1062,
"text": "In this article, we will be discussing the working, syntax, and examples of\nstack::top() function in C++ STL."
},
{
"code": null,
"e": 1508,
"s": 1172,
"text": "Stacks are the data structure that stores the data in LIFO (Last In First Out) where we do insertion and deletion from the top of the last element inserted. Like a stack of plates, if we want to push a new plate into the stack we insert on the top and if we want to remove the plate from the stack, we then also remove it\nfrom the top."
},
{
"code": null,
"e": 1784,
"s": 1508,
"text": "stack::top() function is an inbuilt function in C++ STL, which is defined in <stack>\nheader file. top() is used to access the element at the top of the stack container. In a stack, the top element is the element that is inserted at the last or most recently inserted element."
},
{
"code": null,
"e": 1802,
"s": 1784,
"text": "stack_name.top();"
},
{
"code": null,
"e": 1841,
"s": 1802,
"text": "The function accepts no parameter(s) −"
},
{
"code": null,
"e": 1925,
"s": 1841,
"text": "This function returns a reference of the element at the top of the stack container."
},
{
"code": null,
"e": 1932,
"s": 1925,
"text": "Input "
},
{
"code": null,
"e": 2012,
"s": 1932,
"text": "std::stack<int> odd;\nodd.emplace(1);\nodd.emplace(3);\nodd.emplace(5);\nodd.top();"
},
{
"code": null,
"e": 2019,
"s": 2012,
"text": "Output"
},
{
"code": null,
"e": 2021,
"s": 2019,
"text": "5"
},
{
"code": null,
"e": 2032,
"s": 2021,
"text": " Live Demo"
},
{
"code": null,
"e": 2509,
"s": 2032,
"text": "#include <iostream>\n#include <stack&lgt;\nusing namespace std;\nint main(){\n stack<int> stck_1, stck_2;\n //inserting elements to stack 1\n stck_1.push(1);\n stck_1.push(2);\n stck_1.push(3);\n stck_1.push(4);\n //swapping elements of stack 1 in stack 2 and vice-versa\n cout<<\"The top element in stack using TOP(): \"<<stck_1.top();\n cout<<\"\\nElements in stack are: \";\n while (!stck_1.empty()){\n cout<<stck_1.top()<<\" \";\n stck_1.pop();\n }\n return 0;\n}"
},
{
"code": null,
"e": 2574,
"s": 2509,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 2645,
"s": 2574,
"text": "The top element in stack using TOP(): 4\nElements in stack are: 4 3 2 1"
}
] |
Decision Statements
|
Decision making is critical to computer programming. There will be many situations when you will be given two or more options and you will have to select an option based on the given conditions. For example, we want to print a remark about a student based on his secured marks. Following is the situation −
Assume given marks are x for a student:
If given marks are more than 95, then
Student is brilliant
If given marks are less than 30, then
Student is poor
If given marks are less than 95 and more than 30, then
Student is average
Now, the question is how to write a programming code to handle such situations. Almost all the programming languages provide conditional statements that work based on the following flow diagram −
Let's write a C program with the help of if conditional statements to convert the above given situation into a programming code −
#include <stdio.h>
int main() {
int x = 45;
if( x > 95) {
printf( "Student is brilliant\n");
}
if( x < 30) {
printf( "Student is poor\n");
}
if( x < 95 && x > 30 ) {
printf( "Student is average\n");
}
}
When the above program is executed, it produces the following result −
Student is average
The above program uses if conditional statements. Here, the first if statement checks whether the given condition i.e., variable x is greater than 95 or not and if it finds the condition is true, then the conditional body is entered to execute the given statements. Here we have only one printf() statement to print a remark about the student.
Similarly, the second if statement works. Finally, the third if statement is executed, here we have the following two conditions −
First condition is x > 95
First condition is x > 95
Second condition is x < 30
Second condition is x < 30
The computer evaluates both the given conditions and then, the overall result is combined with the help of the binary operator &&. If the final result is true, then the conditional statement will be executed, otherwise no statement will be executed.
This tutorial will give you a basic idea on various forms of if statements and an introduction to switch statements available in C programming language. Different programming languages provide different types of decision-making statements, but the basic concept remains the same as explained in this tutorial.
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. The syntax of an if...else statement in C programming language is −
if(boolean_expression) {
/* Statement(s) will execute if the boolean expression is true */
} else {
/* Statement(s) will execute if the boolean expression is false */
}
The above syntax can be represented in the form of a flow diagram as shown below −
An if...else statement is useful when we have to take a decision out of two options. For example, if a student secures more marks than 95, then the student is brilliant, otherwise no such situation can be coded, as follows −
#include <stdio.h>
int main() {
int x = 45;
if( x > 95) {
printf( "Student is brilliant\n");
} else {
printf( "Student is not brilliant\n");
}
}
When the above program is executed, it produces the following result −
Student is not brilliant
An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions.
While using if, else if, else statements, there are a few points to keep in mind −
An if can have zero or one else's and it must come after an else if.
An if can have zero or one else's and it must come after an else if.
An if can have zero to many else...if's and they must come before the else.
An if can have zero to many else...if's and they must come before the else.
Once an else...if succeeds, none of the remaining else...if's or else's will be tested.
Once an else...if succeeds, none of the remaining else...if's or else's will be tested.
The syntax of an if...else if...else statement in C programming language is −
if(boolean_expression 1) {
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2) {
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3) {
/* Executes when the boolean expression 3 is true */
} else {
/* Executes when the none of the above condition is true */
}
Now with the help of if...elseif...else statement, the very first program can be coded as follows −
#include <stdio.h>
int main() {
int x = 45;
if( x > 95) {
printf( "Student is brilliant\n");
}
else if( x < 30) {
printf( "Student is poor\n");
}
else if( x < 95 && x > 30 ) {
printf( "Student is average\n");
}
}
When the above program is executed, it produces the following result −
Student is average
A switch statement is an alternative of if statements which allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. It has the following syntax −
switch(expression){
case ONE :
statement(s);
break;
case TWO:
statement(s);
break;
......
default :
statement(s);
}
The expression used in a switch statement must give an integer value, which will be compared for equality with different cases given. Wherever an expression value matches with a case value, the body of that case will be executed and finally, the switch will be terminated using a break statement. If no break statements are provided, then the computer continues executing other statements available below to the matched case. If none of the cases matches, then the default case body is executed.
The above syntax can be represented in the form of a flow diagram as shown below −
Now, let's consider another example where we want to write the equivalent English word for a given number. Then, it can be coded as follows −
#include <stdio.h>
int main() {
int x = 2;
switch( x ){
case 1 :
printf( "One\n");
break;
case 2 :
printf( "Two\n");
break;
case 3 :
printf( "Three\n");
break;
case 4 :
printf( "Four\n");
break;
default :
printf( "None of the above...\n");
}
}
When the above program is executed, it produces the following result −
Two
Following is the equivalent program written in Java which too supports if, if...else, if...elseif...else, and switch statements.
You can try to execute the following program to see the output, which must be identical to the result generated by the above C example.
public class DemoJava {
public static void main(String []args) {
int x = 45;
if( x > 95) {
System.out.println( "Student is brilliant");
}
else if( x < 30) {
System.out.println( "Student is poor");
}
else if( x < 95 && x > 30 ) {
System.out.println( "Student is average");
}
}
}
When the above program is executed, it produces the following result −
Student is average
Following is the equivalent program written in Python. Python provides if, if...else, if...elif...else, and switch statements. Here, you must note that Python does not make use of curly braces for conditional body, instead it simply identifies the body of the block using indentation of the statements.
You can try to execute the following program to see the output −
x = 45
if x > 95:
print "Student is brilliant"
elif x < 30:
print "Student is poor"
elif x < 95 and x > 30:
print "Student is average"
print "The end"
When the above program is executed, it produces the following result −
Student is average
The end
107 Lectures
13.5 hours
Arnab Chakraborty
106 Lectures
8 hours
Arnab Chakraborty
99 Lectures
6 hours
Arnab Chakraborty
46 Lectures
2.5 hours
Shweta
70 Lectures
9 hours
Abhilash Nelson
52 Lectures
7 hours
Abhishek And Pukhraj
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2447,
"s": 2140,
"text": "Decision making is critical to computer programming. There will be many situations when you will be given two or more options and you will have to select an option based on the given conditions. For example, we want to print a remark about a student based on his secured marks. Following is the situation −"
},
{
"code": null,
"e": 2678,
"s": 2447,
"text": "Assume given marks are x for a student:\n\nIf given marks are more than 95, then\nStudent is brilliant\n\nIf given marks are less than 30, then\nStudent is poor\n\nIf given marks are less than 95 and more than 30, then\nStudent is average\n"
},
{
"code": null,
"e": 2874,
"s": 2678,
"text": "Now, the question is how to write a programming code to handle such situations. Almost all the programming languages provide conditional statements that work based on the following flow diagram −"
},
{
"code": null,
"e": 3004,
"s": 2874,
"text": "Let's write a C program with the help of if conditional statements to convert the above given situation into a programming code −"
},
{
"code": null,
"e": 3257,
"s": 3004,
"text": "#include <stdio.h>\n\nint main() {\n int x = 45;\n \n if( x > 95) {\n\t\n printf( \"Student is brilliant\\n\");\n }\n if( x < 30) {\n\t\n printf( \"Student is poor\\n\");\n }\n if( x < 95 && x > 30 ) {\n\t\n printf( \"Student is average\\n\");\n }\n}"
},
{
"code": null,
"e": 3328,
"s": 3257,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 3348,
"s": 3328,
"text": "Student is average\n"
},
{
"code": null,
"e": 3692,
"s": 3348,
"text": "The above program uses if conditional statements. Here, the first if statement checks whether the given condition i.e., variable x is greater than 95 or not and if it finds the condition is true, then the conditional body is entered to execute the given statements. Here we have only one printf() statement to print a remark about the student."
},
{
"code": null,
"e": 3823,
"s": 3692,
"text": "Similarly, the second if statement works. Finally, the third if statement is executed, here we have the following two conditions −"
},
{
"code": null,
"e": 3849,
"s": 3823,
"text": "First condition is x > 95"
},
{
"code": null,
"e": 3875,
"s": 3849,
"text": "First condition is x > 95"
},
{
"code": null,
"e": 3902,
"s": 3875,
"text": "Second condition is x < 30"
},
{
"code": null,
"e": 3929,
"s": 3902,
"text": "Second condition is x < 30"
},
{
"code": null,
"e": 4179,
"s": 3929,
"text": "The computer evaluates both the given conditions and then, the overall result is combined with the help of the binary operator &&. If the final result is true, then the conditional statement will be executed, otherwise no statement will be executed."
},
{
"code": null,
"e": 4489,
"s": 4179,
"text": "This tutorial will give you a basic idea on various forms of if statements and an introduction to switch statements available in C programming language. Different programming languages provide different types of decision-making statements, but the basic concept remains the same as explained in this tutorial."
},
{
"code": null,
"e": 4673,
"s": 4489,
"text": "An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. The syntax of an if...else statement in C programming language is −"
},
{
"code": null,
"e": 4855,
"s": 4673,
"text": "if(boolean_expression) {\n \n /* Statement(s) will execute if the boolean expression is true */\n} else {\n \n /* Statement(s) will execute if the boolean expression is false */\n}\n"
},
{
"code": null,
"e": 4938,
"s": 4855,
"text": "The above syntax can be represented in the form of a flow diagram as shown below −"
},
{
"code": null,
"e": 5163,
"s": 4938,
"text": "An if...else statement is useful when we have to take a decision out of two options. For example, if a student secures more marks than 95, then the student is brilliant, otherwise no such situation can be coded, as follows −"
},
{
"code": null,
"e": 5339,
"s": 5163,
"text": "#include <stdio.h>\n\nint main() {\n int x = 45;\n \n if( x > 95) {\n\t\n printf( \"Student is brilliant\\n\");\n } else {\n printf( \"Student is not brilliant\\n\");\n }\n}"
},
{
"code": null,
"e": 5410,
"s": 5339,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 5436,
"s": 5410,
"text": "Student is not brilliant\n"
},
{
"code": null,
"e": 5558,
"s": 5436,
"text": "An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions."
},
{
"code": null,
"e": 5641,
"s": 5558,
"text": "While using if, else if, else statements, there are a few points to keep in mind −"
},
{
"code": null,
"e": 5710,
"s": 5641,
"text": "An if can have zero or one else's and it must come after an else if."
},
{
"code": null,
"e": 5779,
"s": 5710,
"text": "An if can have zero or one else's and it must come after an else if."
},
{
"code": null,
"e": 5855,
"s": 5779,
"text": "An if can have zero to many else...if's and they must come before the else."
},
{
"code": null,
"e": 5931,
"s": 5855,
"text": "An if can have zero to many else...if's and they must come before the else."
},
{
"code": null,
"e": 6019,
"s": 5931,
"text": "Once an else...if succeeds, none of the remaining else...if's or else's will be tested."
},
{
"code": null,
"e": 6107,
"s": 6019,
"text": "Once an else...if succeeds, none of the remaining else...if's or else's will be tested."
},
{
"code": null,
"e": 6185,
"s": 6107,
"text": "The syntax of an if...else if...else statement in C programming language is −"
},
{
"code": null,
"e": 6531,
"s": 6185,
"text": "if(boolean_expression 1) {\n\n /* Executes when the boolean expression 1 is true */\n}\nelse if( boolean_expression 2) {\n\n /* Executes when the boolean expression 2 is true */\n}\nelse if( boolean_expression 3) {\n\n /* Executes when the boolean expression 3 is true */\n} else {\n \n /* Executes when the none of the above condition is true */\n}"
},
{
"code": null,
"e": 6631,
"s": 6531,
"text": "Now with the help of if...elseif...else statement, the very first program can be coded as follows −"
},
{
"code": null,
"e": 6890,
"s": 6631,
"text": "#include <stdio.h>\n\nint main() {\n int x = 45;\n \n if( x > 95) {\n printf( \"Student is brilliant\\n\");\n } \n else if( x < 30) {\n printf( \"Student is poor\\n\");\n } \n else if( x < 95 && x > 30 ) {\n printf( \"Student is average\\n\");\n }\n}"
},
{
"code": null,
"e": 6961,
"s": 6890,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 6981,
"s": 6961,
"text": "Student is average\n"
},
{
"code": null,
"e": 7238,
"s": 6981,
"text": "A switch statement is an alternative of if statements which allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. It has the following syntax −"
},
{
"code": null,
"e": 7401,
"s": 7238,
"text": "switch(expression){\n case ONE :\n statement(s);\n break;\n case TWO:\n statement(s);\n break;\n ......\n \n default :\n statement(s);\n}\n"
},
{
"code": null,
"e": 7897,
"s": 7401,
"text": "The expression used in a switch statement must give an integer value, which will be compared for equality with different cases given. Wherever an expression value matches with a case value, the body of that case will be executed and finally, the switch will be terminated using a break statement. If no break statements are provided, then the computer continues executing other statements available below to the matched case. If none of the cases matches, then the default case body is executed."
},
{
"code": null,
"e": 7980,
"s": 7897,
"text": "The above syntax can be represented in the form of a flow diagram as shown below −"
},
{
"code": null,
"e": 8122,
"s": 7980,
"text": "Now, let's consider another example where we want to write the equivalent English word for a given number. Then, it can be coded as follows −"
},
{
"code": null,
"e": 8491,
"s": 8122,
"text": "#include <stdio.h>\n\nint main() {\n int x = 2;\n \n switch( x ){\n case 1 :\n printf( \"One\\n\");\n break;\n case 2 :\n printf( \"Two\\n\");\n break;\n case 3 :\n printf( \"Three\\n\");\n break;\n case 4 :\n printf( \"Four\\n\");\n break;\n default :\n printf( \"None of the above...\\n\");\n }\n}"
},
{
"code": null,
"e": 8562,
"s": 8491,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 8567,
"s": 8562,
"text": "Two\n"
},
{
"code": null,
"e": 8696,
"s": 8567,
"text": "Following is the equivalent program written in Java which too supports if, if...else, if...elseif...else, and switch statements."
},
{
"code": null,
"e": 8832,
"s": 8696,
"text": "You can try to execute the following program to see the output, which must be identical to the result generated by the above C example."
},
{
"code": null,
"e": 9191,
"s": 8832,
"text": "public class DemoJava {\n public static void main(String []args) {\n int x = 45;\n \n if( x > 95) {\n System.out.println( \"Student is brilliant\");\n } \n else if( x < 30) {\n System.out.println( \"Student is poor\");\n } \n else if( x < 95 && x > 30 ) {\n System.out.println( \"Student is average\");\n }\n }\n}"
},
{
"code": null,
"e": 9262,
"s": 9191,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 9282,
"s": 9262,
"text": "Student is average\n"
},
{
"code": null,
"e": 9585,
"s": 9282,
"text": "Following is the equivalent program written in Python. Python provides if, if...else, if...elif...else, and switch statements. Here, you must note that Python does not make use of curly braces for conditional body, instead it simply identifies the body of the block using indentation of the statements."
},
{
"code": null,
"e": 9650,
"s": 9585,
"text": "You can try to execute the following program to see the output −"
},
{
"code": null,
"e": 9812,
"s": 9650,
"text": "x = 45\n\nif x > 95:\n print \"Student is brilliant\"\nelif x < 30:\n print \"Student is poor\"\nelif x < 95 and x > 30:\n print \"Student is average\"\n\nprint \"The end\""
},
{
"code": null,
"e": 9883,
"s": 9812,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 9911,
"s": 9883,
"text": "Student is average\nThe end\n"
},
{
"code": null,
"e": 9948,
"s": 9911,
"text": "\n 107 Lectures \n 13.5 hours \n"
},
{
"code": null,
"e": 9967,
"s": 9948,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 10001,
"s": 9967,
"text": "\n 106 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 10020,
"s": 10001,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 10053,
"s": 10020,
"text": "\n 99 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 10072,
"s": 10053,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 10107,
"s": 10072,
"text": "\n 46 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 10115,
"s": 10107,
"text": " Shweta"
},
{
"code": null,
"e": 10148,
"s": 10115,
"text": "\n 70 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 10165,
"s": 10148,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10198,
"s": 10165,
"text": "\n 52 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 10220,
"s": 10198,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 10227,
"s": 10220,
"text": " Print"
},
{
"code": null,
"e": 10238,
"s": 10227,
"text": " Add Notes"
}
] |
override Keyword in C++
|
The function overriding is the most common feature of C++. Basically function overriding means redefine a function which is present in the base class, also be defined in the derived class. So the function signatures are the same but the behavior will be different.
But there may be a situation when a programmer makes a mistake while overriding that function. Like if the signature is not the same, then that will be treated as another function, but not the overridden method or that. In that case, we can use the override keyword. This keyword is introduced in C+ +11. When the compiler finds this kind of keyword, it can understand that this is an overridden version of the same class.
Let us see the example to understand the concept.
#include <iostream>
using namespace std;
class BaseClass{
public:
virtual void display() {
cout << "Displaying from Base Class\n";
}
};
class DerivedClass : public BaseClass{
public:
void display() {
cout << "Displaying from Derived Class\n";
}
};
main() {
BaseClass *b_ptr;
b_ptr = new DerivedClass();
b_ptr->display();
}
Displaying from Derived Class
In this case the program is working fine as the signatures are the same. In the following example, the signature will be different. For the override keyword, it will generate an error.
#include <iostream>
using namespace std;
class BaseClass{
public:
virtual void display() {
cout << "Displaying from Base Class\n";
}
};
class DerivedClass : public BaseClass{
public:
void display(int x) override{
cout << "Displaying from Derived Class\n";
}
};
main() {
BaseClass *b_ptr;
b_ptr = new DerivedClass();
b_ptr->display();
}
[Error] 'void DerivedClass::display(int)' marked override, but does not override
In this case, the program is working fine as the signatures are the same. In the following example, the signature will be different. For the override keyword, it will generate error.
|
[
{
"code": null,
"e": 1327,
"s": 1062,
"text": "The function overriding is the most common feature of C++. Basically function overriding means redefine a function which is present in the base class, also be defined in the derived class. So the function signatures are the same but the behavior will be different."
},
{
"code": null,
"e": 1750,
"s": 1327,
"text": "But there may be a situation when a programmer makes a mistake while overriding that function. Like if the signature is not the same, then that will be treated as another function, but not the overridden method or that. In that case, we can use the override keyword. This keyword is introduced in C+ +11. When the compiler finds this kind of keyword, it can understand that this is an overridden version of the same class."
},
{
"code": null,
"e": 1800,
"s": 1750,
"text": "Let us see the example to understand the concept."
},
{
"code": null,
"e": 2180,
"s": 1800,
"text": "#include <iostream>\nusing namespace std;\nclass BaseClass{\n public:\n virtual void display() {\n cout << \"Displaying from Base Class\\n\";\n }\n};\nclass DerivedClass : public BaseClass{\n public:\n void display() {\n cout << \"Displaying from Derived Class\\n\";\n }\n};\nmain() {\n BaseClass *b_ptr;\n b_ptr = new DerivedClass();\n b_ptr->display();\n}"
},
{
"code": null,
"e": 2210,
"s": 2180,
"text": "Displaying from Derived Class"
},
{
"code": null,
"e": 2395,
"s": 2210,
"text": "In this case the program is working fine as the signatures are the same. In the following example, the signature will be different. For the override keyword, it will generate an error."
},
{
"code": null,
"e": 2788,
"s": 2395,
"text": "#include <iostream>\nusing namespace std;\nclass BaseClass{\n public:\n virtual void display() {\n cout << \"Displaying from Base Class\\n\";\n }\n};\nclass DerivedClass : public BaseClass{\n public:\n void display(int x) override{\n cout << \"Displaying from Derived Class\\n\";\n }\n};\nmain() {\n BaseClass *b_ptr;\n b_ptr = new DerivedClass();\n b_ptr->display();\n}"
},
{
"code": null,
"e": 2869,
"s": 2788,
"text": "[Error] 'void DerivedClass::display(int)' marked override, but does not override"
},
{
"code": null,
"e": 3052,
"s": 2869,
"text": "In this case, the program is working fine as the signatures are the same. In the following example, the signature will be different. For the override keyword, it will generate error."
}
] |
Collision Detection in CSMA/CD - GeeksforGeeks
|
31 Aug, 2021
CSMA/CD (Carrier Sense Multiple Access/ Collision Detection) is a media access control method that was widely used in Early Ethernet technology/LANs When there used to be shared Bus Topology and each node ( Computers) were connected By Coaxial Cables. Now a Days Ethernet is Full Duplex and CSMA/CD is not used as Topology is either Star (connected via Switch or Router) or Point to Point ( Direct Connection) but they are still supported though.
Consider a scenario where there are ‘n’ stations on a link and all are waiting to transfer data through that channel. In this case, all ‘n’ stations would want to access the link/channel to transfer their own data. Problem arises when more than one station transmits the data at the moment. In this case, there will be collisions in the data from different stations.
CSMA/CD is one such technique where different stations that follow this protocol agree on some terms and collision detection measures for effective transmission. This protocol decides which station will transmit when so that data reaches the destination without corruption.
How CSMA/CD works?
Step 1: Check if the sender is ready for transmitting data packets.
Step 2: Check if the transmission link is idle? Sender has to keep on checking if the transmission link/medium is idle. For this, it continuously senses transmissions from other nodes. Sender sends dummy data on the link. If it does not receive any collision signal, this means the link is idle at the moment. If it senses that the carrier is free and there are no collisions, it sends the data. Otherwise, it refrains from sending data.
Step 3: Transmit the data & check for collisions. Sender transmits its data on the link. CSMA/CD does not use an ‘acknowledgment’ system. It checks for successful and unsuccessful transmissions through collision signals. During transmission, if a collision signal is received by the node, transmission is stopped. The station then transmits a jam signal onto the link and waits for random time intervals before it resends the frame. After some random time, it again attempts to transfer the data and repeats the above process.
Step 4: If no collision was detected in propagation, the sender completes its frame transmission and resets the counters.
How does a station know if its data collide?
Consider the above situation. Two stations, A & B. Propagation Time: Tp = 1 hr ( Signal takes 1 hr to go from A to B)
At time t=0, A transmits its data.
t= 30 mins : Collision occurs.
After the collision occurs, a collision signal is generated and sent to both A & B to inform the stations about a collision. Since the collision happened midway, the collision signal also takes 30 minutes to reach A & B.
Therefore, t=1 hr: A & B receive collision signals.
This collision signal is received by all the stations on that link. Then,
How to ensure that it is our station’s data that collided? For this, Transmission time (Tt) > Propagation Time (Tp) [Rough bound] This is because, we want that before we transmit the last bit of our data from our station, we should at least be sure that some of the bits have already reached their destination. This ensures that the link is not busy and collisions will not occur. But, above is a loose bound. We have not taken the time taken by the collision signal to travel back to us. For this consider the worst-case scenario.
Consider the above system again.
At time t=0, A transmits its data.
t= 59:59 mins : Collision occurs
This collision occurs just before the data reaches B. Now the collision signal takes 59:59 minutes again to reach A. Hence, A receives the collision information approximately after 2 hours, that is, after 2 * Tp.
Hence, to ensure tighter bound, to detect the collision completely,
Tt > >= 2 * Tp
This is the maximum collision time that a system can take to detect if the collision was of its own data.
What should be the minimum length of the packet to be transmitted? Transmission Time = Tt = Length of the packet/ Bandwidth of the link [Number of bits transmitted by sender per second] Substituting above, we get, Length of the packet/ Bandwidth of the link>= 2 * Tp
Length of the packet >= 2 * Tp * Bandwidth of the link
Padding helps in the cases where we do not have such long packets. We can pad extra characters to the end of our data to satisfy the above condition.
Read next – Efficiency of CSMA/CD
Alok Prasad
vivekpal23123451254
Pushpender007
Computer Networks
GATE CS
Technical Scripter
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Caesar Cipher in Cryptography
Socket Programming in Python
UDP Server-Client implementation in C
Differences between IPv4 and IPv6
Socket Programming in Java
ACID Properties in DBMS
Page Replacement Algorithms in Operating Systems
Types of Operating Systems
Normal Forms in DBMS
Semaphores in Process Synchronization
|
[
{
"code": null,
"e": 36594,
"s": 36566,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 37042,
"s": 36594,
"text": "CSMA/CD (Carrier Sense Multiple Access/ Collision Detection) is a media access control method that was widely used in Early Ethernet technology/LANs When there used to be shared Bus Topology and each node ( Computers) were connected By Coaxial Cables. Now a Days Ethernet is Full Duplex and CSMA/CD is not used as Topology is either Star (connected via Switch or Router) or Point to Point ( Direct Connection) but they are still supported though. "
},
{
"code": null,
"e": 37410,
"s": 37042,
"text": "Consider a scenario where there are ‘n’ stations on a link and all are waiting to transfer data through that channel. In this case, all ‘n’ stations would want to access the link/channel to transfer their own data. Problem arises when more than one station transmits the data at the moment. In this case, there will be collisions in the data from different stations. "
},
{
"code": null,
"e": 37685,
"s": 37410,
"text": "CSMA/CD is one such technique where different stations that follow this protocol agree on some terms and collision detection measures for effective transmission. This protocol decides which station will transmit when so that data reaches the destination without corruption. "
},
{
"code": null,
"e": 37705,
"s": 37685,
"text": "How CSMA/CD works? "
},
{
"code": null,
"e": 37773,
"s": 37705,
"text": "Step 1: Check if the sender is ready for transmitting data packets."
},
{
"code": null,
"e": 38211,
"s": 37773,
"text": "Step 2: Check if the transmission link is idle? Sender has to keep on checking if the transmission link/medium is idle. For this, it continuously senses transmissions from other nodes. Sender sends dummy data on the link. If it does not receive any collision signal, this means the link is idle at the moment. If it senses that the carrier is free and there are no collisions, it sends the data. Otherwise, it refrains from sending data."
},
{
"code": null,
"e": 38738,
"s": 38211,
"text": "Step 3: Transmit the data & check for collisions. Sender transmits its data on the link. CSMA/CD does not use an ‘acknowledgment’ system. It checks for successful and unsuccessful transmissions through collision signals. During transmission, if a collision signal is received by the node, transmission is stopped. The station then transmits a jam signal onto the link and waits for random time intervals before it resends the frame. After some random time, it again attempts to transfer the data and repeats the above process."
},
{
"code": null,
"e": 38860,
"s": 38738,
"text": "Step 4: If no collision was detected in propagation, the sender completes its frame transmission and resets the counters."
},
{
"code": null,
"e": 38907,
"s": 38860,
"text": "How does a station know if its data collide? "
},
{
"code": null,
"e": 39026,
"s": 38907,
"text": "Consider the above situation. Two stations, A & B. Propagation Time: Tp = 1 hr ( Signal takes 1 hr to go from A to B) "
},
{
"code": null,
"e": 39100,
"s": 39026,
"text": "At time t=0, A transmits its data.\n t= 30 mins : Collision occurs."
},
{
"code": null,
"e": 39322,
"s": 39100,
"text": "After the collision occurs, a collision signal is generated and sent to both A & B to inform the stations about a collision. Since the collision happened midway, the collision signal also takes 30 minutes to reach A & B. "
},
{
"code": null,
"e": 39374,
"s": 39322,
"text": "Therefore, t=1 hr: A & B receive collision signals."
},
{
"code": null,
"e": 39449,
"s": 39374,
"text": "This collision signal is received by all the stations on that link. Then, "
},
{
"code": null,
"e": 39982,
"s": 39449,
"text": "How to ensure that it is our station’s data that collided? For this, Transmission time (Tt) > Propagation Time (Tp) [Rough bound] This is because, we want that before we transmit the last bit of our data from our station, we should at least be sure that some of the bits have already reached their destination. This ensures that the link is not busy and collisions will not occur. But, above is a loose bound. We have not taken the time taken by the collision signal to travel back to us. For this consider the worst-case scenario. "
},
{
"code": null,
"e": 40016,
"s": 39982,
"text": "Consider the above system again. "
},
{
"code": null,
"e": 40092,
"s": 40016,
"text": "At time t=0, A transmits its data.\n t= 59:59 mins : Collision occurs"
},
{
"code": null,
"e": 40307,
"s": 40092,
"text": "This collision occurs just before the data reaches B. Now the collision signal takes 59:59 minutes again to reach A. Hence, A receives the collision information approximately after 2 hours, that is, after 2 * Tp. "
},
{
"code": null,
"e": 40394,
"s": 40307,
"text": "Hence, to ensure tighter bound, to detect the collision completely,\n Tt > >= 2 * Tp "
},
{
"code": null,
"e": 40501,
"s": 40394,
"text": "This is the maximum collision time that a system can take to detect if the collision was of its own data. "
},
{
"code": null,
"e": 40769,
"s": 40501,
"text": "What should be the minimum length of the packet to be transmitted? Transmission Time = Tt = Length of the packet/ Bandwidth of the link [Number of bits transmitted by sender per second] Substituting above, we get, Length of the packet/ Bandwidth of the link>= 2 * Tp "
},
{
"code": null,
"e": 40824,
"s": 40769,
"text": "Length of the packet >= 2 * Tp * Bandwidth of the link"
},
{
"code": null,
"e": 40975,
"s": 40824,
"text": "Padding helps in the cases where we do not have such long packets. We can pad extra characters to the end of our data to satisfy the above condition. "
},
{
"code": null,
"e": 41010,
"s": 40975,
"text": "Read next – Efficiency of CSMA/CD "
},
{
"code": null,
"e": 41022,
"s": 41010,
"text": "Alok Prasad"
},
{
"code": null,
"e": 41042,
"s": 41022,
"text": "vivekpal23123451254"
},
{
"code": null,
"e": 41056,
"s": 41042,
"text": "Pushpender007"
},
{
"code": null,
"e": 41074,
"s": 41056,
"text": "Computer Networks"
},
{
"code": null,
"e": 41082,
"s": 41074,
"text": "GATE CS"
},
{
"code": null,
"e": 41101,
"s": 41082,
"text": "Technical Scripter"
},
{
"code": null,
"e": 41119,
"s": 41101,
"text": "Computer Networks"
},
{
"code": null,
"e": 41217,
"s": 41119,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41247,
"s": 41217,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 41276,
"s": 41247,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 41314,
"s": 41276,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 41348,
"s": 41314,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 41375,
"s": 41348,
"text": "Socket Programming in Java"
},
{
"code": null,
"e": 41399,
"s": 41375,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 41448,
"s": 41399,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 41475,
"s": 41448,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 41496,
"s": 41475,
"text": "Normal Forms in DBMS"
}
] |
Exploratory Data Analysis of the FIFA 19 Dataset in Python | by Sadrach Pierre, Ph.D. | Towards Data Science
|
In this post we will perform simple exploratory data analysis of the FIFA 19 data set. The data set can be found on Kaggle. FIFA is the Fédération Internationale de Football Association and FIFA 19 is part of the FIFA series of association football video games. It is one of the best selling video games of all time selling over 260 million copies to date.
For this analysis we will be using the python pandas library, numpy, seaborn and matplotlib. The dataset contains 89 columns but we will limit our analysis to the following ten columns:
Name — Name of PlayerAge — Age of PlayerNationality — Nationality of PlayerValue — Current Market ValueWage — Wage of PlayerPreferred Foot — Preferred foot of playerHeight — Height of PlayerWeight — Weight of playerPosition — Position on the pitchOverall — Player’s Overall Rating
Name — Name of Player
Age — Age of Player
Nationality — Nationality of Player
Value — Current Market Value
Wage — Wage of Player
Preferred Foot — Preferred foot of player
Height — Height of Player
Weight — Weight of player
Position — Position on the pitch
Overall — Player’s Overall Rating
Let’s get started!
First let’s import the pandas library and read the csv file into a pandas dataframe and print the first five rows for the first sixteen columns:
import pandas as pddf = pd.read_csv("data.csv")print(df.head())
We can filter the dataframe so it only includes the ten columns we want:
df = df[['Name', 'Age', 'Nationality', Value', 'Wage', 'Preferred Foot', 'Height', 'Weight', Position', 'Overall']]print(df.head())
First thing we can do is generate some statistics on the height column. The values are given as strings so we will want to convert them to a number we can use in calculations. Here we convert the height strings into centimeter values. We do this by multiplying the first element of the string, for example ‘5’7’, by 12.0 (inches) and we add the third element of the string ‘7’ (which is in inches) and multiply the final result by 2.54 (centimeters):
Height_cm = []for i in list(df['Height'].values): try: Height_cm.append((float(str(i)[0])*12.0 + float(str(i)[2:]))*2.54) except(ValueError): Height_cm.append(np.nan) df['Height_cm'] = Height_cm
First we initialize a list called ‘Height_cm’ and we iterate over the height string value in the dataframe. We insert the conversion statements in between try except clause since there are cases where the strings contain non-numeric values, specifically there are missing height values. Whenever we reach a missing value we append an np.nan (numpy ‘not a number’) value. Finally we defined the new column to be the list we just populated.
Next let’s remove the missing values from the dataframe and print the first five rows:
df.dropna(inplace = True)print(df['Height_cm'].head())
We can look at the mean and standard deviation in Height in cm:
print("Mean: ", df['Height_cm'].mean())print("Standard Deviation: ", df['Height_cm'].std())
We can also generate a histogram of the heights:
import seaborn as sns sns.set()df['Height_cm'].hist(bins = 10)
We can also wrap this up in a function and resuse it for any numeric column:
import seaborn as sns import matplotlib.pyplot as pltdef get_statistics(numeric_column_name): print("Mean {}: ".format(numeric_column_name), df[numeric_column_name].mean()) print("Standard Deviation in {}: ".format(numeric_column_name), df[numeric_column_name].std()) sns.set() plt.title("{} Histogram".format(numeric_column_name)) df[numeric_column_name].hist(bins = 10) get_statistics('Height_cm')
which generates the same output as above.
We can also convert the weight column to kilograms for consistent use of the metric system. We do this by taking the first three elements of each string values in the ‘Weight’ column, convert them into floating point values and the divide by the conversion factor between Kg and pounds (2.20462):
df['Weight_kg'] = df['Weight'].str[:3].astype(float)/2.20462print(df.head())
We can call our generate_statistics function with ‘Weight_kg’:
get_statistics('Weight_kg')
We can also look at a the frequency in Nationality of each player using the ‘Counter’ method from the collections module:
from collections import Counterprint(Counter(df['Nationality'].values))
We can limit the counter to output only the five most common nationalities:
print(Counter(df['Nationality'].values).most_common(5))
As you can see England is the most frequent nationality with 1,657 records, followed by Germany with 1,195 and Spain with 1,071. We can display this output in a bar chart:
bar_plot = dict(Counter(df['Nationality'].values).most_common(5))plt.bar(*zip(*bar_plot.items()))plt.show()
Again, we can define a function that let’s us plot the most common values for any categorical column:
def plot_most_common(category): bar_plot = dict(Counter(df[category].values).most_common(5)) plt.bar(*zip(*bar_plot.items())) plt.show()
If we call the function with ‘Position’ we get:
plot_most_common('Position')
Next let’s convert the value (which is the market value for the player) and the wage into numeric values we can use in calculations. First lets truncate the string values in the ‘Value’ column such that we remove the ‘Euro’ and the ‘M’. The we can then convert each string into a floating point and multiply by 1e6:
value_list = []for i in list(df['Value'].values): try: value_list.append(float(i)*1e6) except(ValueError): value_list.append(np.nan)df['Value_numeric'] = value_list
We can do the same for ‘Wage’, but here we multiply by 1e3:
wage_list = []for i in list(df['Wage'].values): try: wage_list.append(float(i)*1e3) except(ValueError): wage_list.append(np.nan)df['Wage_numeric'] = wage_list
We will also want to convert the string values in the ‘Age’ column into integers:
df['Age'] = df['Age'].astype(int)
From here we can generate a heat map from the numerical columns which will show us how strongly correlated each variable is with the other. Let’s filter the dataframe so that it only includes numerical values and generate a heat map from the resulting dataframe:
numerical_columns = df[['Height_cm', 'Weight_kg', 'Value_numeric', 'Age', 'Wage_numeric']]sns.heatmap(numerical_columns.corr(), annot=True)plt.show()
We can also use box plots to visualize the distribution in numeric values based on the minimum, maximum, median, first quartile, and third quartile. If you are unfamiliar with them take a look at the article Understanding Boxplots.
For example the distribution in market value for England, Germany and Spain:
df = df[df['Nationality'].isin(['England', 'Germany', 'Spain'])]sns.boxplot(x= df['Nationality'], y = df['Value_numeric'])plt.show()
And the distribution in age:
sns.boxplot(x= df['Nationality'], y = df['Age'])plt.show()
The distribution in weight:
sns.boxplot(x= df['Nationality'], y = df['Weight_kg'])plt.show()
And height:
sns.boxplot(x= df['Nationality'], y = df['Height_cm'])plt.show()
I’ll stop here but feel free to play around with the data and code yourself. The code from this post is available on GitHub. Thank you for reading!
|
[
{
"code": null,
"e": 531,
"s": 172,
"text": "In this post we will perform simple exploratory data analysis of the FIFA 19 data set. The data set can be found on Kaggle. FIFA is the Fédération Internationale de Football Association and FIFA 19 is part of the FIFA series of association football video games. It is one of the best selling video games of all time selling over 260 million copies to date."
},
{
"code": null,
"e": 717,
"s": 531,
"text": "For this analysis we will be using the python pandas library, numpy, seaborn and matplotlib. The dataset contains 89 columns but we will limit our analysis to the following ten columns:"
},
{
"code": null,
"e": 998,
"s": 717,
"text": "Name — Name of PlayerAge — Age of PlayerNationality — Nationality of PlayerValue — Current Market ValueWage — Wage of PlayerPreferred Foot — Preferred foot of playerHeight — Height of PlayerWeight — Weight of playerPosition — Position on the pitchOverall — Player’s Overall Rating"
},
{
"code": null,
"e": 1020,
"s": 998,
"text": "Name — Name of Player"
},
{
"code": null,
"e": 1040,
"s": 1020,
"text": "Age — Age of Player"
},
{
"code": null,
"e": 1076,
"s": 1040,
"text": "Nationality — Nationality of Player"
},
{
"code": null,
"e": 1105,
"s": 1076,
"text": "Value — Current Market Value"
},
{
"code": null,
"e": 1127,
"s": 1105,
"text": "Wage — Wage of Player"
},
{
"code": null,
"e": 1169,
"s": 1127,
"text": "Preferred Foot — Preferred foot of player"
},
{
"code": null,
"e": 1195,
"s": 1169,
"text": "Height — Height of Player"
},
{
"code": null,
"e": 1221,
"s": 1195,
"text": "Weight — Weight of player"
},
{
"code": null,
"e": 1254,
"s": 1221,
"text": "Position — Position on the pitch"
},
{
"code": null,
"e": 1288,
"s": 1254,
"text": "Overall — Player’s Overall Rating"
},
{
"code": null,
"e": 1307,
"s": 1288,
"text": "Let’s get started!"
},
{
"code": null,
"e": 1452,
"s": 1307,
"text": "First let’s import the pandas library and read the csv file into a pandas dataframe and print the first five rows for the first sixteen columns:"
},
{
"code": null,
"e": 1516,
"s": 1452,
"text": "import pandas as pddf = pd.read_csv(\"data.csv\")print(df.head())"
},
{
"code": null,
"e": 1589,
"s": 1516,
"text": "We can filter the dataframe so it only includes the ten columns we want:"
},
{
"code": null,
"e": 1721,
"s": 1589,
"text": "df = df[['Name', 'Age', 'Nationality', Value', 'Wage', 'Preferred Foot', 'Height', 'Weight', Position', 'Overall']]print(df.head())"
},
{
"code": null,
"e": 2172,
"s": 1721,
"text": "First thing we can do is generate some statistics on the height column. The values are given as strings so we will want to convert them to a number we can use in calculations. Here we convert the height strings into centimeter values. We do this by multiplying the first element of the string, for example ‘5’7’, by 12.0 (inches) and we add the third element of the string ‘7’ (which is in inches) and multiply the final result by 2.54 (centimeters):"
},
{
"code": null,
"e": 2394,
"s": 2172,
"text": "Height_cm = []for i in list(df['Height'].values): try: Height_cm.append((float(str(i)[0])*12.0 + float(str(i)[2:]))*2.54) except(ValueError): Height_cm.append(np.nan) df['Height_cm'] = Height_cm"
},
{
"code": null,
"e": 2833,
"s": 2394,
"text": "First we initialize a list called ‘Height_cm’ and we iterate over the height string value in the dataframe. We insert the conversion statements in between try except clause since there are cases where the strings contain non-numeric values, specifically there are missing height values. Whenever we reach a missing value we append an np.nan (numpy ‘not a number’) value. Finally we defined the new column to be the list we just populated."
},
{
"code": null,
"e": 2920,
"s": 2833,
"text": "Next let’s remove the missing values from the dataframe and print the first five rows:"
},
{
"code": null,
"e": 2975,
"s": 2920,
"text": "df.dropna(inplace = True)print(df['Height_cm'].head())"
},
{
"code": null,
"e": 3039,
"s": 2975,
"text": "We can look at the mean and standard deviation in Height in cm:"
},
{
"code": null,
"e": 3131,
"s": 3039,
"text": "print(\"Mean: \", df['Height_cm'].mean())print(\"Standard Deviation: \", df['Height_cm'].std())"
},
{
"code": null,
"e": 3180,
"s": 3131,
"text": "We can also generate a histogram of the heights:"
},
{
"code": null,
"e": 3243,
"s": 3180,
"text": "import seaborn as sns sns.set()df['Height_cm'].hist(bins = 10)"
},
{
"code": null,
"e": 3320,
"s": 3243,
"text": "We can also wrap this up in a function and resuse it for any numeric column:"
},
{
"code": null,
"e": 3744,
"s": 3320,
"text": "import seaborn as sns import matplotlib.pyplot as pltdef get_statistics(numeric_column_name): print(\"Mean {}: \".format(numeric_column_name), df[numeric_column_name].mean()) print(\"Standard Deviation in {}: \".format(numeric_column_name), df[numeric_column_name].std()) sns.set() plt.title(\"{} Histogram\".format(numeric_column_name)) df[numeric_column_name].hist(bins = 10) get_statistics('Height_cm')"
},
{
"code": null,
"e": 3786,
"s": 3744,
"text": "which generates the same output as above."
},
{
"code": null,
"e": 4083,
"s": 3786,
"text": "We can also convert the weight column to kilograms for consistent use of the metric system. We do this by taking the first three elements of each string values in the ‘Weight’ column, convert them into floating point values and the divide by the conversion factor between Kg and pounds (2.20462):"
},
{
"code": null,
"e": 4160,
"s": 4083,
"text": "df['Weight_kg'] = df['Weight'].str[:3].astype(float)/2.20462print(df.head())"
},
{
"code": null,
"e": 4223,
"s": 4160,
"text": "We can call our generate_statistics function with ‘Weight_kg’:"
},
{
"code": null,
"e": 4251,
"s": 4223,
"text": "get_statistics('Weight_kg')"
},
{
"code": null,
"e": 4373,
"s": 4251,
"text": "We can also look at a the frequency in Nationality of each player using the ‘Counter’ method from the collections module:"
},
{
"code": null,
"e": 4445,
"s": 4373,
"text": "from collections import Counterprint(Counter(df['Nationality'].values))"
},
{
"code": null,
"e": 4521,
"s": 4445,
"text": "We can limit the counter to output only the five most common nationalities:"
},
{
"code": null,
"e": 4577,
"s": 4521,
"text": "print(Counter(df['Nationality'].values).most_common(5))"
},
{
"code": null,
"e": 4749,
"s": 4577,
"text": "As you can see England is the most frequent nationality with 1,657 records, followed by Germany with 1,195 and Spain with 1,071. We can display this output in a bar chart:"
},
{
"code": null,
"e": 4857,
"s": 4749,
"text": "bar_plot = dict(Counter(df['Nationality'].values).most_common(5))plt.bar(*zip(*bar_plot.items()))plt.show()"
},
{
"code": null,
"e": 4959,
"s": 4857,
"text": "Again, we can define a function that let’s us plot the most common values for any categorical column:"
},
{
"code": null,
"e": 5105,
"s": 4959,
"text": "def plot_most_common(category): bar_plot = dict(Counter(df[category].values).most_common(5)) plt.bar(*zip(*bar_plot.items())) plt.show()"
},
{
"code": null,
"e": 5153,
"s": 5105,
"text": "If we call the function with ‘Position’ we get:"
},
{
"code": null,
"e": 5182,
"s": 5153,
"text": "plot_most_common('Position')"
},
{
"code": null,
"e": 5498,
"s": 5182,
"text": "Next let’s convert the value (which is the market value for the player) and the wage into numeric values we can use in calculations. First lets truncate the string values in the ‘Value’ column such that we remove the ‘Euro’ and the ‘M’. The we can then convert each string into a floating point and multiply by 1e6:"
},
{
"code": null,
"e": 5683,
"s": 5498,
"text": "value_list = []for i in list(df['Value'].values): try: value_list.append(float(i)*1e6) except(ValueError): value_list.append(np.nan)df['Value_numeric'] = value_list"
},
{
"code": null,
"e": 5743,
"s": 5683,
"text": "We can do the same for ‘Wage’, but here we multiply by 1e3:"
},
{
"code": null,
"e": 5922,
"s": 5743,
"text": "wage_list = []for i in list(df['Wage'].values): try: wage_list.append(float(i)*1e3) except(ValueError): wage_list.append(np.nan)df['Wage_numeric'] = wage_list"
},
{
"code": null,
"e": 6004,
"s": 5922,
"text": "We will also want to convert the string values in the ‘Age’ column into integers:"
},
{
"code": null,
"e": 6038,
"s": 6004,
"text": "df['Age'] = df['Age'].astype(int)"
},
{
"code": null,
"e": 6301,
"s": 6038,
"text": "From here we can generate a heat map from the numerical columns which will show us how strongly correlated each variable is with the other. Let’s filter the dataframe so that it only includes numerical values and generate a heat map from the resulting dataframe:"
},
{
"code": null,
"e": 6451,
"s": 6301,
"text": "numerical_columns = df[['Height_cm', 'Weight_kg', 'Value_numeric', 'Age', 'Wage_numeric']]sns.heatmap(numerical_columns.corr(), annot=True)plt.show()"
},
{
"code": null,
"e": 6683,
"s": 6451,
"text": "We can also use box plots to visualize the distribution in numeric values based on the minimum, maximum, median, first quartile, and third quartile. If you are unfamiliar with them take a look at the article Understanding Boxplots."
},
{
"code": null,
"e": 6760,
"s": 6683,
"text": "For example the distribution in market value for England, Germany and Spain:"
},
{
"code": null,
"e": 6893,
"s": 6760,
"text": "df = df[df['Nationality'].isin(['England', 'Germany', 'Spain'])]sns.boxplot(x= df['Nationality'], y = df['Value_numeric'])plt.show()"
},
{
"code": null,
"e": 6922,
"s": 6893,
"text": "And the distribution in age:"
},
{
"code": null,
"e": 6981,
"s": 6922,
"text": "sns.boxplot(x= df['Nationality'], y = df['Age'])plt.show()"
},
{
"code": null,
"e": 7009,
"s": 6981,
"text": "The distribution in weight:"
},
{
"code": null,
"e": 7074,
"s": 7009,
"text": "sns.boxplot(x= df['Nationality'], y = df['Weight_kg'])plt.show()"
},
{
"code": null,
"e": 7086,
"s": 7074,
"text": "And height:"
},
{
"code": null,
"e": 7151,
"s": 7086,
"text": "sns.boxplot(x= df['Nationality'], y = df['Height_cm'])plt.show()"
}
] |
Program to count number of elements in a list that contains odd number of digits in Python
|
Suppose we have a list of positive numbers called nums, we have to find the number of
elements that have odd number of digits.
So, if the input is like [1, 300, 12, 10, 3, 51236, 1245], then the output will be 4
To solve this, we will follow these steps −
c:= 0
for i in range 0 to size of nums, dos:= digit count of nums[i]if s is odd, thenc:= c+1
s:= digit count of nums[i]
if s is odd, thenc:= c+1
c:= c+1
return c
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, nums):
c=0
for i in range(len(nums)):
s=len(str(nums[i]))
if s%2!=0:
c=c+1
return c
ob = Solution()
print(ob.solve([1, 300, 12, 10, 3, 51236, 1245]))
[1, 300, 12, 10, 3, 51236, 1245]
4
|
[
{
"code": null,
"e": 1189,
"s": 1062,
"text": "Suppose we have a list of positive numbers called nums, we have to find the number of\nelements that have odd number of digits."
},
{
"code": null,
"e": 1274,
"s": 1189,
"text": "So, if the input is like [1, 300, 12, 10, 3, 51236, 1245], then the output will be 4"
},
{
"code": null,
"e": 1318,
"s": 1274,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1324,
"s": 1318,
"text": "c:= 0"
},
{
"code": null,
"e": 1411,
"s": 1324,
"text": "for i in range 0 to size of nums, dos:= digit count of nums[i]if s is odd, thenc:= c+1"
},
{
"code": null,
"e": 1438,
"s": 1411,
"text": "s:= digit count of nums[i]"
},
{
"code": null,
"e": 1463,
"s": 1438,
"text": "if s is odd, thenc:= c+1"
},
{
"code": null,
"e": 1471,
"s": 1463,
"text": "c:= c+1"
},
{
"code": null,
"e": 1480,
"s": 1471,
"text": "return c"
},
{
"code": null,
"e": 1550,
"s": 1480,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1561,
"s": 1550,
"text": " Live Demo"
},
{
"code": null,
"e": 1794,
"s": 1561,
"text": "class Solution:\n def solve(self, nums):\n c=0\n for i in range(len(nums)):\n s=len(str(nums[i]))\n if s%2!=0:\n c=c+1\n return c\nob = Solution()\nprint(ob.solve([1, 300, 12, 10, 3, 51236, 1245]))"
},
{
"code": null,
"e": 1827,
"s": 1794,
"text": "[1, 300, 12, 10, 3, 51236, 1245]"
},
{
"code": null,
"e": 1829,
"s": 1827,
"text": "4"
}
] |
C++ STL Tutorial
|
Hope you have already understood the concept of C++ Template which we have discussed earlier. The C++ STL (Standard Template Library) is a powerful set of C++ template classes to provide general-purpose classes and functions with templates that implement many popular and commonly used algorithms and data structures like vectors, lists, queues, and stacks.
At the core of the C++ Standard Template Library are following three well-structured components −
Containers
Containers are used to manage collections of objects of a certain kind. There are several different types of containers like deque, list, vector, map etc.
Algorithms
Algorithms act on containers. They provide the means by which you will perform initialization, sorting, searching, and transforming of the contents of containers.
Iterators
Iterators are used to step through the elements of collections of objects. These collections may be containers or subsets of containers.
We will discuss about all the three C++ STL components in next chapter while discussing C++ Standard Library. For now, keep in mind that all the three components have a rich set of pre-defined functions which help us in doing complicated tasks in very easy fashion.
Let us take the following program that demonstrates the vector container (a C++ Standard Template) which is similar to an array with an exception that it automatically handles its own storage requirements in case it grows −
#include <iostream>
#include <vector>
using namespace std;
int main() {
// create a vector to store int
vector<int> vec;
int i;
// display the original size of vec
cout << "vector size = " << vec.size() << endl;
// push 5 values into the vector
for(i = 0; i < 5; i++) {
vec.push_back(i);
}
// display extended size of vec
cout << "extended vector size = " << vec.size() << endl;
// access 5 values from the vector
for(i = 0; i < 5; i++) {
cout << "value of vec [" << i << "] = " << vec[i] << endl;
}
// use iterator to access the values
vector<int>::iterator v = vec.begin();
while( v != vec.end()) {
cout << "value of v = " << *v << endl;
v++;
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
vector size = 0
extended vector size = 5
value of vec [0] = 0
value of vec [1] = 1
value of vec [2] = 2
value of vec [3] = 3
value of vec [4] = 4
value of v = 0
value of v = 1
value of v = 2
value of v = 3
value of v = 4
Here are following points to be noted related to various functions we used in the above example −
The push_back( ) member function inserts value at the end of the vector, expanding its size as needed.
The push_back( ) member function inserts value at the end of the vector, expanding its size as needed.
The size( ) function displays the size of the vector.
The size( ) function displays the size of the vector.
The function begin( ) returns an iterator to the start of the vector.
The function begin( ) returns an iterator to the start of the vector.
The function end( ) returns an iterator to the end of the vector.
The function end( ) returns an iterator to the end of the vector.
154 Lectures
11.5 hours
Arnab Chakraborty
14 Lectures
57 mins
Kaushik Roy Chowdhury
30 Lectures
12.5 hours
Frahaan Hussain
54 Lectures
3.5 hours
Frahaan Hussain
77 Lectures
5.5 hours
Frahaan Hussain
12 Lectures
3.5 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2676,
"s": 2318,
"text": "Hope you have already understood the concept of C++ Template which we have discussed earlier. The C++ STL (Standard Template Library) is a powerful set of C++ template classes to provide general-purpose classes and functions with templates that implement many popular and commonly used algorithms and data structures like vectors, lists, queues, and stacks."
},
{
"code": null,
"e": 2774,
"s": 2676,
"text": "At the core of the C++ Standard Template Library are following three well-structured components −"
},
{
"code": null,
"e": 2785,
"s": 2774,
"text": "Containers"
},
{
"code": null,
"e": 2941,
"s": 2785,
"text": "Containers are used to manage collections of objects of a certain kind. There are several different types of containers like deque, list, vector, map etc."
},
{
"code": null,
"e": 2952,
"s": 2941,
"text": "Algorithms"
},
{
"code": null,
"e": 3115,
"s": 2952,
"text": "Algorithms act on containers. They provide the means by which you will perform initialization, sorting, searching, and transforming of the contents of containers."
},
{
"code": null,
"e": 3125,
"s": 3115,
"text": "Iterators"
},
{
"code": null,
"e": 3262,
"s": 3125,
"text": "Iterators are used to step through the elements of collections of objects. These collections may be containers or subsets of containers."
},
{
"code": null,
"e": 3528,
"s": 3262,
"text": "We will discuss about all the three C++ STL components in next chapter while discussing C++ Standard Library. For now, keep in mind that all the three components have a rich set of pre-defined functions which help us in doing complicated tasks in very easy fashion."
},
{
"code": null,
"e": 3752,
"s": 3528,
"text": "Let us take the following program that demonstrates the vector container (a C++ Standard Template) which is similar to an array with an exception that it automatically handles its own storage requirements in case it grows −"
},
{
"code": null,
"e": 4499,
"s": 3752,
"text": "#include <iostream>\n#include <vector>\nusing namespace std;\n \nint main() {\n\n // create a vector to store int\n vector<int> vec; \n int i;\n\n // display the original size of vec\n cout << \"vector size = \" << vec.size() << endl;\n\n // push 5 values into the vector\n for(i = 0; i < 5; i++) {\n vec.push_back(i);\n }\n\n // display extended size of vec\n cout << \"extended vector size = \" << vec.size() << endl;\n\n // access 5 values from the vector\n for(i = 0; i < 5; i++) {\n cout << \"value of vec [\" << i << \"] = \" << vec[i] << endl;\n }\n\n // use iterator to access the values\n vector<int>::iterator v = vec.begin();\n while( v != vec.end()) {\n cout << \"value of v = \" << *v << endl;\n v++;\n }\n\n return 0;\n}"
},
{
"code": null,
"e": 4580,
"s": 4499,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4802,
"s": 4580,
"text": "vector size = 0\nextended vector size = 5\nvalue of vec [0] = 0\nvalue of vec [1] = 1\nvalue of vec [2] = 2\nvalue of vec [3] = 3\nvalue of vec [4] = 4\nvalue of v = 0\nvalue of v = 1\nvalue of v = 2\nvalue of v = 3\nvalue of v = 4\n"
},
{
"code": null,
"e": 4900,
"s": 4802,
"text": "Here are following points to be noted related to various functions we used in the above example −"
},
{
"code": null,
"e": 5003,
"s": 4900,
"text": "The push_back( ) member function inserts value at the end of the vector, expanding its size as needed."
},
{
"code": null,
"e": 5106,
"s": 5003,
"text": "The push_back( ) member function inserts value at the end of the vector, expanding its size as needed."
},
{
"code": null,
"e": 5160,
"s": 5106,
"text": "The size( ) function displays the size of the vector."
},
{
"code": null,
"e": 5214,
"s": 5160,
"text": "The size( ) function displays the size of the vector."
},
{
"code": null,
"e": 5284,
"s": 5214,
"text": "The function begin( ) returns an iterator to the start of the vector."
},
{
"code": null,
"e": 5354,
"s": 5284,
"text": "The function begin( ) returns an iterator to the start of the vector."
},
{
"code": null,
"e": 5420,
"s": 5354,
"text": "The function end( ) returns an iterator to the end of the vector."
},
{
"code": null,
"e": 5486,
"s": 5420,
"text": "The function end( ) returns an iterator to the end of the vector."
},
{
"code": null,
"e": 5523,
"s": 5486,
"text": "\n 154 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 5542,
"s": 5523,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5574,
"s": 5542,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 5597,
"s": 5574,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 5633,
"s": 5597,
"text": "\n 30 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 5650,
"s": 5633,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5685,
"s": 5650,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5702,
"s": 5685,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5737,
"s": 5702,
"text": "\n 77 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5754,
"s": 5737,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5789,
"s": 5754,
"text": "\n 12 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5806,
"s": 5789,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5813,
"s": 5806,
"text": " Print"
},
{
"code": null,
"e": 5824,
"s": 5813,
"text": " Add Notes"
}
] |
Predicting IMDb Movie Ratings using Supervised Machine Learning | by Joe Cowell | Towards Data Science
|
My name is Joe Cowell and I recently enrolled in the Metis Data Science Bootcamp. The 12-week immersive program will turn me from ‘data novice’ into a full-fledged data scientist. I mean, the title of this post includes ‘Supervised Machine Learning’ and I’ve only been in the program for three weeks, so it seems like Metis is holding up their end of the bargain. Anyway, I’ll try to make a post about who I am for those interested, but for now, let’s take a look at how I used supervised machine learning to predict IMDb movie ratings.
Background:
During my musical career, the question was always, “how good is this song?” and never, “how much money will this song make?” Maybe that’s why we were your typical starving artists... Regardless, I took that concept and applied it to movies for this model. The idea is that artists in the movie industry can utilize this model to predict how well a movie will be received by viewers, thus, focusing on IMDb rating as the target, rather than Metacritic’s rating system or Rotten Tomatoes’s Tomatometer.
In its entirety, this project explored a few critical skills required of a data scientist:
Web scraping (requests, HTML, Beautiful Soup)
EDA (pandas, numpy)
Linear regression (scikit-learn)
Data visualization (seaborn, matplotlib)
Step 1: Data acquisition & cleaning 🔍
As a quick note, IMDb has an API available to download bulk data, but a primary requirement for this project was to obtain data through web scraping; so, I went along and got the information from IMDb using requests and Beautiful Soup. Requests is the module required to take the webpage and turn it into an object in python. Beautiful Soup takes that object, which is the HTML information behind the webpage, and makes searching and accessing specific information within the HTML text easy. You really need both in order to fully complete the process of web scraping.
On the IMDb page, I used the advanced search feature to access titles between 2000 and 2020. The results spanned thousands of pages and each page held the titles and links to 100 movies. Upon further inspection, I noticed the URL contained the phrase: ‘start=1’. Increasing this start number by 100 would flip through each page. With a helper function, I used requests and Beautiful Soup to pull the links for each page and returned a list of those links.
To utilize that list of movie hyperlinks, I created another function to extract as much data as I could from each page. This function took in a link and returned a dictionary containing the following information: title, IMDb rating, the number of IMDb raters, MPAA rating, genres, directors, writers, top three stars, initial country of the release, original language of the release, release date, budget, opening weekend USA, gross USA, cumulative worldwide gross, production companies, and runtime.
As part of the EDA, some data had to be cleaned. This consisted of turning any numerical value from a string into an integer. Runtime had to be converted into minutes, all of the monetary values needed commas and dollar signs removed, and the release date had to be converted into datetime. Additionally, categories that contained lists needed to be converted from strings into actual python lists (genres, directors, stars, production companies). The retrieval function did most of this cleaning, but after putting the data into a DataFrame, some other cleaning was necessary.
With over 2,000 movies in a DataFrame, I needed to do some more processing to get a functional DataFrame for modeling. This meant dropping movies without information on budget, movies with a budget below $1,000, and movies with a sum of raters under 1,500. In regards to that last requirement, movies with a low number of raters proved to report the more extreme movie ratings (movies leaning towards a perfect 10 or a big goose egg). All in all, I ended up with a DataFrame consisting of over 1,100 movies. Now it’s time to start modeling.
Pairplots: Before moving on to the next section, I’d like to mention pairplots. Pairplots is a great visualization tool for exploring relationships within the data and informing where to start for an MVP. It seems like a lot of information, but when you format your DataFrame with the first or last column being the target, it is a lot easier to interpret all of this information. For this pairplot, the plots in the first column show relationships between the independent variables and the target. Although I did not use most of the numerical data, it is obvious that there are linear and exponential relationships, which can easily inform where to start modeling.
sns.pairplot(movies_df_drop, height=1.2, aspect=1.25)
Step 2: Models and features 📈
It is important to note that another requirement for this project was the use of linear regression, so the models I experimented with were linear regressions and ridge regressions. With such a large number of features available and having this as my first experience with regression in python, it took me a bit of time to sort out each feature.
First, I decided to take the easy route by conducting a simple linear regression with runtime as my sole feature and IMDb rating as the target. This resulted in an R2 value of 0.2687. Honestly, I was fairly excited to get any number above zero, so I was ready to dive in to the rest of the data.
For MPAA rating and genre, I created dummy variables to add to the DataFrame and got an R2 of 0.3997. As for directors, writers, stars, and production company, I created a list of the most frequently occurring players in each of those categories and created dummy variables for the top contenders. If a director only appeared once in my data, then that director’s weight (or coefficient) would be a direct result of that specific film’s rating, so having players with multiple rows of data would give the model more information to create a better informed coefficient.
To get a little more creative, I took the release date and made a ‘release month’ feature. In the same vein, I took the release date and created another feature that determined the years since the movie was released. It may not have been the most relevant feature, but I was excited to experiment with datetime information.
Having loaded the features into a model, a resulting R2 of 0.4751 seemed promising, but the next step was to rigorously test the model with cross validation.
Step 3: Testing and training / the results 🎥
Although linear regression was getting the job done, I knew I wanted to compare the coefficients of the model, and using a ridge regression was a great way to force myself to scale the inputs and try a different approach to creating a model.
For this section, I would recommend taking a look at the project repository to see the process behind training and testing models, but I’ll just jump to the final model and the results.
The final model resulted in an R2 of 0.432 and a mean absolute error of 0.64. This is a fairly low R2, but this article describes why an R2 below 0.5 for predicting human behavior is expected. Additionally, the plot to the left of predicted ratings vs. actual ratings provided more confidence in the model, as there is some sort of linear relationship between the two. Also, the movies with highest residuals had either a low number of ratings, or were movies like Cats, Fifty Shades of Grey, and The Emoji Movie. These particular movies have good stats behind them, but the public just did not receive them well, which is a hard metric to incorporate into this model.
It’s also important to look at the coefficients associated with each feature. As seen in the plot on the left, runtime, years since release, and budget were all big players in the model, with some genres and writers being up there as well. That’s the beauty of the ridge regression: being able to use the coefficients to determine the weight of a specific feature.
In the end, I had a model that predicted IMDb rating with an R2 of 0.432, significantly better than just predicting with the mean, and an MSE of 0.64, which means the prediction was liable to be wrong by 0.64 points in either direction.
Summary: 📘
Not only was this my first time scraping the web for data, but it was also my first time creating a model, let alone a linear regression model. And with all things considered, I’m fairly proud of this model. Also, the experience of individually traversing the data science workflow was very rewarding; I:
Created my own dataset through scraping the web for information
Explored the dataset and cleaned up anything that was off
Developed an MVP to have a working model at any given moment
Iteratively improved that model to get a better product with each feature
Visualized the validity of my model and what contributed to the rating of a movie
Within three weeks of the bootcamp, I became comfortable with web scraping, EDA, linear regression modeling, and data visualization. Once again, for a more code-heavy explanation of my process, check out my GitHub repository, and feel free to reach out if you have any questions or comments.
I am really looking forward to learning more techniques and skills while at Metis, so check back for updates if you are interested in my data science journey.
Feel free to reach out:LinkedIn | Twitter
|
[
{
"code": null,
"e": 709,
"s": 172,
"text": "My name is Joe Cowell and I recently enrolled in the Metis Data Science Bootcamp. The 12-week immersive program will turn me from ‘data novice’ into a full-fledged data scientist. I mean, the title of this post includes ‘Supervised Machine Learning’ and I’ve only been in the program for three weeks, so it seems like Metis is holding up their end of the bargain. Anyway, I’ll try to make a post about who I am for those interested, but for now, let’s take a look at how I used supervised machine learning to predict IMDb movie ratings."
},
{
"code": null,
"e": 721,
"s": 709,
"text": "Background:"
},
{
"code": null,
"e": 1222,
"s": 721,
"text": "During my musical career, the question was always, “how good is this song?” and never, “how much money will this song make?” Maybe that’s why we were your typical starving artists... Regardless, I took that concept and applied it to movies for this model. The idea is that artists in the movie industry can utilize this model to predict how well a movie will be received by viewers, thus, focusing on IMDb rating as the target, rather than Metacritic’s rating system or Rotten Tomatoes’s Tomatometer."
},
{
"code": null,
"e": 1313,
"s": 1222,
"text": "In its entirety, this project explored a few critical skills required of a data scientist:"
},
{
"code": null,
"e": 1359,
"s": 1313,
"text": "Web scraping (requests, HTML, Beautiful Soup)"
},
{
"code": null,
"e": 1379,
"s": 1359,
"text": "EDA (pandas, numpy)"
},
{
"code": null,
"e": 1412,
"s": 1379,
"text": "Linear regression (scikit-learn)"
},
{
"code": null,
"e": 1453,
"s": 1412,
"text": "Data visualization (seaborn, matplotlib)"
},
{
"code": null,
"e": 1491,
"s": 1453,
"text": "Step 1: Data acquisition & cleaning 🔍"
},
{
"code": null,
"e": 2060,
"s": 1491,
"text": "As a quick note, IMDb has an API available to download bulk data, but a primary requirement for this project was to obtain data through web scraping; so, I went along and got the information from IMDb using requests and Beautiful Soup. Requests is the module required to take the webpage and turn it into an object in python. Beautiful Soup takes that object, which is the HTML information behind the webpage, and makes searching and accessing specific information within the HTML text easy. You really need both in order to fully complete the process of web scraping."
},
{
"code": null,
"e": 2516,
"s": 2060,
"text": "On the IMDb page, I used the advanced search feature to access titles between 2000 and 2020. The results spanned thousands of pages and each page held the titles and links to 100 movies. Upon further inspection, I noticed the URL contained the phrase: ‘start=1’. Increasing this start number by 100 would flip through each page. With a helper function, I used requests and Beautiful Soup to pull the links for each page and returned a list of those links."
},
{
"code": null,
"e": 3017,
"s": 2516,
"text": "To utilize that list of movie hyperlinks, I created another function to extract as much data as I could from each page. This function took in a link and returned a dictionary containing the following information: title, IMDb rating, the number of IMDb raters, MPAA rating, genres, directors, writers, top three stars, initial country of the release, original language of the release, release date, budget, opening weekend USA, gross USA, cumulative worldwide gross, production companies, and runtime."
},
{
"code": null,
"e": 3595,
"s": 3017,
"text": "As part of the EDA, some data had to be cleaned. This consisted of turning any numerical value from a string into an integer. Runtime had to be converted into minutes, all of the monetary values needed commas and dollar signs removed, and the release date had to be converted into datetime. Additionally, categories that contained lists needed to be converted from strings into actual python lists (genres, directors, stars, production companies). The retrieval function did most of this cleaning, but after putting the data into a DataFrame, some other cleaning was necessary."
},
{
"code": null,
"e": 4136,
"s": 3595,
"text": "With over 2,000 movies in a DataFrame, I needed to do some more processing to get a functional DataFrame for modeling. This meant dropping movies without information on budget, movies with a budget below $1,000, and movies with a sum of raters under 1,500. In regards to that last requirement, movies with a low number of raters proved to report the more extreme movie ratings (movies leaning towards a perfect 10 or a big goose egg). All in all, I ended up with a DataFrame consisting of over 1,100 movies. Now it’s time to start modeling."
},
{
"code": null,
"e": 4802,
"s": 4136,
"text": "Pairplots: Before moving on to the next section, I’d like to mention pairplots. Pairplots is a great visualization tool for exploring relationships within the data and informing where to start for an MVP. It seems like a lot of information, but when you format your DataFrame with the first or last column being the target, it is a lot easier to interpret all of this information. For this pairplot, the plots in the first column show relationships between the independent variables and the target. Although I did not use most of the numerical data, it is obvious that there are linear and exponential relationships, which can easily inform where to start modeling."
},
{
"code": null,
"e": 4856,
"s": 4802,
"text": "sns.pairplot(movies_df_drop, height=1.2, aspect=1.25)"
},
{
"code": null,
"e": 4886,
"s": 4856,
"text": "Step 2: Models and features 📈"
},
{
"code": null,
"e": 5231,
"s": 4886,
"text": "It is important to note that another requirement for this project was the use of linear regression, so the models I experimented with were linear regressions and ridge regressions. With such a large number of features available and having this as my first experience with regression in python, it took me a bit of time to sort out each feature."
},
{
"code": null,
"e": 5527,
"s": 5231,
"text": "First, I decided to take the easy route by conducting a simple linear regression with runtime as my sole feature and IMDb rating as the target. This resulted in an R2 value of 0.2687. Honestly, I was fairly excited to get any number above zero, so I was ready to dive in to the rest of the data."
},
{
"code": null,
"e": 6096,
"s": 5527,
"text": "For MPAA rating and genre, I created dummy variables to add to the DataFrame and got an R2 of 0.3997. As for directors, writers, stars, and production company, I created a list of the most frequently occurring players in each of those categories and created dummy variables for the top contenders. If a director only appeared once in my data, then that director’s weight (or coefficient) would be a direct result of that specific film’s rating, so having players with multiple rows of data would give the model more information to create a better informed coefficient."
},
{
"code": null,
"e": 6420,
"s": 6096,
"text": "To get a little more creative, I took the release date and made a ‘release month’ feature. In the same vein, I took the release date and created another feature that determined the years since the movie was released. It may not have been the most relevant feature, but I was excited to experiment with datetime information."
},
{
"code": null,
"e": 6578,
"s": 6420,
"text": "Having loaded the features into a model, a resulting R2 of 0.4751 seemed promising, but the next step was to rigorously test the model with cross validation."
},
{
"code": null,
"e": 6623,
"s": 6578,
"text": "Step 3: Testing and training / the results 🎥"
},
{
"code": null,
"e": 6865,
"s": 6623,
"text": "Although linear regression was getting the job done, I knew I wanted to compare the coefficients of the model, and using a ridge regression was a great way to force myself to scale the inputs and try a different approach to creating a model."
},
{
"code": null,
"e": 7051,
"s": 6865,
"text": "For this section, I would recommend taking a look at the project repository to see the process behind training and testing models, but I’ll just jump to the final model and the results."
},
{
"code": null,
"e": 7720,
"s": 7051,
"text": "The final model resulted in an R2 of 0.432 and a mean absolute error of 0.64. This is a fairly low R2, but this article describes why an R2 below 0.5 for predicting human behavior is expected. Additionally, the plot to the left of predicted ratings vs. actual ratings provided more confidence in the model, as there is some sort of linear relationship between the two. Also, the movies with highest residuals had either a low number of ratings, or were movies like Cats, Fifty Shades of Grey, and The Emoji Movie. These particular movies have good stats behind them, but the public just did not receive them well, which is a hard metric to incorporate into this model."
},
{
"code": null,
"e": 8085,
"s": 7720,
"text": "It’s also important to look at the coefficients associated with each feature. As seen in the plot on the left, runtime, years since release, and budget were all big players in the model, with some genres and writers being up there as well. That’s the beauty of the ridge regression: being able to use the coefficients to determine the weight of a specific feature."
},
{
"code": null,
"e": 8322,
"s": 8085,
"text": "In the end, I had a model that predicted IMDb rating with an R2 of 0.432, significantly better than just predicting with the mean, and an MSE of 0.64, which means the prediction was liable to be wrong by 0.64 points in either direction."
},
{
"code": null,
"e": 8333,
"s": 8322,
"text": "Summary: 📘"
},
{
"code": null,
"e": 8638,
"s": 8333,
"text": "Not only was this my first time scraping the web for data, but it was also my first time creating a model, let alone a linear regression model. And with all things considered, I’m fairly proud of this model. Also, the experience of individually traversing the data science workflow was very rewarding; I:"
},
{
"code": null,
"e": 8702,
"s": 8638,
"text": "Created my own dataset through scraping the web for information"
},
{
"code": null,
"e": 8760,
"s": 8702,
"text": "Explored the dataset and cleaned up anything that was off"
},
{
"code": null,
"e": 8821,
"s": 8760,
"text": "Developed an MVP to have a working model at any given moment"
},
{
"code": null,
"e": 8895,
"s": 8821,
"text": "Iteratively improved that model to get a better product with each feature"
},
{
"code": null,
"e": 8977,
"s": 8895,
"text": "Visualized the validity of my model and what contributed to the rating of a movie"
},
{
"code": null,
"e": 9269,
"s": 8977,
"text": "Within three weeks of the bootcamp, I became comfortable with web scraping, EDA, linear regression modeling, and data visualization. Once again, for a more code-heavy explanation of my process, check out my GitHub repository, and feel free to reach out if you have any questions or comments."
},
{
"code": null,
"e": 9428,
"s": 9269,
"text": "I am really looking forward to learning more techniques and skills while at Metis, so check back for updates if you are interested in my data science journey."
}
] |
JavaScript - Array unshift() Method
|
Javascript array unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
Its syntax is as follows −
array.unshift( element1, ..., elementN );
element1, ..., elementN − The elements to add to the front of the array.
Returns the length of the new array. It returns undefined in IE browser.
Try the following example.
<html>
<head>
<title>JavaScript Array unshift Method</title>
</head>
<body>
<script type = "text/javascript">
var arr = new Array("orange", "mango", "banana", "sugar");
var length = arr.unshift("water");
document.write("Returned array is : " + arr );
document.write("<br /> Length of the array is : " + length );
</script>
</body>
</html>
Returned array is : water,orange,mango,banana,sugar
Length of the array is : 5
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2596,
"s": 2466,
"text": "Javascript array unshift() method adds one or more elements to the beginning of an array and returns the new length of the array."
},
{
"code": null,
"e": 2623,
"s": 2596,
"text": "Its syntax is as follows −"
},
{
"code": null,
"e": 2666,
"s": 2623,
"text": "array.unshift( element1, ..., elementN );\n"
},
{
"code": null,
"e": 2739,
"s": 2666,
"text": "element1, ..., elementN − The elements to add to the front of the array."
},
{
"code": null,
"e": 2812,
"s": 2739,
"text": "Returns the length of the new array. It returns undefined in IE browser."
},
{
"code": null,
"e": 2839,
"s": 2812,
"text": "Try the following example."
},
{
"code": null,
"e": 3266,
"s": 2839,
"text": "<html>\n <head>\n <title>JavaScript Array unshift Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var arr = new Array(\"orange\", \"mango\", \"banana\", \"sugar\"); \n var length = arr.unshift(\"water\");\n document.write(\"Returned array is : \" + arr );\n document.write(\"<br /> Length of the array is : \" + length );\n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 3347,
"s": 3266,
"text": "Returned array is : water,orange,mango,banana,sugar\nLength of the array is : 5 \n"
},
{
"code": null,
"e": 3382,
"s": 3347,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3396,
"s": 3382,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3430,
"s": 3396,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3444,
"s": 3430,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3479,
"s": 3444,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3496,
"s": 3479,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3531,
"s": 3496,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3548,
"s": 3531,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3581,
"s": 3548,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3609,
"s": 3581,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3643,
"s": 3609,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 3671,
"s": 3643,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3678,
"s": 3671,
"text": " Print"
},
{
"code": null,
"e": 3689,
"s": 3678,
"text": " Add Notes"
}
] |
Explore your activity on Google with R: How to Analyze and Visualize Your Search History | by Saúl Buentello | Towards Data Science
|
Can you imagine a world without the most popular search engine in the world? I bet, dear reader, that if you are between the ages of 18 and 25, touching a dictionary or encyclopedia is not a part of everyday life for you, as it was for many of us in our youth.
Finding answers, knowledge, information (and misinformation), is just a click away nowadays within the reach of anyone. That is why I find it interesting to be able to take a look at how our personal consumption habits have changed, especially if you have a long history since you opened the doors to Google to find out everything about you.
Thanks to Google Takeout, a tool that Google provides to consult your data stored in any of the products that you have used, you can consult your search history. You have to enter the URL https://takeout.google.com/settings/takeout to log in with your personal account.
You can request a complete copy of your data, or by-product, or select only some characteristics of a single product. For us, for purposes of this article, it is sufficient to select “My Activity”.
I also recommend that you make sure to uncheck the rest of the options it contains to only leave the “Search” option, to reduce the weight and delivery time of the file it will generate.
Once this is done, you will have to select “export once” and choose the .zip delivery format.
And voila, now you just have to be patient, waiting for the copy of the content you have selected to be generated.
When your file is generated, you will receive a notification email inviting you to download it, with an expiration date to be able to do so before the specified date, for security reasons.
When you unzip the .zip you downloaded, you will find a file named “MyActivity.html”.
This HTML file contains the complete data of your search history in Google, from when you started using the search engine for the first time, until the moment when you generated this data copy with Google Takeout.
Now you can proceed to work on the information obtained in a new R script. First, you must include all the packages that you will use, and establish the reading of your search history, contained in the file “MyActivity.html” that is inside the “Search” folder, contained in the “My Activity” folder.
# REQUIRED LIBRARIESlibrary(wordcloud)library(lubridate)library(rvest)library(tm)library(tidyverse)# READ DATAfileHTML <- "Takeout/My Activity/Search/MyActivity.html"mySearchFile <- read_html(fileHTML, encoding = "UTF-8")
You will extract the data that interests you and you will do web scrapping of the HTML, using the “rvest” package. In this way, using regular expressions, you can extract the date and time of your searches, the searched text, and the type of search you did on Google, to create a data frame with all this information.
# SCRAPPING SEARCH DATE AND TIMEdateSearch <- mySearchFile %>% html_nodes(xpath = '//div[@class="mdl-grid"]/div/div') %>% str_extract(pattern = "(?<=<br>)(.*)(?<=PM|AM)") %>% mdy_hms()dateSearch[1:5]# SCRAPING SEARCH TEXTtextSearch <- mySearchFile %>% html_nodes(xpath = '//div[@class="mdl-grid"]/div/div') %>% str_extract(pattern = '(?<=<a)(.*)(?=</a>)') %>% str_extract(pattern = '(?<=\">)(.*)')textSearch[1:5]# SCRAPING SEARCH TYPEsearchType <- mySearchFile %>% html_nodes(xpath = '//div[@class="mdl-grid"]/div/div') %>% str_extract(pattern = "(?<=mdl-typography--body-1\">)(.*)(?=<a)") %>% str_extract(pattern = "(\\w+)(?=\\s)")searchType[1:5]# CREATE DATA FRAME USING SCRAPED DATAsearchedData <- tibble(timestamp = dateSearch, date = as_date(dateSearch), year = year(dateSearch), month = month(dateSearch, label = TRUE), day = weekdays(dateSearch), hour = hour(dateSearch), type = searchType, search = textSearch)searchedData$day <- factor(searchedData$day, levels = c("Sunday", "Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday"))searchedData <- na.omit(searchedData)head(searchedData)
As a result, you will get a new data frame with 8 variables.
This could be the first question that you can answer. With the information obtained, you can view the number of searches carried out concerning the years of your history.
# PLOT SEARCHED BY YEARsearchByYear <- ggplot(searchedData, aes(year, fill=..count..)) + scale_fill_gradient(low = "yellow", high = "red")+ geom_bar(width=0.7)+ labs(x= "Year", y= "Count") + ggtitle("How much your search frequency has changed over time", "Search activity by year")searchByYearggplotly()
In my case, for example, my history goes from 2007 to today, in 2020. That is, 13 years of searches are represented in volume as follows. There is a very notable increase, mainly in comparison with years before 2014, in which I continued to use the Yahoo search engine mostly, also it seems to me that it must be taken into consideration that access to increasingly faster and faster Internet connections also facilitated the possibility of making more and more queries to Google.
You can dig a little deeper into the results previously obtained, now visualizing how much the frequency with which you have searched on Google has changed, detailed by months over the years of age that your history has.
# PLOT SEARCH BY MONTHsearchByMonth <- searchedData[(searchedData$year > 2007 & searchedData$year< 2021), ]ggplot(searchByMonth, aes(year, fill=..count..)) + scale_fill_gradient(low = "yellow", high = "red")+ geom_bar(aes(x = month, group = year)) + theme(axis.text.x = element_text(angle=90)) + facet_grid(.~year, scales="free") + labs(x= "Year / Month", y= "Count") + ggtitle("How much your search frequency has changed over time", "Month activity on detail")
I am almost sure, dear reader, that like me, if you look carefully, a lot had to do with the increase in the number of searches carried out concerning the worst months in which the pandemic covid-19 in your country forced you to stay more at home, and therefore with your devices such as phones, tablets, and computers with internet access. For example in my case, I do not think it is a coincidence that the maximum records plotted in 2020 coincide with the red traffic light (closure of all non-essential establishments and remote work from home) established in the country where I live (Mexico).
You can get this information as well since you have a record of the exact time you searched with the popular Google engine.
# PLOT SEARCH BY HOURsearchByHour <- ggplot(searchedData, aes(hour, fill=..count..)) + scale_fill_gradient(low = "yellow", high = "red") + geom_bar() + labs(x= "Hour", y= "Count") + ggtitle("What time of day do you have the highest frequency of searches?", "Hour activity on detail")searchByHour
You will get the following plot as a result, where, for example, in my case, it is notable that I am mostly not a Google user at dawn.
Following the previous example, you can also visualize which days of the week register the highest number of searches performed by you.
# PLOT SEARCH BY WEEKDAYseearchByWeekD <- ggplot(searchedData, aes(day, fill=..count..)) + scale_fill_gradient(low = "yellow", high = "red") + geom_bar() + labs(x= "Day", y= "Count") + ggtitle("What day of the week do you have the highest frequency of searches?", "Weekday activity on detail")seearchByWeekD
It is to be expected that if, like me, you occupy your weekends to get away a little from staying online, to go see your friends, for example, the decrease in search volume will be noticeably visible.
Taking up the last two plots obtained, where you can see the time and day of the week in which you register the most searches in Google, you can create a new plot to see in detail the relationship between the two.
# PLOT SEARCH BY WEEKDAY AND TIME searchWdayTime <- ggplot(searchedData) + scale_fill_gradient(low = "yellow", high = "red")+ geom_bar(aes(x = hour, group = day, fill=..count..) ) + labs(x= "Hour / Day", y= "Count") + ggtitle("Relationship between day / time you have a higher frequency of searches", "Weekday/Time activity on detail") + facet_grid(.~day, scales = "free")searchWdayTime
In this way, you will get a plot like the following. You could also cross data with other variables that you already used such as months and years.
This is another interesting question that you can answer by viewing the data using the “wordcloud” package. First, you will have to extract the terms to later clean them and thus be able to create a Text Corpus. You should also remove words that do not provide relevant information such as articles and pronouns.
# CLEAN AND EXTRACT TEXT TO CREATE A TEXT CORPUSlastTwoYears <- searchedData[(searchedData$year > 2007 & searchedData$year< 2010), ]search <- tolower(lastTwoYears$search)search <- gsub('(http|https)\\S+\\s*|(#|@)\\S+\\s*|\\n|\\"', " ", search)search <- gsub("(.*.)\\.com(.*.)\\S+\\s|[^[:alnum:]]", " ", search)search <- trimws(search)textCorpus <- Corpus(VectorSource(search))textCorpus <- tm_map(textCorpus, content_transformer(removePunctuation))textCorpus <- tm_map(textCorpus, content_transformer(removeNumbers))stopwords <- c(stopwords("english"), "que", "com", "cómo", "como", "para", "con", "qué", "las", "los", "del", "can")textCorpus <- tm_map(textCorpus, removeWords, stopwords)searchTDM <- TermDocumentMatrix(textCorpus)searchMatrix <- as.matrix(searchTDM)
Finally, you can create a new Data Frame to be able to visualize your cloud of most searched terms in Google for the last two years.
# CREATE DATA FRAME WITH WORDSarrange <- sort(rowSums(searchMatrix), decreasing = TRUE)twNames <- names(arrange)dataCloud <- data.frame(word = twNames, freq = arrange)wordcloud(dataCloud$word, dataCloud$freq, min.freq = 40, scale = c(2 , 0.5), max.words = 100, colors=brewer.pal(9, "Paired"))
You should then get your wordcloud with the terms you searched for at least 40 times or more. This is my cloud of most searched terms from 2018 to 2020. Do not judge me for searching so much “torrent” please hehe.
As a bonus, you can repeat the exercise to find out what the most searched terms were during the first two years that you allowed Google to enter your life to know everything about you. You only need to modify the range of years covered in the lastTwoYears variable. In my case, for example, from 2008 to 2010 (years of a lot of Flash and forums where to find answers about web development), this is my wordcloud. Obviously, the search volume was much lower compared to the previously generated wordcloud.
Thank you very much for your kind reading. As with most of my articles, I share the plots generated with plotly in a flexdashboard that I put together a little more aesthetic: https://rpubs.com/cosmoduende/google-search-history-analysis
Here you can find the complete code: https://github.com/cosmoduende/r-google-search-history-analysis
I thank you for making it to the end, I wish you a very happy analysis, that you can put everything into practice, and that you are surprised and have as much fun as I am with the results!
Some rights reserved
|
[
{
"code": null,
"e": 432,
"s": 171,
"text": "Can you imagine a world without the most popular search engine in the world? I bet, dear reader, that if you are between the ages of 18 and 25, touching a dictionary or encyclopedia is not a part of everyday life for you, as it was for many of us in our youth."
},
{
"code": null,
"e": 774,
"s": 432,
"text": "Finding answers, knowledge, information (and misinformation), is just a click away nowadays within the reach of anyone. That is why I find it interesting to be able to take a look at how our personal consumption habits have changed, especially if you have a long history since you opened the doors to Google to find out everything about you."
},
{
"code": null,
"e": 1044,
"s": 774,
"text": "Thanks to Google Takeout, a tool that Google provides to consult your data stored in any of the products that you have used, you can consult your search history. You have to enter the URL https://takeout.google.com/settings/takeout to log in with your personal account."
},
{
"code": null,
"e": 1242,
"s": 1044,
"text": "You can request a complete copy of your data, or by-product, or select only some characteristics of a single product. For us, for purposes of this article, it is sufficient to select “My Activity”."
},
{
"code": null,
"e": 1429,
"s": 1242,
"text": "I also recommend that you make sure to uncheck the rest of the options it contains to only leave the “Search” option, to reduce the weight and delivery time of the file it will generate."
},
{
"code": null,
"e": 1523,
"s": 1429,
"text": "Once this is done, you will have to select “export once” and choose the .zip delivery format."
},
{
"code": null,
"e": 1638,
"s": 1523,
"text": "And voila, now you just have to be patient, waiting for the copy of the content you have selected to be generated."
},
{
"code": null,
"e": 1827,
"s": 1638,
"text": "When your file is generated, you will receive a notification email inviting you to download it, with an expiration date to be able to do so before the specified date, for security reasons."
},
{
"code": null,
"e": 1913,
"s": 1827,
"text": "When you unzip the .zip you downloaded, you will find a file named “MyActivity.html”."
},
{
"code": null,
"e": 2127,
"s": 1913,
"text": "This HTML file contains the complete data of your search history in Google, from when you started using the search engine for the first time, until the moment when you generated this data copy with Google Takeout."
},
{
"code": null,
"e": 2427,
"s": 2127,
"text": "Now you can proceed to work on the information obtained in a new R script. First, you must include all the packages that you will use, and establish the reading of your search history, contained in the file “MyActivity.html” that is inside the “Search” folder, contained in the “My Activity” folder."
},
{
"code": null,
"e": 2649,
"s": 2427,
"text": "# REQUIRED LIBRARIESlibrary(wordcloud)library(lubridate)library(rvest)library(tm)library(tidyverse)# READ DATAfileHTML <- \"Takeout/My Activity/Search/MyActivity.html\"mySearchFile <- read_html(fileHTML, encoding = \"UTF-8\")"
},
{
"code": null,
"e": 2967,
"s": 2649,
"text": "You will extract the data that interests you and you will do web scrapping of the HTML, using the “rvest” package. In this way, using regular expressions, you can extract the date and time of your searches, the searched text, and the type of search you did on Google, to create a data frame with all this information."
},
{
"code": null,
"e": 4237,
"s": 2967,
"text": "# SCRAPPING SEARCH DATE AND TIMEdateSearch <- mySearchFile %>% html_nodes(xpath = '//div[@class=\"mdl-grid\"]/div/div') %>% str_extract(pattern = \"(?<=<br>)(.*)(?<=PM|AM)\") %>% mdy_hms()dateSearch[1:5]# SCRAPING SEARCH TEXTtextSearch <- mySearchFile %>% html_nodes(xpath = '//div[@class=\"mdl-grid\"]/div/div') %>% str_extract(pattern = '(?<=<a)(.*)(?=</a>)') %>% str_extract(pattern = '(?<=\\\">)(.*)')textSearch[1:5]# SCRAPING SEARCH TYPEsearchType <- mySearchFile %>% html_nodes(xpath = '//div[@class=\"mdl-grid\"]/div/div') %>% str_extract(pattern = \"(?<=mdl-typography--body-1\\\">)(.*)(?=<a)\") %>% str_extract(pattern = \"(\\\\w+)(?=\\\\s)\")searchType[1:5]# CREATE DATA FRAME USING SCRAPED DATAsearchedData <- tibble(timestamp = dateSearch, date = as_date(dateSearch), year = year(dateSearch), month = month(dateSearch, label = TRUE), day = weekdays(dateSearch), hour = hour(dateSearch), type = searchType, search = textSearch)searchedData$day <- factor(searchedData$day, levels = c(\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\"Thursday\", \"Friday\", \"Saturday\"))searchedData <- na.omit(searchedData)head(searchedData)"
},
{
"code": null,
"e": 4298,
"s": 4237,
"text": "As a result, you will get a new data frame with 8 variables."
},
{
"code": null,
"e": 4469,
"s": 4298,
"text": "This could be the first question that you can answer. With the information obtained, you can view the number of searches carried out concerning the years of your history."
},
{
"code": null,
"e": 4778,
"s": 4469,
"text": "# PLOT SEARCHED BY YEARsearchByYear <- ggplot(searchedData, aes(year, fill=..count..)) + scale_fill_gradient(low = \"yellow\", high = \"red\")+ geom_bar(width=0.7)+ labs(x= \"Year\", y= \"Count\") + ggtitle(\"How much your search frequency has changed over time\", \"Search activity by year\")searchByYearggplotly()"
},
{
"code": null,
"e": 5259,
"s": 4778,
"text": "In my case, for example, my history goes from 2007 to today, in 2020. That is, 13 years of searches are represented in volume as follows. There is a very notable increase, mainly in comparison with years before 2014, in which I continued to use the Yahoo search engine mostly, also it seems to me that it must be taken into consideration that access to increasingly faster and faster Internet connections also facilitated the possibility of making more and more queries to Google."
},
{
"code": null,
"e": 5480,
"s": 5259,
"text": "You can dig a little deeper into the results previously obtained, now visualizing how much the frequency with which you have searched on Google has changed, detailed by months over the years of age that your history has."
},
{
"code": null,
"e": 5951,
"s": 5480,
"text": "# PLOT SEARCH BY MONTHsearchByMonth <- searchedData[(searchedData$year > 2007 & searchedData$year< 2021), ]ggplot(searchByMonth, aes(year, fill=..count..)) + scale_fill_gradient(low = \"yellow\", high = \"red\")+ geom_bar(aes(x = month, group = year)) + theme(axis.text.x = element_text(angle=90)) + facet_grid(.~year, scales=\"free\") + labs(x= \"Year / Month\", y= \"Count\") + ggtitle(\"How much your search frequency has changed over time\", \"Month activity on detail\")"
},
{
"code": null,
"e": 6550,
"s": 5951,
"text": "I am almost sure, dear reader, that like me, if you look carefully, a lot had to do with the increase in the number of searches carried out concerning the worst months in which the pandemic covid-19 in your country forced you to stay more at home, and therefore with your devices such as phones, tablets, and computers with internet access. For example in my case, I do not think it is a coincidence that the maximum records plotted in 2020 coincide with the red traffic light (closure of all non-essential establishments and remote work from home) established in the country where I live (Mexico)."
},
{
"code": null,
"e": 6674,
"s": 6550,
"text": "You can get this information as well since you have a record of the exact time you searched with the popular Google engine."
},
{
"code": null,
"e": 6976,
"s": 6674,
"text": "# PLOT SEARCH BY HOURsearchByHour <- ggplot(searchedData, aes(hour, fill=..count..)) + scale_fill_gradient(low = \"yellow\", high = \"red\") + geom_bar() + labs(x= \"Hour\", y= \"Count\") + ggtitle(\"What time of day do you have the highest frequency of searches?\", \"Hour activity on detail\")searchByHour"
},
{
"code": null,
"e": 7111,
"s": 6976,
"text": "You will get the following plot as a result, where, for example, in my case, it is notable that I am mostly not a Google user at dawn."
},
{
"code": null,
"e": 7247,
"s": 7111,
"text": "Following the previous example, you can also visualize which days of the week register the highest number of searches performed by you."
},
{
"code": null,
"e": 7561,
"s": 7247,
"text": "# PLOT SEARCH BY WEEKDAYseearchByWeekD <- ggplot(searchedData, aes(day, fill=..count..)) + scale_fill_gradient(low = \"yellow\", high = \"red\") + geom_bar() + labs(x= \"Day\", y= \"Count\") + ggtitle(\"What day of the week do you have the highest frequency of searches?\", \"Weekday activity on detail\")seearchByWeekD"
},
{
"code": null,
"e": 7762,
"s": 7561,
"text": "It is to be expected that if, like me, you occupy your weekends to get away a little from staying online, to go see your friends, for example, the decrease in search volume will be noticeably visible."
},
{
"code": null,
"e": 7976,
"s": 7762,
"text": "Taking up the last two plots obtained, where you can see the time and day of the week in which you register the most searches in Google, you can create a new plot to see in detail the relationship between the two."
},
{
"code": null,
"e": 8370,
"s": 7976,
"text": "# PLOT SEARCH BY WEEKDAY AND TIME searchWdayTime <- ggplot(searchedData) + scale_fill_gradient(low = \"yellow\", high = \"red\")+ geom_bar(aes(x = hour, group = day, fill=..count..) ) + labs(x= \"Hour / Day\", y= \"Count\") + ggtitle(\"Relationship between day / time you have a higher frequency of searches\", \"Weekday/Time activity on detail\") + facet_grid(.~day, scales = \"free\")searchWdayTime"
},
{
"code": null,
"e": 8518,
"s": 8370,
"text": "In this way, you will get a plot like the following. You could also cross data with other variables that you already used such as months and years."
},
{
"code": null,
"e": 8831,
"s": 8518,
"text": "This is another interesting question that you can answer by viewing the data using the “wordcloud” package. First, you will have to extract the terms to later clean them and thus be able to create a Text Corpus. You should also remove words that do not provide relevant information such as articles and pronouns."
},
{
"code": null,
"e": 9602,
"s": 8831,
"text": "# CLEAN AND EXTRACT TEXT TO CREATE A TEXT CORPUSlastTwoYears <- searchedData[(searchedData$year > 2007 & searchedData$year< 2010), ]search <- tolower(lastTwoYears$search)search <- gsub('(http|https)\\\\S+\\\\s*|(#|@)\\\\S+\\\\s*|\\\\n|\\\\\"', \" \", search)search <- gsub(\"(.*.)\\\\.com(.*.)\\\\S+\\\\s|[^[:alnum:]]\", \" \", search)search <- trimws(search)textCorpus <- Corpus(VectorSource(search))textCorpus <- tm_map(textCorpus, content_transformer(removePunctuation))textCorpus <- tm_map(textCorpus, content_transformer(removeNumbers))stopwords <- c(stopwords(\"english\"), \"que\", \"com\", \"cómo\", \"como\", \"para\", \"con\", \"qué\", \"las\", \"los\", \"del\", \"can\")textCorpus <- tm_map(textCorpus, removeWords, stopwords)searchTDM <- TermDocumentMatrix(textCorpus)searchMatrix <- as.matrix(searchTDM)"
},
{
"code": null,
"e": 9735,
"s": 9602,
"text": "Finally, you can create a new Data Frame to be able to visualize your cloud of most searched terms in Google for the last two years."
},
{
"code": null,
"e": 10028,
"s": 9735,
"text": "# CREATE DATA FRAME WITH WORDSarrange <- sort(rowSums(searchMatrix), decreasing = TRUE)twNames <- names(arrange)dataCloud <- data.frame(word = twNames, freq = arrange)wordcloud(dataCloud$word, dataCloud$freq, min.freq = 40, scale = c(2 , 0.5), max.words = 100, colors=brewer.pal(9, \"Paired\"))"
},
{
"code": null,
"e": 10242,
"s": 10028,
"text": "You should then get your wordcloud with the terms you searched for at least 40 times or more. This is my cloud of most searched terms from 2018 to 2020. Do not judge me for searching so much “torrent” please hehe."
},
{
"code": null,
"e": 10748,
"s": 10242,
"text": "As a bonus, you can repeat the exercise to find out what the most searched terms were during the first two years that you allowed Google to enter your life to know everything about you. You only need to modify the range of years covered in the lastTwoYears variable. In my case, for example, from 2008 to 2010 (years of a lot of Flash and forums where to find answers about web development), this is my wordcloud. Obviously, the search volume was much lower compared to the previously generated wordcloud."
},
{
"code": null,
"e": 10985,
"s": 10748,
"text": "Thank you very much for your kind reading. As with most of my articles, I share the plots generated with plotly in a flexdashboard that I put together a little more aesthetic: https://rpubs.com/cosmoduende/google-search-history-analysis"
},
{
"code": null,
"e": 11086,
"s": 10985,
"text": "Here you can find the complete code: https://github.com/cosmoduende/r-google-search-history-analysis"
},
{
"code": null,
"e": 11275,
"s": 11086,
"text": "I thank you for making it to the end, I wish you a very happy analysis, that you can put everything into practice, and that you are surprised and have as much fun as I am with the results!"
}
] |
How to Fix java.lang.UnsupportedClassVersionError in Java? - GeeksforGeeks
|
28 Jan, 2021
The UnsupportedClassVersionError is a sub-class of the LinkageError and thrown by the Java Virtual Machine (JVM). When a class file is read and when major and minor version numbers are not supported, this error is thrown, and especially during the linking phase, this error is thrown
A sample snapshot of UnsupportedClassVersionError
Situations when the error is thrown :
When we tried to compile a program using a higher version of Java and execute it using a JVM of a lower version, this error is thrown. But the reverse case is not true.
Hence, it is important to note the java versions
Get the installed java version :
java –version (In command prompt(windows), we can give)
Check java version
Fixing the program via command line :
In order to overcome the UnsupportedClassVersionError, we can either compile our code for an earlier version of Java or run our code on a newer Java version. It is about our choice of decision only. If a third-party library is used then, it is better to run on a newer java version and if it is for distribution, it is best to compile to an older version.
Using JAVA_HOME Environment Variable :
While doing Java programs, always it is good to set JAVA_HOME and setting that value in path
We can check that in command prompt in the below way also
C:\Windows\system32>echo %JAVA_HOME%
C:\Program Files\Java\jdk-9.0.4
Requirements to run a java program on a new JRE:
Move to the directory and locate the bin directory. For example, if the JRE is in location like
C:\Program Files\Java\jdk-11.0.2, then navigate till C:\Program Files\Java\jdk-11.0.2\bin
Execute the program as
java <filename> // Even we can give filename with full package
Requirements to run a java program on an older JRE :
Example :
C:\Program Files\Java\jdk1.8.0_31\bin\javac <filename along with package>
In order to ensure compatibility, we can point “-bootclasspath” at the rt.jar of the targeted JRE:
javac -bootclasspath "C:\Program Files\Java\jdk1.8.0_31\jre\lib\rt.jar"
\ -source 1.8 -target 1.8 <filename>
[Applicable mainly to JDK 8 and lower]
But in JDK 9, the “–release” parameter was added to replace “-source” and “-target”.
The “–release” option supports targets 6, 7, 8, 9, 10, and 11. As an example, let us use “–release” to target Java 8:
javac --release 8 <filename>
There are many IDEs are available for Java development
Let us see how we can overcome “UnsupportedClassVersionError” in Eclipse
Selecting JRE using Java Build Path->Installed JRE
Java compiler level selection :
Java compiler selection
Maven
We can control the version of Java when we build and package a file in Maven. When using Java 7 or older, we set the source and target for the compiler plugin.
Let’s set the source and target using compiler plugin properties:
–release option added in Java 9
Conclusion :
By setting the environment changes either via command-line way or via IDE way or via Maven way, we can overcome “unsupportedclassversion”.
Java-Exceptions
Picked
Technical Scripter 2020
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
How to remove an element from ArrayList in Java?
Difference between Abstract Class and Interface in Java
|
[
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n28 Jan, 2021"
},
{
"code": null,
"e": 23841,
"s": 23557,
"text": "The UnsupportedClassVersionError is a sub-class of the LinkageError and thrown by the Java Virtual Machine (JVM). When a class file is read and when major and minor version numbers are not supported, this error is thrown, and especially during the linking phase, this error is thrown"
},
{
"code": null,
"e": 23892,
"s": 23841,
"text": "A sample snapshot of UnsupportedClassVersionError "
},
{
"code": null,
"e": 23932,
"s": 23894,
"text": "Situations when the error is thrown :"
},
{
"code": null,
"e": 24101,
"s": 23932,
"text": "When we tried to compile a program using a higher version of Java and execute it using a JVM of a lower version, this error is thrown. But the reverse case is not true."
},
{
"code": null,
"e": 24151,
"s": 24101,
"text": "Hence, it is important to note the java versions "
},
{
"code": null,
"e": 24186,
"s": 24153,
"text": "Get the installed java version :"
},
{
"code": null,
"e": 24243,
"s": 24186,
"text": "java –version (In command prompt(windows), we can give)"
},
{
"code": null,
"e": 24262,
"s": 24243,
"text": "Check java version"
},
{
"code": null,
"e": 24302,
"s": 24264,
"text": "Fixing the program via command line :"
},
{
"code": null,
"e": 24658,
"s": 24302,
"text": "In order to overcome the UnsupportedClassVersionError, we can either compile our code for an earlier version of Java or run our code on a newer Java version. It is about our choice of decision only. If a third-party library is used then, it is better to run on a newer java version and if it is for distribution, it is best to compile to an older version."
},
{
"code": null,
"e": 24699,
"s": 24660,
"text": "Using JAVA_HOME Environment Variable :"
},
{
"code": null,
"e": 24792,
"s": 24699,
"text": "While doing Java programs, always it is good to set JAVA_HOME and setting that value in path"
},
{
"code": null,
"e": 24850,
"s": 24792,
"text": "We can check that in command prompt in the below way also"
},
{
"code": null,
"e": 24919,
"s": 24850,
"text": "C:\\Windows\\system32>echo %JAVA_HOME%\nC:\\Program Files\\Java\\jdk-9.0.4"
},
{
"code": null,
"e": 24970,
"s": 24921,
"text": "Requirements to run a java program on a new JRE:"
},
{
"code": null,
"e": 25066,
"s": 24970,
"text": "Move to the directory and locate the bin directory. For example, if the JRE is in location like"
},
{
"code": null,
"e": 25156,
"s": 25066,
"text": "C:\\Program Files\\Java\\jdk-11.0.2, then navigate till C:\\Program Files\\Java\\jdk-11.0.2\\bin"
},
{
"code": null,
"e": 25179,
"s": 25156,
"text": "Execute the program as"
},
{
"code": null,
"e": 25244,
"s": 25179,
"text": "java <filename> // Even we can give filename with full package"
},
{
"code": null,
"e": 25299,
"s": 25246,
"text": "Requirements to run a java program on an older JRE :"
},
{
"code": null,
"e": 25310,
"s": 25299,
"text": "Example : "
},
{
"code": null,
"e": 25384,
"s": 25310,
"text": "C:\\Program Files\\Java\\jdk1.8.0_31\\bin\\javac <filename along with package>"
},
{
"code": null,
"e": 25483,
"s": 25384,
"text": "In order to ensure compatibility, we can point “-bootclasspath” at the rt.jar of the targeted JRE:"
},
{
"code": null,
"e": 25593,
"s": 25483,
"text": "javac -bootclasspath \"C:\\Program Files\\Java\\jdk1.8.0_31\\jre\\lib\\rt.jar\" \n\\ -source 1.8 -target 1.8 <filename>"
},
{
"code": null,
"e": 25632,
"s": 25593,
"text": "[Applicable mainly to JDK 8 and lower]"
},
{
"code": null,
"e": 25718,
"s": 25632,
"text": "But in JDK 9, the “–release” parameter was added to replace “-source” and “-target”. "
},
{
"code": null,
"e": 25836,
"s": 25718,
"text": "The “–release” option supports targets 6, 7, 8, 9, 10, and 11. As an example, let us use “–release” to target Java 8:"
},
{
"code": null,
"e": 25865,
"s": 25836,
"text": "javac --release 8 <filename>"
},
{
"code": null,
"e": 25920,
"s": 25865,
"text": "There are many IDEs are available for Java development"
},
{
"code": null,
"e": 25993,
"s": 25920,
"text": "Let us see how we can overcome “UnsupportedClassVersionError” in Eclipse"
},
{
"code": null,
"e": 26044,
"s": 25993,
"text": "Selecting JRE using Java Build Path->Installed JRE"
},
{
"code": null,
"e": 26076,
"s": 26044,
"text": "Java compiler level selection :"
},
{
"code": null,
"e": 26100,
"s": 26076,
"text": "Java compiler selection"
},
{
"code": null,
"e": 26106,
"s": 26100,
"text": "Maven"
},
{
"code": null,
"e": 26266,
"s": 26106,
"text": "We can control the version of Java when we build and package a file in Maven. When using Java 7 or older, we set the source and target for the compiler plugin."
},
{
"code": null,
"e": 26332,
"s": 26266,
"text": "Let’s set the source and target using compiler plugin properties:"
},
{
"code": null,
"e": 26364,
"s": 26332,
"text": "–release option added in Java 9"
},
{
"code": null,
"e": 26377,
"s": 26364,
"text": "Conclusion :"
},
{
"code": null,
"e": 26516,
"s": 26377,
"text": "By setting the environment changes either via command-line way or via IDE way or via Maven way, we can overcome “unsupportedclassversion”."
},
{
"code": null,
"e": 26532,
"s": 26516,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 26539,
"s": 26532,
"text": "Picked"
},
{
"code": null,
"e": 26563,
"s": 26539,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 26568,
"s": 26563,
"text": "Java"
},
{
"code": null,
"e": 26587,
"s": 26568,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26592,
"s": 26587,
"text": "Java"
},
{
"code": null,
"e": 26690,
"s": 26592,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26699,
"s": 26690,
"text": "Comments"
},
{
"code": null,
"e": 26712,
"s": 26699,
"text": "Old Comments"
},
{
"code": null,
"e": 26742,
"s": 26712,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26757,
"s": 26742,
"text": "Stream In Java"
},
{
"code": null,
"e": 26778,
"s": 26757,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26824,
"s": 26778,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26843,
"s": 26824,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26860,
"s": 26843,
"text": "Generics in Java"
},
{
"code": null,
"e": 26903,
"s": 26860,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26919,
"s": 26903,
"text": "Strings in Java"
},
{
"code": null,
"e": 26968,
"s": 26919,
"text": "How to remove an element from ArrayList in Java?"
}
] |
How to Find the Power of a Number Using Recursion in Python?
|
Following program accepts a number and index from user. The recursive funcion rpower() uses these two as arguments. The function multiplies the number repeatedly and recursively to return power.
def rpower(num,idx):
if(idx==1):
return(num)
else:
return(num*rpower(num,idx-1))
base=int(input("Enter number: "))
exp=int(input("Enter index: "))
rpow=rpower(base,exp)
print("{} raised to {}: {}".format(base,exp,rpow))
Here is a sample run −
Enter number: 10
Enter index: 3
10 raised to 3: 1000
|
[
{
"code": null,
"e": 1257,
"s": 1062,
"text": "Following program accepts a number and index from user. The recursive funcion rpower() uses these two as arguments. The function multiplies the number repeatedly and recursively to return power."
},
{
"code": null,
"e": 1499,
"s": 1257,
"text": "def rpower(num,idx):\n if(idx==1):\n return(num)\n else:\n return(num*rpower(num,idx-1))\nbase=int(input(\"Enter number: \"))\nexp=int(input(\"Enter index: \"))\nrpow=rpower(base,exp)\nprint(\"{} raised to {}: {}\".format(base,exp,rpow))"
},
{
"code": null,
"e": 1522,
"s": 1499,
"text": "Here is a sample run −"
},
{
"code": null,
"e": 1575,
"s": 1522,
"text": "Enter number: 10\nEnter index: 3\n10 raised to 3: 1000"
}
] |
Aptitude - Time & Work Online Quiz
|
Following quiz provides Multiple Choice Questions (MCQs) related to Simple Interest. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz.
Q 1 - A does 20% less work than B. In the event that A can finish a bit of work in 15/2 hours, then B can do it in
A - 5 hours
B - 11/2 hours
C - 6 hours
D - 13/2 hours
Suppose in a given time B completes the whole work.
Then, in that time A does 80/100 work i.e. 4/5 work
Ratio of work done by A and B = inverse ratio of time taken by A and B.
Suppose B do the work in x hrs .Then, 4/5:1=2/15:1/x⇒4:5=2x: 15
⇒ (5*2x) = (4*15) ⇒10x =60⇒x=6.
Time taken by B to finish the work=6hrs.
Q 2 - A and B can finish a bit of work in 8 days while B and C together can do it in 12 days . All the three can together finish in 6 days. In the amount of the truth will surface eventually and C together finish the work?
A - 8 days
B - 10 days
C - 12 days
D - 20 days
(A+B) 1 day work=1/8, (B+C) 1 day work=1/12.
Suppose (A+C) can finish it in x day. Then, (A+C) 1 day work=1/.
2(A+B+C) 1days work = (1/8+1/12+1/x)
⇒ (2*1/6) = (1/8+1/12+1/x) =5/24+1/x
⇒1/x = (1/3-5/24)3/24=1/8⇒x=8.
∴A and C can finish the work in 8 days.
Q 3 - A can do 1/3 of a work in 5 days and B can do 2/5 of the work in 10 days. In how long both A and B together can take the necessary steps?
A - 31/4 days
B - 44/5 days
C - 75/8 days
D - 10 days
1/3 work is done by A in 5 days.
Whole work will be done by A in 15 days.
2/5 work is done by B in 10 days.
Whole work will be done by B in (10*5/2) day?s i.e 25 days
(A+B) 's 1 days work = (1/15+1/25) = 8/75
∴A and B can do the work in 75/8 days
Q 4 - A can make a sure showing in 25 days which B alone can do in 20 days. A began the work and was joined by B following 10 days. The work went on for
A - 25/2 days
B - 128/9 days
C - 15 days
D - 50/3 days
A's 10 days work = (1/25*10)= 2/5 ; remaining work = (1-2/5) = 3/5
(A+B)'s 1 day work = (1/25+1/20) = 9/100
9/100 work is finished by (A+B) In 1 day.
3/5 work is finished by (A+B) in (100/9* 3/5) days = 20/3 days
Total time taken = (10+ 20/3) = 50/3 days
Q 5 - A man and a kid finish a work together in 24 days. On the off chance that throughout the previous 6 days man alone takes every necessary step then it is finished in 26 days. To what extent the kid will take to complete the work done?
A - 72 days
B - 20 days
C - 24 days
D - 36 days
Work done by (man + boy ) in 20 days = (1/24*20)= 5/6
Remaining work = (1-5/6) = 1/6
1/6 work is done by boy in 6 days.
Whole work will be done by the boy in (6*6) = 36 days
Q 6 - A men, a ladies and a kid can together finish a bit of work in 3 days. In the event that a men alone can do it in 6 days and a kid alone in 18 days, to what extent will a ladies take to finish the work?
A - 9 days
B - 21 days
C - 24 days
D - 27 days
(1 man+ 1 women +1 boy ) 1 day work = 1/3
Suppose the women alone can do it in x days. Then
1/6 +1/x+1/18= 1/3 ⇒4/18 +1/x = 1/3 ⇒1/x = (1/3- 2/9) = 1/9
So, 1 woman can do the work in 9 days
Q 7 - If 5 men or 9 ladies can complete a bit of work in 19 days, 3 men and 6 ladies will do likewise work in
A - 10 days
B - 12 days
C - 13 days
D - 15 days
5 men 1 day work = 1/19 ⇒ 1 man's 1 day work = 1/95
9 women 1 day work = 1/19 ⇒1 women 1 day work = 1/171
(3 men + 6 women) 1 day work = (3/95 + 6/171) = (27+30)/855 = 57/ 855 = 1/15
∴ 3 men and 6 women can finish the work in 15 days.
Q 8 - A and B attempted to do a bit of work for rs .4500. An alone could do it in 8 days and B alone in 12 days. With the help of C, they completed the work in 4 days. C's offer of cash is:
A - 375
B - 750
C - 1500
D - 2250
A's 1 day work = 1/8 ,B's 1 day work = 1/12
(A+B+C) 's 1 days work = 1/4
C 's 1 day work = 1/4 - (1/8+ 1/12) = (1/4 -5/24) = 1/24
A: B: C = 1/8: 1/12: 1/24 = 3:2:1
C's share = (4500* 1/6) = Rs. 750
Q 9 - Two man embrace to do a bit of work for Rs. 4000. One alone can do it in 6 days, the other in 8 days. With the assistance of a kid, they complete it in 3 days. The young men offer is:
A - 400
B - 500
C - 600
D - 800
Let the men be A and B and the boy be C.
A's 1 days work = 1/6, B's 1 day work = 1/8. (A+B+C)'s 1 day work = 1/3
1/6 + 1/8 +1/x = 1/3 ⇒1/x = (1/3- 7/24) = 1/24
Ratio of shares of A, B, C = 1/6: 1/8: 1/24 = 4:3:1
Boys share = (4000*1/8) = RS. 500
Q 10 - A works twice as quick as B. On the off chance that the two can together complete a bit of work in 12 days, then B alone can do it in
A - 24 days
B - 27 days
C - 36 days
D - 48 days
Let B 1 day work =x. Then , A 1 days work=2x
X+2x=1/12⇒3x=1/12⇒x=1/36.
B 1 day work=1/36.
Hence B alone can finish the work in 36 days.
87 Lectures
22.5 hours
Programming Line
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 4221,
"s": 3892,
"text": "Following quiz provides Multiple Choice Questions (MCQs) related to Simple Interest. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz."
},
{
"code": null,
"e": 4336,
"s": 4221,
"text": "Q 1 - A does 20% less work than B. In the event that A can finish a bit of work in 15/2 hours, then B can do it in"
},
{
"code": null,
"e": 4348,
"s": 4336,
"text": "A - 5 hours"
},
{
"code": null,
"e": 4363,
"s": 4348,
"text": "B - 11/2 hours"
},
{
"code": null,
"e": 4375,
"s": 4363,
"text": "C - 6 hours"
},
{
"code": null,
"e": 4390,
"s": 4375,
"text": "D - 13/2 hours"
},
{
"code": null,
"e": 4703,
"s": 4390,
"text": "Suppose in a given time B completes the whole work.\nThen, in that time A does 80/100 work i.e. 4/5 work\nRatio of work done by A and B = inverse ratio of time taken by A and B.\nSuppose B do the work in x hrs .Then, 4/5:1=2/15:1/x⇒4:5=2x: 15\n⇒ (5*2x) = (4*15) ⇒10x =60⇒x=6.\nTime taken by B to finish the work=6hrs."
},
{
"code": null,
"e": 4926,
"s": 4703,
"text": "Q 2 - A and B can finish a bit of work in 8 days while B and C together can do it in 12 days . All the three can together finish in 6 days. In the amount of the truth will surface eventually and C together finish the work?"
},
{
"code": null,
"e": 4937,
"s": 4926,
"text": "A - 8 days"
},
{
"code": null,
"e": 4949,
"s": 4937,
"text": "B - 10 days"
},
{
"code": null,
"e": 4961,
"s": 4949,
"text": "C - 12 days"
},
{
"code": null,
"e": 4973,
"s": 4961,
"text": "D - 20 days"
},
{
"code": null,
"e": 5228,
"s": 4973,
"text": "(A+B) 1 day work=1/8, (B+C) 1 day work=1/12.\nSuppose (A+C) can finish it in x day. Then, (A+C) 1 day work=1/.\n2(A+B+C) 1days work = (1/8+1/12+1/x)\n⇒ (2*1/6) = (1/8+1/12+1/x) =5/24+1/x\n⇒1/x = (1/3-5/24)3/24=1/8⇒x=8.\n∴A and C can finish the work in 8 days."
},
{
"code": null,
"e": 5372,
"s": 5228,
"text": "Q 3 - A can do 1/3 of a work in 5 days and B can do 2/5 of the work in 10 days. In how long both A and B together can take the necessary steps?"
},
{
"code": null,
"e": 5387,
"s": 5372,
"text": "A - 31/4 days "
},
{
"code": null,
"e": 5401,
"s": 5387,
"text": "B - 44/5 days"
},
{
"code": null,
"e": 5415,
"s": 5401,
"text": "C - 75/8 days"
},
{
"code": null,
"e": 5427,
"s": 5415,
"text": "D - 10 days"
},
{
"code": null,
"e": 5674,
"s": 5427,
"text": "1/3 work is done by A in 5 days.\nWhole work will be done by A in 15 days.\n2/5 work is done by B in 10 days.\nWhole work will be done by B in (10*5/2) day?s i.e 25 days\n(A+B) 's 1 days work = (1/15+1/25) = 8/75\n∴A and B can do the work in 75/8 days"
},
{
"code": null,
"e": 5827,
"s": 5674,
"text": "Q 4 - A can make a sure showing in 25 days which B alone can do in 20 days. A began the work and was joined by B following 10 days. The work went on for"
},
{
"code": null,
"e": 5841,
"s": 5827,
"text": "A - 25/2 days"
},
{
"code": null,
"e": 5856,
"s": 5841,
"text": "B - 128/9 days"
},
{
"code": null,
"e": 5868,
"s": 5856,
"text": "C - 15 days"
},
{
"code": null,
"e": 5882,
"s": 5868,
"text": "D - 50/3 days"
},
{
"code": null,
"e": 6137,
"s": 5882,
"text": "A's 10 days work = (1/25*10)= 2/5 ; remaining work = (1-2/5) = 3/5\n(A+B)'s 1 day work = (1/25+1/20) = 9/100\n9/100 work is finished by (A+B) In 1 day.\n3/5 work is finished by (A+B) in (100/9* 3/5) days = 20/3 days\nTotal time taken = (10+ 20/3) = 50/3 days"
},
{
"code": null,
"e": 6377,
"s": 6137,
"text": "Q 5 - A man and a kid finish a work together in 24 days. On the off chance that throughout the previous 6 days man alone takes every necessary step then it is finished in 26 days. To what extent the kid will take to complete the work done?"
},
{
"code": null,
"e": 6389,
"s": 6377,
"text": "A - 72 days"
},
{
"code": null,
"e": 6401,
"s": 6389,
"text": "B - 20 days"
},
{
"code": null,
"e": 6413,
"s": 6401,
"text": "C - 24 days"
},
{
"code": null,
"e": 6425,
"s": 6413,
"text": "D - 36 days"
},
{
"code": null,
"e": 6614,
"s": 6425,
"text": "Work done by (man + boy ) in 20 days = (1/24*20)= 5/6\n Remaining work = (1-5/6) = 1/6\n1/6 work is done by boy in 6 days.\nWhole work will be done by the boy in (6*6) = 36 days"
},
{
"code": null,
"e": 6824,
"s": 6614,
"text": "Q 6 - A men, a ladies and a kid can together finish a bit of work in 3 days. In the event that a men alone can do it in 6 days and a kid alone in 18 days, to what extent will a ladies take to finish the work? "
},
{
"code": null,
"e": 6835,
"s": 6824,
"text": "A - 9 days"
},
{
"code": null,
"e": 6847,
"s": 6835,
"text": "B - 21 days"
},
{
"code": null,
"e": 6859,
"s": 6847,
"text": "C - 24 days"
},
{
"code": null,
"e": 6871,
"s": 6859,
"text": "D - 27 days"
},
{
"code": null,
"e": 7061,
"s": 6871,
"text": "(1 man+ 1 women +1 boy ) 1 day work = 1/3\nSuppose the women alone can do it in x days. Then\n1/6 +1/x+1/18= 1/3 ⇒4/18 +1/x = 1/3 ⇒1/x = (1/3- 2/9) = 1/9\nSo, 1 woman can do the work in 9 days"
},
{
"code": null,
"e": 7171,
"s": 7061,
"text": "Q 7 - If 5 men or 9 ladies can complete a bit of work in 19 days, 3 men and 6 ladies will do likewise work in"
},
{
"code": null,
"e": 7183,
"s": 7171,
"text": "A - 10 days"
},
{
"code": null,
"e": 7195,
"s": 7183,
"text": "B - 12 days"
},
{
"code": null,
"e": 7207,
"s": 7195,
"text": "C - 13 days"
},
{
"code": null,
"e": 7220,
"s": 7207,
"text": "D - 15 days "
},
{
"code": null,
"e": 7455,
"s": 7220,
"text": "5 men 1 day work = 1/19 ⇒ 1 man's 1 day work = 1/95\n9 women 1 day work = 1/19 ⇒1 women 1 day work = 1/171\n(3 men + 6 women) 1 day work = (3/95 + 6/171) = (27+30)/855 = 57/ 855 = 1/15\n∴ 3 men and 6 women can finish the work in 15 days."
},
{
"code": null,
"e": 7645,
"s": 7455,
"text": "Q 8 - A and B attempted to do a bit of work for rs .4500. An alone could do it in 8 days and B alone in 12 days. With the help of C, they completed the work in 4 days. C's offer of cash is:"
},
{
"code": null,
"e": 7653,
"s": 7645,
"text": "A - 375"
},
{
"code": null,
"e": 7661,
"s": 7653,
"text": "B - 750"
},
{
"code": null,
"e": 7670,
"s": 7661,
"text": "C - 1500"
},
{
"code": null,
"e": 7679,
"s": 7670,
"text": "D - 2250"
},
{
"code": null,
"e": 7879,
"s": 7679,
"text": "A's 1 day work = 1/8 ,B's 1 day work = 1/12\n(A+B+C) 's 1 days work = 1/4\n C 's 1 day work = 1/4 - (1/8+ 1/12) = (1/4 -5/24) = 1/24\nA: B: C = 1/8: 1/12: 1/24 = 3:2:1\nC's share = (4500* 1/6) = Rs. 750"
},
{
"code": null,
"e": 8069,
"s": 7879,
"text": "Q 9 - Two man embrace to do a bit of work for Rs. 4000. One alone can do it in 6 days, the other in 8 days. With the assistance of a kid, they complete it in 3 days. The young men offer is:"
},
{
"code": null,
"e": 8077,
"s": 8069,
"text": "A - 400"
},
{
"code": null,
"e": 8085,
"s": 8077,
"text": "B - 500"
},
{
"code": null,
"e": 8093,
"s": 8085,
"text": "C - 600"
},
{
"code": null,
"e": 8101,
"s": 8093,
"text": "D - 800"
},
{
"code": null,
"e": 8347,
"s": 8101,
"text": "Let the men be A and B and the boy be C.\nA's 1 days work = 1/6, B's 1 day work = 1/8. (A+B+C)'s 1 day work = 1/3\n1/6 + 1/8 +1/x = 1/3 ⇒1/x = (1/3- 7/24) = 1/24\nRatio of shares of A, B, C = 1/6: 1/8: 1/24 = 4:3:1\nBoys share = (4000*1/8) = RS. 500"
},
{
"code": null,
"e": 8488,
"s": 8347,
"text": "Q 10 - A works twice as quick as B. On the off chance that the two can together complete a bit of work in 12 days, then B alone can do it in"
},
{
"code": null,
"e": 8500,
"s": 8488,
"text": "A - 24 days"
},
{
"code": null,
"e": 8512,
"s": 8500,
"text": "B - 27 days"
},
{
"code": null,
"e": 8524,
"s": 8512,
"text": "C - 36 days"
},
{
"code": null,
"e": 8536,
"s": 8524,
"text": "D - 48 days"
},
{
"code": null,
"e": 8672,
"s": 8536,
"text": "Let B 1 day work =x. Then , A 1 days work=2x\nX+2x=1/12⇒3x=1/12⇒x=1/36.\nB 1 day work=1/36.\nHence B alone can finish the work in 36 days."
},
{
"code": null,
"e": 8708,
"s": 8672,
"text": "\n 87 Lectures \n 22.5 hours \n"
},
{
"code": null,
"e": 8726,
"s": 8708,
"text": " Programming Line"
},
{
"code": null,
"e": 8733,
"s": 8726,
"text": " Print"
},
{
"code": null,
"e": 8744,
"s": 8733,
"text": " Add Notes"
}
] |
Understanding RSA Algorithm
|
RSA algorithm is a public key encryption technique and is considered as the most secure way of encryption. It was invented by Rivest, Shamir and Adleman in year 1978 and hence name RSA algorithm.
The RSA algorithm holds the following features −
RSA algorithm is a popular exponentiation in a finite field over integers including prime numbers.
RSA algorithm is a popular exponentiation in a finite field over integers including prime numbers.
The integers used by this method are sufficiently large making it difficult to solve.
The integers used by this method are sufficiently large making it difficult to solve.
There are two sets of keys in this algorithm: private key and public key.
There are two sets of keys in this algorithm: private key and public key.
You will have to go through the following steps to work on RSA algorithm −
The initial procedure begins with selection of two prime numbers namely p and q, and then calculating their product N, as shown −
N=p*q
Here, let N be the specified large number.
Consider number e as a derived number which should be greater than 1 and less than (p-1) and (q-1). The primary condition will be that there should be no common factor of (p-1) and (q-1) except 1
The specified pair of numbers n and e forms the RSA public key and it is made public.
Private Key d is calculated from the numbers p, q and e. The mathematical relationship between the numbers is as follows −
ed = 1 mod (p-1) (q-1)
The above formula is the basic formula for Extended Euclidean Algorithm, which takes p and q as the input parameters.
Consider a sender who sends the plain text message to someone whose public key is (n,e). To encrypt the plain text message in the given scenario, use the following syntax −
C = Pe mod n
The decryption process is very straightforward and includes analytics for calculation in a systematic approach. Considering receiver C has the private key d, the result modulus will be calculated as −
Plaintext = Cd mod n
10 Lectures
2 hours
Total Seminars
10 Lectures
2 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2488,
"s": 2292,
"text": "RSA algorithm is a public key encryption technique and is considered as the most secure way of encryption. It was invented by Rivest, Shamir and Adleman in year 1978 and hence name RSA algorithm."
},
{
"code": null,
"e": 2537,
"s": 2488,
"text": "The RSA algorithm holds the following features −"
},
{
"code": null,
"e": 2636,
"s": 2537,
"text": "RSA algorithm is a popular exponentiation in a finite field over integers including prime numbers."
},
{
"code": null,
"e": 2735,
"s": 2636,
"text": "RSA algorithm is a popular exponentiation in a finite field over integers including prime numbers."
},
{
"code": null,
"e": 2821,
"s": 2735,
"text": "The integers used by this method are sufficiently large making it difficult to solve."
},
{
"code": null,
"e": 2907,
"s": 2821,
"text": "The integers used by this method are sufficiently large making it difficult to solve."
},
{
"code": null,
"e": 2981,
"s": 2907,
"text": "There are two sets of keys in this algorithm: private key and public key."
},
{
"code": null,
"e": 3055,
"s": 2981,
"text": "There are two sets of keys in this algorithm: private key and public key."
},
{
"code": null,
"e": 3130,
"s": 3055,
"text": "You will have to go through the following steps to work on RSA algorithm −"
},
{
"code": null,
"e": 3260,
"s": 3130,
"text": "The initial procedure begins with selection of two prime numbers namely p and q, and then calculating their product N, as shown −"
},
{
"code": null,
"e": 3267,
"s": 3260,
"text": "N=p*q\n"
},
{
"code": null,
"e": 3310,
"s": 3267,
"text": "Here, let N be the specified large number."
},
{
"code": null,
"e": 3506,
"s": 3310,
"text": "Consider number e as a derived number which should be greater than 1 and less than (p-1) and (q-1). The primary condition will be that there should be no common factor of (p-1) and (q-1) except 1"
},
{
"code": null,
"e": 3592,
"s": 3506,
"text": "The specified pair of numbers n and e forms the RSA public key and it is made public."
},
{
"code": null,
"e": 3715,
"s": 3592,
"text": "Private Key d is calculated from the numbers p, q and e. The mathematical relationship between the numbers is as follows −"
},
{
"code": null,
"e": 3739,
"s": 3715,
"text": "ed = 1 mod (p-1) (q-1)\n"
},
{
"code": null,
"e": 3857,
"s": 3739,
"text": "The above formula is the basic formula for Extended Euclidean Algorithm, which takes p and q as the input parameters."
},
{
"code": null,
"e": 4030,
"s": 3857,
"text": "Consider a sender who sends the plain text message to someone whose public key is (n,e). To encrypt the plain text message in the given scenario, use the following syntax −"
},
{
"code": null,
"e": 4044,
"s": 4030,
"text": "C = Pe mod n\n"
},
{
"code": null,
"e": 4245,
"s": 4044,
"text": "The decryption process is very straightforward and includes analytics for calculation in a systematic approach. Considering receiver C has the private key d, the result modulus will be calculated as −"
},
{
"code": null,
"e": 4267,
"s": 4245,
"text": "Plaintext = Cd mod n\n"
},
{
"code": null,
"e": 4300,
"s": 4267,
"text": "\n 10 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4316,
"s": 4300,
"text": " Total Seminars"
},
{
"code": null,
"e": 4349,
"s": 4316,
"text": "\n 10 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4372,
"s": 4349,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 4379,
"s": 4372,
"text": " Print"
},
{
"code": null,
"e": 4390,
"s": 4379,
"text": " Add Notes"
}
] |
Using CountVectorizer to Extracting Features from Text
|
07 Jul, 2022
CountVectorizer is a great tool provided by the scikit-learn library in Python. It is used to transform a given text into a vector on the basis of the frequency (count) of each word that occurs in the entire text. This is helpful when we have multiple such texts, and we wish to convert each word in each text into vectors (for using in further text analysis). Let us consider a few sample texts from a document (each as a list element):
document = [ “One Geek helps Two Geeks”, “Two Geeks help Four Geeks”, “Each Geek helps many other Geeks at GeeksforGeeks.”]
CountVectorizer creates a matrix in which each unique word is represented by a column of the matrix, and each text sample from the document is a row in the matrix. The value of each cell is nothing but the count of the word in that particular text sample. This can be visualized as follows –
Key Observations:
There are 12 unique words in the document, represented as columns of the table.There are 3 text samples in the document, each represented as rows of the table.Every cell contains a number, that represents the count of the word in that particular text.All words have been converted to lowercase.The words in columns have been arranged alphabetically.
There are 12 unique words in the document, represented as columns of the table.
There are 3 text samples in the document, each represented as rows of the table.
Every cell contains a number, that represents the count of the word in that particular text.
All words have been converted to lowercase.
The words in columns have been arranged alphabetically.
Inside CountVectorizer, these words are not stored as strings. Rather, they are given a particular index value. In this case, ‘at’ would have index 0, ‘each’ would have index 1, ‘four’ would have index 2 and so on. The actual representation has been shown in the table below –
A Sparse Matrix
This way of representation is known as a Sparse Matrix. Code: Python implementation of CountVectorizer
python3
from sklearn.feature_extraction.text import CountVectorizer document = ["One Geek helps Two Geeks", "Two Geeks help Four Geeks", "Each Geek helps many other Geeks at GeeksforGeeks"] # Create a Vectorizer Objectvectorizer = CountVectorizer() vectorizer.fit(document) # Printing the identified Unique words along with their indicesprint("Vocabulary: ", vectorizer.vocabulary_) # Encode the Documentvector = vectorizer.transform(document) # Summarizing the Encoded Textsprint("Encoded Document is:")print(vector.toarray())
Output:
Vocabulary: {'one': 9, 'geek': 3, 'helps': 7, 'two': 11, 'geeks': 4, 'help': 6, 'four': 2, 'each': 1, 'many': 8, 'other': 10, 'at': 0, 'geeksforgeeks': 5}
Encoded Document is:
[ [0 0 0 1 1 0 0 1 0 1 0 1]
[0 0 1 0 2 0 1 0 0 0 0 1]
[1 1 0 1 1 1 0 1 1 0 1 0] ]
mrdedhia
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 491,
"s": 53,
"text": "CountVectorizer is a great tool provided by the scikit-learn library in Python. It is used to transform a given text into a vector on the basis of the frequency (count) of each word that occurs in the entire text. This is helpful when we have multiple such texts, and we wish to convert each word in each text into vectors (for using in further text analysis). Let us consider a few sample texts from a document (each as a list element):"
},
{
"code": null,
"e": 615,
"s": 491,
"text": "document = [ “One Geek helps Two Geeks”, “Two Geeks help Four Geeks”, “Each Geek helps many other Geeks at GeeksforGeeks.”]"
},
{
"code": null,
"e": 908,
"s": 615,
"text": "CountVectorizer creates a matrix in which each unique word is represented by a column of the matrix, and each text sample from the document is a row in the matrix. The value of each cell is nothing but the count of the word in that particular text sample. This can be visualized as follows –"
},
{
"code": null,
"e": 926,
"s": 908,
"text": "Key Observations:"
},
{
"code": null,
"e": 1276,
"s": 926,
"text": "There are 12 unique words in the document, represented as columns of the table.There are 3 text samples in the document, each represented as rows of the table.Every cell contains a number, that represents the count of the word in that particular text.All words have been converted to lowercase.The words in columns have been arranged alphabetically."
},
{
"code": null,
"e": 1356,
"s": 1276,
"text": "There are 12 unique words in the document, represented as columns of the table."
},
{
"code": null,
"e": 1437,
"s": 1356,
"text": "There are 3 text samples in the document, each represented as rows of the table."
},
{
"code": null,
"e": 1530,
"s": 1437,
"text": "Every cell contains a number, that represents the count of the word in that particular text."
},
{
"code": null,
"e": 1574,
"s": 1530,
"text": "All words have been converted to lowercase."
},
{
"code": null,
"e": 1630,
"s": 1574,
"text": "The words in columns have been arranged alphabetically."
},
{
"code": null,
"e": 1907,
"s": 1630,
"text": "Inside CountVectorizer, these words are not stored as strings. Rather, they are given a particular index value. In this case, ‘at’ would have index 0, ‘each’ would have index 1, ‘four’ would have index 2 and so on. The actual representation has been shown in the table below –"
},
{
"code": null,
"e": 1923,
"s": 1907,
"text": "A Sparse Matrix"
},
{
"code": null,
"e": 2027,
"s": 1923,
"text": "This way of representation is known as a Sparse Matrix. Code: Python implementation of CountVectorizer "
},
{
"code": null,
"e": 2035,
"s": 2027,
"text": "python3"
},
{
"code": "from sklearn.feature_extraction.text import CountVectorizer document = [\"One Geek helps Two Geeks\", \"Two Geeks help Four Geeks\", \"Each Geek helps many other Geeks at GeeksforGeeks\"] # Create a Vectorizer Objectvectorizer = CountVectorizer() vectorizer.fit(document) # Printing the identified Unique words along with their indicesprint(\"Vocabulary: \", vectorizer.vocabulary_) # Encode the Documentvector = vectorizer.transform(document) # Summarizing the Encoded Textsprint(\"Encoded Document is:\")print(vector.toarray())",
"e": 2577,
"s": 2035,
"text": null
},
{
"code": null,
"e": 2585,
"s": 2577,
"text": "Output:"
},
{
"code": null,
"e": 2852,
"s": 2585,
"text": "Vocabulary: {'one': 9, 'geek': 3, 'helps': 7, 'two': 11, 'geeks': 4, 'help': 6, 'four': 2, 'each': 1, 'many': 8, 'other': 10, 'at': 0, 'geeksforgeeks': 5}\n\nEncoded Document is:\n\n[ [0 0 0 1 1 0 0 1 0 1 0 1]\n\n [0 0 1 0 2 0 1 0 0 0 0 1]\n\n [1 1 0 1 1 1 0 1 1 0 1 0] ]"
},
{
"code": null,
"e": 2861,
"s": 2852,
"text": "mrdedhia"
},
{
"code": null,
"e": 2878,
"s": 2861,
"text": "Machine Learning"
},
{
"code": null,
"e": 2885,
"s": 2878,
"text": "Python"
},
{
"code": null,
"e": 2902,
"s": 2885,
"text": "Machine Learning"
}
] |
Python Tweepy – Getting the ID of a status
|
18 Jun, 2020
In this article we will see how we can get the ID of a status. Each status or tweet has a unique ID. The id attribute of the Status object provides us with the ID of the status/tweet.
Identifying the ID in the GUI :
In the above mentioned status, the ID can be found in the URL, the ID here is : 1271031982189879297
In order to get the ID of a status, we have to do the following :
Identify the status ID of the status from the GUI.Get the Status object of the status using the get_status() method with the status ID.From this object, fetch the id attribute present in it.
Identify the status ID of the status from the GUI.
Get the Status object of the status using the get_status() method with the status ID.
From this object, fetch the id attribute present in it.
Example 1 : Consider the following status :
We will use the status ID to fetch the status. The status ID of the above mentioned status is 1272771459249844224.
# import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the statusid = 1272771459249844224 # fetching the statusstatus = api.get_status(id) # fetching the id attributeid = status.id print("The ID of the status is : " + str(id))
Output :
The ID of the status is : 1272771459249844224
Example 2 : Consider the following status :
We will use the status ID to fetch the status. The status ID of the above mentioned status is 1272479136133627905.
# the ID of the statusid = 1272479136133627905 # fetching the statusstatus = api.get_status(id) # fetching the id attributeid = status.id print("The ID of the status is : " + str(id))
Output :
The ID of the status is : 1272479136133627905
Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jun, 2020"
},
{
"code": null,
"e": 212,
"s": 28,
"text": "In this article we will see how we can get the ID of a status. Each status or tweet has a unique ID. The id attribute of the Status object provides us with the ID of the status/tweet."
},
{
"code": null,
"e": 244,
"s": 212,
"text": "Identifying the ID in the GUI :"
},
{
"code": null,
"e": 344,
"s": 244,
"text": "In the above mentioned status, the ID can be found in the URL, the ID here is : 1271031982189879297"
},
{
"code": null,
"e": 410,
"s": 344,
"text": "In order to get the ID of a status, we have to do the following :"
},
{
"code": null,
"e": 601,
"s": 410,
"text": "Identify the status ID of the status from the GUI.Get the Status object of the status using the get_status() method with the status ID.From this object, fetch the id attribute present in it."
},
{
"code": null,
"e": 652,
"s": 601,
"text": "Identify the status ID of the status from the GUI."
},
{
"code": null,
"e": 738,
"s": 652,
"text": "Get the Status object of the status using the get_status() method with the status ID."
},
{
"code": null,
"e": 794,
"s": 738,
"text": "From this object, fetch the id attribute present in it."
},
{
"code": null,
"e": 838,
"s": 794,
"text": "Example 1 : Consider the following status :"
},
{
"code": null,
"e": 953,
"s": 838,
"text": "We will use the status ID to fetch the status. The status ID of the above mentioned status is 1272771459249844224."
},
{
"code": "# import the moduleimport tweepy # assign the values accordinglyconsumer_key = \"\"consumer_secret = \"\"access_token = \"\"access_token_secret = \"\" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the statusid = 1272771459249844224 # fetching the statusstatus = api.get_status(id) # fetching the id attributeid = status.id print(\"The ID of the status is : \" + str(id))",
"e": 1548,
"s": 953,
"text": null
},
{
"code": null,
"e": 1557,
"s": 1548,
"text": "Output :"
},
{
"code": null,
"e": 1604,
"s": 1557,
"text": "The ID of the status is : 1272771459249844224\n"
},
{
"code": null,
"e": 1648,
"s": 1604,
"text": "Example 2 : Consider the following status :"
},
{
"code": null,
"e": 1763,
"s": 1648,
"text": "We will use the status ID to fetch the status. The status ID of the above mentioned status is 1272479136133627905."
},
{
"code": "# the ID of the statusid = 1272479136133627905 # fetching the statusstatus = api.get_status(id) # fetching the id attributeid = status.id print(\"The ID of the status is : \" + str(id))",
"e": 1951,
"s": 1763,
"text": null
},
{
"code": null,
"e": 1960,
"s": 1951,
"text": "Output :"
},
{
"code": null,
"e": 2007,
"s": 1960,
"text": "The ID of the status is : 1272479136133627905\n"
},
{
"code": null,
"e": 2021,
"s": 2007,
"text": "Python-Tweepy"
},
{
"code": null,
"e": 2028,
"s": 2021,
"text": "Python"
}
] |
How to Change the Screen Orientation Programmatically using a Button in Android?
|
14 Oct, 2020
Generally, the screen orientation of any application is Portrait styled. But when it comes to gaming or any other multimedia service such as watching a video, the screen orientation must change functionally from Portrait to landscape or vice-versa when the functionality is not required. So a developer has to explicitly write a program where the orientation changes without the user to invoke it traditionally by switching on and off the rotate/auto-rotate available in the swipe-down menu.
The main focus of changing the screen to landscape mode is to increase the area of action and response, and back to normal when not required. The latter can be neglected if there is a direct exit from the application. So this is not an application, instead, it is a feature, that can be given to any application. Some of the applications are where this feature can be added are:
Gaming Applications: As previously mentioned. Landscape view gives better accessibility to the screen for touch in Gaming applications.Videos Application: Applications broadcasting multimedia such as a video can enable this feature to view the same video by utilizing each screen’s pixel.Photo Editing Applications: This feature can help the user view the changes and compare two different portions of the image as the display size has now increased.Applications requiring multiple user inputs: such as a notepad, or a browser, where a user can read the entire line or paragraphs that are being written or applications.
Gaming Applications: As previously mentioned. Landscape view gives better accessibility to the screen for touch in Gaming applications.
Videos Application: Applications broadcasting multimedia such as a video can enable this feature to view the same video by utilizing each screen’s pixel.
Photo Editing Applications: This feature can help the user view the changes and compare two different portions of the image as the display size has now increased.
Applications requiring multiple user inputs: such as a notepad, or a browser, where a user can read the entire line or paragraphs that are being written or applications.
In this application, we will create this feature and keep it explicit, i.e., a Button should be clicked to make the changes. The code in the latter section of the article is limited to the created application only. Screen Orientation changed inside the application make no changes outside the application, i.e., the orientation outside the application remains the same as previously. Note that we are going to implement this project using the Kotlin language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the activity_main.xml file
When the setup is ready, go to the activity_main.xml file, which represents the UI of the project. Create a Button that changes the screen orientation on click. 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:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="click" /> </RelativeLayout>
Step 3: Working with the MainActivity.kt file
In the MainActivity.kt file, declare the Button to change screen orientation (refer to the codes). While setting the onClickListeners to the Button, orientation request is sent to the ActivityInfo. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.content.pm.ActivityInfoimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Button class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val btn = findViewById<Button>(R.id.btn) // reference to change the orientation on every click var isPortrait = true // Button action on click btn.setOnClickListener { // if isPortrait true, change to Landscape requestedOrientation = if (isPortrait) { ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE // else change to Portrait } else { ActivityInfo.SCREEN_ORIENTATION_PORTRAIT } // opposite the value of isPortrait isPortrait = !isPortrait } }}
android
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
Android RecyclerView in Kotlin
Android Project folder Structure
Flutter - Custom Bottom Navigation Bar
Navigation Drawer in Android
Android RecyclerView in Kotlin
Kotlin constructor
Kotlin Array
Android UI Layouts
Retrofit with Kotlin Coroutine in Android
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Oct, 2020"
},
{
"code": null,
"e": 520,
"s": 28,
"text": "Generally, the screen orientation of any application is Portrait styled. But when it comes to gaming or any other multimedia service such as watching a video, the screen orientation must change functionally from Portrait to landscape or vice-versa when the functionality is not required. So a developer has to explicitly write a program where the orientation changes without the user to invoke it traditionally by switching on and off the rotate/auto-rotate available in the swipe-down menu."
},
{
"code": null,
"e": 899,
"s": 520,
"text": "The main focus of changing the screen to landscape mode is to increase the area of action and response, and back to normal when not required. The latter can be neglected if there is a direct exit from the application. So this is not an application, instead, it is a feature, that can be given to any application. Some of the applications are where this feature can be added are:"
},
{
"code": null,
"e": 1519,
"s": 899,
"text": "Gaming Applications: As previously mentioned. Landscape view gives better accessibility to the screen for touch in Gaming applications.Videos Application: Applications broadcasting multimedia such as a video can enable this feature to view the same video by utilizing each screen’s pixel.Photo Editing Applications: This feature can help the user view the changes and compare two different portions of the image as the display size has now increased.Applications requiring multiple user inputs: such as a notepad, or a browser, where a user can read the entire line or paragraphs that are being written or applications."
},
{
"code": null,
"e": 1655,
"s": 1519,
"text": "Gaming Applications: As previously mentioned. Landscape view gives better accessibility to the screen for touch in Gaming applications."
},
{
"code": null,
"e": 1809,
"s": 1655,
"text": "Videos Application: Applications broadcasting multimedia such as a video can enable this feature to view the same video by utilizing each screen’s pixel."
},
{
"code": null,
"e": 1972,
"s": 1809,
"text": "Photo Editing Applications: This feature can help the user view the changes and compare two different portions of the image as the display size has now increased."
},
{
"code": null,
"e": 2142,
"s": 1972,
"text": "Applications requiring multiple user inputs: such as a notepad, or a browser, where a user can read the entire line or paragraphs that are being written or applications."
},
{
"code": null,
"e": 2603,
"s": 2142,
"text": "In this application, we will create this feature and keep it explicit, i.e., a Button should be clicked to make the changes. The code in the latter section of the article is limited to the created application only. Screen Orientation changed inside the application make no changes outside the application, i.e., the orientation outside the application remains the same as previously. Note that we are going to implement this project using the Kotlin language. "
},
{
"code": null,
"e": 2632,
"s": 2603,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 2796,
"s": 2632,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language."
},
{
"code": null,
"e": 2844,
"s": 2796,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 3055,
"s": 2844,
"text": "When the setup is ready, go to the activity_main.xml file, which represents the UI of the project. Create a Button that changes the screen orientation on click. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 3059,
"s": 3055,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/btn\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"click\" /> </RelativeLayout>",
"e": 3617,
"s": 3059,
"text": null
},
{
"code": null,
"e": 3663,
"s": 3617,
"text": "Step 3: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 3983,
"s": 3663,
"text": "In the MainActivity.kt file, declare the Button to change screen orientation (refer to the codes). While setting the onClickListeners to the Button, orientation request is sent to the ActivityInfo. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 3990,
"s": 3983,
"text": "Kotlin"
},
{
"code": "import android.content.pm.ActivityInfoimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Button class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val btn = findViewById<Button>(R.id.btn) // reference to change the orientation on every click var isPortrait = true // Button action on click btn.setOnClickListener { // if isPortrait true, change to Landscape requestedOrientation = if (isPortrait) { ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE // else change to Portrait } else { ActivityInfo.SCREEN_ORIENTATION_PORTRAIT } // opposite the value of isPortrait isPortrait = !isPortrait } }}",
"e": 4930,
"s": 3990,
"text": null
},
{
"code": null,
"e": 4938,
"s": 4930,
"text": "android"
},
{
"code": null,
"e": 4946,
"s": 4938,
"text": "Android"
},
{
"code": null,
"e": 4953,
"s": 4946,
"text": "Kotlin"
},
{
"code": null,
"e": 4961,
"s": 4953,
"text": "Android"
},
{
"code": null,
"e": 5059,
"s": 4961,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5091,
"s": 5059,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 5122,
"s": 5091,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 5155,
"s": 5122,
"text": "Android Project folder Structure"
},
{
"code": null,
"e": 5194,
"s": 5155,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 5223,
"s": 5194,
"text": "Navigation Drawer in Android"
},
{
"code": null,
"e": 5254,
"s": 5223,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 5273,
"s": 5254,
"text": "Kotlin constructor"
},
{
"code": null,
"e": 5286,
"s": 5273,
"text": "Kotlin Array"
},
{
"code": null,
"e": 5305,
"s": 5286,
"text": "Android UI Layouts"
}
] |
Python PIL | Image.split() method
|
21 Jun, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities.
Image.split() method is used to split the image into individual bands. This method returns a tuple of individual image bands from an image.Splitting an “RGB” image creates three new images each containing a copy of one of the original bands (red, green, blue).
Syntax:var = Image.Image.split(image_object)ORvar = Image.Image.split(path_of_image)
Return Value: It returns a tuple containing bands.
Code #1:
# importing Image class from PIL packagefrom PIL import Image # opening a multiband image (RGB specifically)im = Image.open(r"C:\Users\Admin\Pictures\network.png") # split() method# this will split the image in individual bands# and return a tupleim1 = Image.Image.split(im) # showing each bandim1[0].show()im1[1].show()im1[2].show()
Output:
Code #2:
# importing Image class from PIL packagefrom PIL import Image # opening a singleband imageim = Image.open(r"C:\Users\Admin\Pictures\singleband.png") # split() method# this will split the image in individual bands# and return a tuple (of 1 element for singleband)im1 = Image.Image.split(im) # showing imageim1[0].show()
Output:
Images Used:
Image-Processing
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jun, 2019"
},
{
"code": null,
"e": 133,
"s": 28,
"text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities."
},
{
"code": null,
"e": 394,
"s": 133,
"text": "Image.split() method is used to split the image into individual bands. This method returns a tuple of individual image bands from an image.Splitting an “RGB” image creates three new images each containing a copy of one of the original bands (red, green, blue)."
},
{
"code": null,
"e": 479,
"s": 394,
"text": "Syntax:var = Image.Image.split(image_object)ORvar = Image.Image.split(path_of_image)"
},
{
"code": null,
"e": 530,
"s": 479,
"text": "Return Value: It returns a tuple containing bands."
},
{
"code": null,
"e": 539,
"s": 530,
"text": "Code #1:"
},
{
"code": "# importing Image class from PIL packagefrom PIL import Image # opening a multiband image (RGB specifically)im = Image.open(r\"C:\\Users\\Admin\\Pictures\\network.png\") # split() method# this will split the image in individual bands# and return a tupleim1 = Image.Image.split(im) # showing each bandim1[0].show()im1[1].show()im1[2].show()",
"e": 876,
"s": 539,
"text": null
},
{
"code": null,
"e": 884,
"s": 876,
"text": "Output:"
},
{
"code": null,
"e": 893,
"s": 884,
"text": "Code #2:"
},
{
"code": "# importing Image class from PIL packagefrom PIL import Image # opening a singleband imageim = Image.open(r\"C:\\Users\\Admin\\Pictures\\singleband.png\") # split() method# this will split the image in individual bands# and return a tuple (of 1 element for singleband)im1 = Image.Image.split(im) # showing imageim1[0].show()",
"e": 1215,
"s": 893,
"text": null
},
{
"code": null,
"e": 1223,
"s": 1215,
"text": "Output:"
},
{
"code": null,
"e": 1236,
"s": 1223,
"text": "Images Used:"
},
{
"code": null,
"e": 1253,
"s": 1236,
"text": "Image-Processing"
},
{
"code": null,
"e": 1268,
"s": 1253,
"text": "python-utility"
},
{
"code": null,
"e": 1275,
"s": 1268,
"text": "Python"
}
] |
Interval Tree
|
19 Mar, 2022
Consider a situation where we have a set of intervals and we need following operations to be implemented efficiently. 1) Add an interval 2) Remove an interval 3) Given an interval x, find if x overlaps with any of the existing intervals.Interval Tree: The idea is to augment a self-balancing Binary Search Tree (BST) like Red Black Tree, AVL Tree, etc to maintain set of intervals so that all operations can be done in O(Logn) time. Every node of Interval Tree stores following information. a) i: An interval which is represented as a pair [low, high] b) max: Maximum high value in subtree rooted with this node.The low value of an interval is used as key to maintain order in BST. The insert and delete operations are same as insert and delete in self-balancing BST used.
The main operation is to search for an overlapping interval. Following is algorithm for searching an overlapping interval x in an Interval tree rooted with root.
Interval overlappingIntervalSearch(root, x)
1) If x overlaps with root's interval, return the root's interval.
2) If left child of root is not empty and the max in left child
is greater than x's low value, recur for left child
3) Else recur for right child.
How does the above algorithm work? Let the interval to be searched be x. We need to prove this in for following two cases.Case 1: When we go to right subtree, one of the following must be true. a) There is an overlap in right subtree: This is fine as we need to return one overlapping interval. b) There is no overlap in either subtree: We go to right subtree only when either left is NULL or maximum value in left is smaller than x.low. So the interval cannot be present in left subtree.Case 2: When we go to left subtree, one of the following must be true. a) There is an overlap in left subtree: This is fine as we need to return one overlapping interval. b) There is no overlap in either subtree: This is the most important part. We need to consider following facts. ... We went to left subtree because x.low <= max in left subtree .... max in left subtree is a high of one of the intervals let us say [a, max] in left subtree. .... Since x doesn’t overlap with any node in left subtree x.high must be smaller than ‘a‘. .... All nodes in BST are ordered by low value, so all nodes in right subtree must have low value greater than ‘a‘. .... From above two facts, we can say all intervals in right subtree have low value greater than x.high. So x cannot overlap with any interval in right subtree.Implementation of Interval Tree: Following is C++ implementation of Interval Tree. The implementation uses basic insert operation of BST to keep things simple. Ideally it should be insertion of AVL Tree or insertion of Red-Black Tree. Deletion from BST is left as an exercise.
CPP
#include <iostream>using namespace std; // Structure to represent an intervalstruct Interval{ int low, high;}; // Structure to represent a node in Interval Search Treestruct ITNode{ Interval *i; // 'i' could also be a normal variable int max; ITNode *left, *right;}; // A utility function to create a new Interval Search Tree NodeITNode * newNode(Interval i){ ITNode *temp = new ITNode; temp->i = new Interval(i); temp->max = i.high; temp->left = temp->right = NULL; return temp;}; // A utility function to insert a new Interval Search Tree Node// This is similar to BST Insert. Here the low value of interval// is used tomaintain BST propertyITNode *insert(ITNode *root, Interval i){ // Base case: Tree is empty, new node becomes root if (root == NULL) return newNode(i); // Get low value of interval at root int l = root->i->low; // If root's low value is smaller, then new interval goes to // left subtree if (i.low < l) root->left = insert(root->left, i); // Else, new node goes to right subtree. else root->right = insert(root->right, i); // Update the max value of this ancestor if needed if (root->max < i.high) root->max = i.high; return root;} // A utility function to check if given two intervals overlapbool doOVerlap(Interval i1, Interval i2){ if (i1.low <= i2.high && i2.low <= i1.high) return true; return false;} // The main function that searches a given interval i in a given// Interval Tree.Interval *overlapSearch(ITNode *root, Interval i){ // Base Case, tree is empty if (root == NULL) return NULL; // If given interval overlaps with root if (doOVerlap(*(root->i), i)) return root->i; // If left child of root is present and max of left child is // greater than or equal to given interval, then i may // overlap with an interval is left subtree if (root->left != NULL && root->left->max >= i.low) return overlapSearch(root->left, i); // Else interval can only overlap with right subtree return overlapSearch(root->right, i);} void inorder(ITNode *root){ if (root == NULL) return; inorder(root->left); cout << "[" << root->i->low << ", " << root->i->high << "]" << " max = " << root->max << endl; inorder(root->right);} // Driver program to test above functionsint main(){ // Let us create interval tree shown in above figure Interval ints[] = {{15, 20}, {10, 30}, {17, 19}, {5, 20}, {12, 15}, {30, 40} }; int n = sizeof(ints)/sizeof(ints[0]); ITNode *root = NULL; for (int i = 0; i < n; i++) root = insert(root, ints[i]); cout << "Inorder traversal of constructed Interval Tree is\n"; inorder(root); Interval x = {6, 7}; cout << "\nSearching for interval [" << x.low << "," << x.high << "]"; Interval *res = overlapSearch(root, x); if (res == NULL) cout << "\nNo Overlapping Interval"; else cout << "\nOverlaps with [" << res->low << ", " << res->high << "]"; return 0;}
Output:
Inorder traversal of constructed Interval Tree is
[5, 20] max = 20
[10, 30] max = 30
[12, 15] max = 15
[15, 20] max = 40
[17, 19] max = 40
[30, 40] max = 40
Searching for interval [6,7]
Overlaps with [5, 20]
Applications of Interval Tree: Interval tree is mainly a geometric data structure and often used for windowing queries, for instance, to find all roads on a computerized map inside a rectangular viewport, or to find all visible elements inside a three-dimensional scene (Source Wiki).Interval Tree vs Segment Tree Both segment and interval trees store intervals. Segment tree is mainly optimized for queries for a given point, and interval trees are mainly optimized for overlapping queries for a given interval.Exercise: 1) Implement delete operation for interval tree. 2) Extend the intervalSearch() to print all overlapping intervals instead of just one. http://en.wikipedia.org/wiki/Interval_tree http://www.cse.unr.edu/~mgunes/cs302/IntervalTrees.pptx Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest https://www.youtube.com/watch?v=dQF0zyaym8APlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above
CurranTejwani
jonathanfdees
Advanced Data Structure
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Mar, 2022"
},
{
"code": null,
"e": 827,
"s": 52,
"text": "Consider a situation where we have a set of intervals and we need following operations to be implemented efficiently. 1) Add an interval 2) Remove an interval 3) Given an interval x, find if x overlaps with any of the existing intervals.Interval Tree: The idea is to augment a self-balancing Binary Search Tree (BST) like Red Black Tree, AVL Tree, etc to maintain set of intervals so that all operations can be done in O(Logn) time. Every node of Interval Tree stores following information. a) i: An interval which is represented as a pair [low, high] b) max: Maximum high value in subtree rooted with this node.The low value of an interval is used as key to maintain order in BST. The insert and delete operations are same as insert and delete in self-balancing BST used. "
},
{
"code": null,
"e": 990,
"s": 827,
"text": "The main operation is to search for an overlapping interval. Following is algorithm for searching an overlapping interval x in an Interval tree rooted with root. "
},
{
"code": null,
"e": 1252,
"s": 990,
"text": "Interval overlappingIntervalSearch(root, x)\n1) If x overlaps with root's interval, return the root's interval.\n\n2) If left child of root is not empty and the max in left child \nis greater than x's low value, recur for left child\n\n3) Else recur for right child."
},
{
"code": null,
"e": 2830,
"s": 1252,
"text": "How does the above algorithm work? Let the interval to be searched be x. We need to prove this in for following two cases.Case 1: When we go to right subtree, one of the following must be true. a) There is an overlap in right subtree: This is fine as we need to return one overlapping interval. b) There is no overlap in either subtree: We go to right subtree only when either left is NULL or maximum value in left is smaller than x.low. So the interval cannot be present in left subtree.Case 2: When we go to left subtree, one of the following must be true. a) There is an overlap in left subtree: This is fine as we need to return one overlapping interval. b) There is no overlap in either subtree: This is the most important part. We need to consider following facts. ... We went to left subtree because x.low <= max in left subtree .... max in left subtree is a high of one of the intervals let us say [a, max] in left subtree. .... Since x doesn’t overlap with any node in left subtree x.high must be smaller than ‘a‘. .... All nodes in BST are ordered by low value, so all nodes in right subtree must have low value greater than ‘a‘. .... From above two facts, we can say all intervals in right subtree have low value greater than x.high. So x cannot overlap with any interval in right subtree.Implementation of Interval Tree: Following is C++ implementation of Interval Tree. The implementation uses basic insert operation of BST to keep things simple. Ideally it should be insertion of AVL Tree or insertion of Red-Black Tree. Deletion from BST is left as an exercise. "
},
{
"code": null,
"e": 2834,
"s": 2830,
"text": "CPP"
},
{
"code": "#include <iostream>using namespace std; // Structure to represent an intervalstruct Interval{ int low, high;}; // Structure to represent a node in Interval Search Treestruct ITNode{ Interval *i; // 'i' could also be a normal variable int max; ITNode *left, *right;}; // A utility function to create a new Interval Search Tree NodeITNode * newNode(Interval i){ ITNode *temp = new ITNode; temp->i = new Interval(i); temp->max = i.high; temp->left = temp->right = NULL; return temp;}; // A utility function to insert a new Interval Search Tree Node// This is similar to BST Insert. Here the low value of interval// is used tomaintain BST propertyITNode *insert(ITNode *root, Interval i){ // Base case: Tree is empty, new node becomes root if (root == NULL) return newNode(i); // Get low value of interval at root int l = root->i->low; // If root's low value is smaller, then new interval goes to // left subtree if (i.low < l) root->left = insert(root->left, i); // Else, new node goes to right subtree. else root->right = insert(root->right, i); // Update the max value of this ancestor if needed if (root->max < i.high) root->max = i.high; return root;} // A utility function to check if given two intervals overlapbool doOVerlap(Interval i1, Interval i2){ if (i1.low <= i2.high && i2.low <= i1.high) return true; return false;} // The main function that searches a given interval i in a given// Interval Tree.Interval *overlapSearch(ITNode *root, Interval i){ // Base Case, tree is empty if (root == NULL) return NULL; // If given interval overlaps with root if (doOVerlap(*(root->i), i)) return root->i; // If left child of root is present and max of left child is // greater than or equal to given interval, then i may // overlap with an interval is left subtree if (root->left != NULL && root->left->max >= i.low) return overlapSearch(root->left, i); // Else interval can only overlap with right subtree return overlapSearch(root->right, i);} void inorder(ITNode *root){ if (root == NULL) return; inorder(root->left); cout << \"[\" << root->i->low << \", \" << root->i->high << \"]\" << \" max = \" << root->max << endl; inorder(root->right);} // Driver program to test above functionsint main(){ // Let us create interval tree shown in above figure Interval ints[] = {{15, 20}, {10, 30}, {17, 19}, {5, 20}, {12, 15}, {30, 40} }; int n = sizeof(ints)/sizeof(ints[0]); ITNode *root = NULL; for (int i = 0; i < n; i++) root = insert(root, ints[i]); cout << \"Inorder traversal of constructed Interval Tree is\\n\"; inorder(root); Interval x = {6, 7}; cout << \"\\nSearching for interval [\" << x.low << \",\" << x.high << \"]\"; Interval *res = overlapSearch(root, x); if (res == NULL) cout << \"\\nNo Overlapping Interval\"; else cout << \"\\nOverlaps with [\" << res->low << \", \" << res->high << \"]\"; return 0;}",
"e": 5879,
"s": 2834,
"text": null
},
{
"code": null,
"e": 5888,
"s": 5879,
"text": "Output: "
},
{
"code": null,
"e": 6097,
"s": 5888,
"text": "Inorder traversal of constructed Interval Tree is\n[5, 20] max = 20\n[10, 30] max = 30\n[12, 15] max = 15\n[15, 20] max = 40\n[17, 19] max = 40\n[30, 40] max = 40\n\nSearching for interval [6,7]\nOverlaps with [5, 20]"
},
{
"code": null,
"e": 7137,
"s": 6097,
"text": "Applications of Interval Tree: Interval tree is mainly a geometric data structure and often used for windowing queries, for instance, to find all roads on a computerized map inside a rectangular viewport, or to find all visible elements inside a three-dimensional scene (Source Wiki).Interval Tree vs Segment Tree Both segment and interval trees store intervals. Segment tree is mainly optimized for queries for a given point, and interval trees are mainly optimized for overlapping queries for a given interval.Exercise: 1) Implement delete operation for interval tree. 2) Extend the intervalSearch() to print all overlapping intervals instead of just one. http://en.wikipedia.org/wiki/Interval_tree http://www.cse.unr.edu/~mgunes/cs302/IntervalTrees.pptx Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest https://www.youtube.com/watch?v=dQF0zyaym8APlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 7151,
"s": 7137,
"text": "CurranTejwani"
},
{
"code": null,
"e": 7165,
"s": 7151,
"text": "jonathanfdees"
},
{
"code": null,
"e": 7189,
"s": 7165,
"text": "Advanced Data Structure"
}
] |
E-Governance
|
12 Jul, 2022
Electronic Governance or E-Governance is the application of Information and Communication Technology (ICT) for providing government services, interchange of statics, communication proceedings, and integration of various independent systems and services. Through the means of e-governance, government services are made available to citizens in a suitable, systematic, and transparent mode. The three main selected groups that can be discriminated against in governance concepts are government, common people, and business groups.
E-governance is the best utilization of information and communication technologies to mutate and upgrade the coherence, productivity, efficacy, transparency, and liability of informational and transnational interchanges within government, between government agencies at different levels, citizens & businesses. It also gives authorization to citizens through access and use of information. Generally, E-governance uses information and communication technologies at various levels of the government and the public sector to enhance governance.
Theoretical studies state that E-Governance is the procedure of change of the correlation of government with its ingredients, the citizens, the businesses, and its own organs, through the use of tools of information and communication technology.
The UNESCO states that E-governance is the public sector’s use of information and communication automation in order to upgrade information and service delivery, stimulating resident involvement in the decision-making process and making government more liable, unambiguous and productive.
Elements of E-Governance:
Basic elements of e-governance are:
GovernmentCitizensInvestors/Businesses
Government
Citizens
Investors/Businesses
Types of E-Governance:
E-governance is of 4 types:
Government-to-Citizen (G2C): The Government-to-citizen mentions the government services that are acquired by the familiar people. Most of the government services come under G2C. Similarly, the primary aim of Government-to-citizen is to supply facilities to the citizens. It also helps ordinary people to minimize the time and cost to carry out a transaction. A citizen can retrieve the facilities anytime from anywhere. Similarly, spending the administrative fee online is also possible due to G2C. The facility of Government-to-Citizen allows the ordinary citizen to outclass time limitations. It also focuses on geographic land barriers.Government-to-business (G2B): Government-to-business is the interchange of services between Government and Business firms. It is productive for both government and business firms. G2B provides access to pertinent forms needed to observe. It also contains many services interchanged between business sectors and government. Similarly, Government-to-business provides timely business information. A business organization can have easy and easy online access to government agencies. G2B plays an important role in business development. It upgrades the efficiency and quality of communication and transparency of government projects.Government-to-Government (G2G): The Government-to-Government mentions the interaction between different government departments, firms, and agencies. This increases the efficiency of government processes. In G2G, government agencies can share the same database using online communication. The government departments can work together. This service can increase international discretion and relations. G2G services can be at the local level or at the international level. It can convey to both global government and local government. It also provides a safe and secure inter-relationship between domestic and foreign governments. G2G builds a universal database for all members to upgrade service.Government-to-Employee (G2E): The Government-to-Employee is the internal part of G2G section. It aims to bring employees together and improvise knowledge sharing. It provides online facilities to the employees. Similarly, applying for leave, reviewing salary payment record and checking the balance of holiday. The G2E sector yields human resource training and development. So, G2E is also the correlation between employees and government institutions.
Government-to-Citizen (G2C): The Government-to-citizen mentions the government services that are acquired by the familiar people. Most of the government services come under G2C. Similarly, the primary aim of Government-to-citizen is to supply facilities to the citizens. It also helps ordinary people to minimize the time and cost to carry out a transaction. A citizen can retrieve the facilities anytime from anywhere. Similarly, spending the administrative fee online is also possible due to G2C. The facility of Government-to-Citizen allows the ordinary citizen to outclass time limitations. It also focuses on geographic land barriers.
Government-to-business (G2B): Government-to-business is the interchange of services between Government and Business firms. It is productive for both government and business firms. G2B provides access to pertinent forms needed to observe. It also contains many services interchanged between business sectors and government. Similarly, Government-to-business provides timely business information. A business organization can have easy and easy online access to government agencies. G2B plays an important role in business development. It upgrades the efficiency and quality of communication and transparency of government projects.
Government-to-Government (G2G): The Government-to-Government mentions the interaction between different government departments, firms, and agencies. This increases the efficiency of government processes. In G2G, government agencies can share the same database using online communication. The government departments can work together. This service can increase international discretion and relations. G2G services can be at the local level or at the international level. It can convey to both global government and local government. It also provides a safe and secure inter-relationship between domestic and foreign governments. G2G builds a universal database for all members to upgrade service.
Government-to-Employee (G2E): The Government-to-Employee is the internal part of G2G section. It aims to bring employees together and improvise knowledge sharing. It provides online facilities to the employees. Similarly, applying for leave, reviewing salary payment record and checking the balance of holiday. The G2E sector yields human resource training and development. So, G2E is also the correlation between employees and government institutions.
Advantages of E-Governance:
The supreme goal of e-governance is to be able to provide an increased portfolio of public services to citizens in a systematic and cost effective way. It allows for government transparency because it allows the public to be informed about what the government is working on as well as the policies they are trying to implement.
The main advantage while executing electronic government will be to enhance the efficiency of the current system.
Another advantage is that it increases transparency in the administration, reduces costs, increases revenue growth, and also improves relationships between the public and the civic authorities.
Disadvantages of E-Governance:
The main disadvantage regarding e-governance is the absence of fairness in public access to the internet, of trustworthy information on the web, and disguised agendas of government groups that could have an impact and could bias public opinions.
krishna_97
sayanc170
Information-Security
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Jul, 2022"
},
{
"code": null,
"e": 558,
"s": 28,
"text": "Electronic Governance or E-Governance is the application of Information and Communication Technology (ICT) for providing government services, interchange of statics, communication proceedings, and integration of various independent systems and services. Through the means of e-governance, government services are made available to citizens in a suitable, systematic, and transparent mode. The three main selected groups that can be discriminated against in governance concepts are government, common people, and business groups. "
},
{
"code": null,
"e": 1102,
"s": 558,
"text": "E-governance is the best utilization of information and communication technologies to mutate and upgrade the coherence, productivity, efficacy, transparency, and liability of informational and transnational interchanges within government, between government agencies at different levels, citizens & businesses. It also gives authorization to citizens through access and use of information. Generally, E-governance uses information and communication technologies at various levels of the government and the public sector to enhance governance. "
},
{
"code": null,
"e": 1349,
"s": 1102,
"text": "Theoretical studies state that E-Governance is the procedure of change of the correlation of government with its ingredients, the citizens, the businesses, and its own organs, through the use of tools of information and communication technology. "
},
{
"code": null,
"e": 1638,
"s": 1349,
"text": "The UNESCO states that E-governance is the public sector’s use of information and communication automation in order to upgrade information and service delivery, stimulating resident involvement in the decision-making process and making government more liable, unambiguous and productive. "
},
{
"code": null,
"e": 1665,
"s": 1638,
"text": "Elements of E-Governance: "
},
{
"code": null,
"e": 1701,
"s": 1665,
"text": "Basic elements of e-governance are:"
},
{
"code": null,
"e": 1740,
"s": 1701,
"text": "GovernmentCitizensInvestors/Businesses"
},
{
"code": null,
"e": 1751,
"s": 1740,
"text": "Government"
},
{
"code": null,
"e": 1760,
"s": 1751,
"text": "Citizens"
},
{
"code": null,
"e": 1781,
"s": 1760,
"text": "Investors/Businesses"
},
{
"code": null,
"e": 1805,
"s": 1781,
"text": "Types of E-Governance: "
},
{
"code": null,
"e": 1833,
"s": 1805,
"text": "E-governance is of 4 types:"
},
{
"code": null,
"e": 4249,
"s": 1833,
"text": "Government-to-Citizen (G2C): The Government-to-citizen mentions the government services that are acquired by the familiar people. Most of the government services come under G2C. Similarly, the primary aim of Government-to-citizen is to supply facilities to the citizens. It also helps ordinary people to minimize the time and cost to carry out a transaction. A citizen can retrieve the facilities anytime from anywhere. Similarly, spending the administrative fee online is also possible due to G2C. The facility of Government-to-Citizen allows the ordinary citizen to outclass time limitations. It also focuses on geographic land barriers.Government-to-business (G2B): Government-to-business is the interchange of services between Government and Business firms. It is productive for both government and business firms. G2B provides access to pertinent forms needed to observe. It also contains many services interchanged between business sectors and government. Similarly, Government-to-business provides timely business information. A business organization can have easy and easy online access to government agencies. G2B plays an important role in business development. It upgrades the efficiency and quality of communication and transparency of government projects.Government-to-Government (G2G): The Government-to-Government mentions the interaction between different government departments, firms, and agencies. This increases the efficiency of government processes. In G2G, government agencies can share the same database using online communication. The government departments can work together. This service can increase international discretion and relations. G2G services can be at the local level or at the international level. It can convey to both global government and local government. It also provides a safe and secure inter-relationship between domestic and foreign governments. G2G builds a universal database for all members to upgrade service.Government-to-Employee (G2E): The Government-to-Employee is the internal part of G2G section. It aims to bring employees together and improvise knowledge sharing. It provides online facilities to the employees. Similarly, applying for leave, reviewing salary payment record and checking the balance of holiday. The G2E sector yields human resource training and development. So, G2E is also the correlation between employees and government institutions."
},
{
"code": null,
"e": 4889,
"s": 4249,
"text": "Government-to-Citizen (G2C): The Government-to-citizen mentions the government services that are acquired by the familiar people. Most of the government services come under G2C. Similarly, the primary aim of Government-to-citizen is to supply facilities to the citizens. It also helps ordinary people to minimize the time and cost to carry out a transaction. A citizen can retrieve the facilities anytime from anywhere. Similarly, spending the administrative fee online is also possible due to G2C. The facility of Government-to-Citizen allows the ordinary citizen to outclass time limitations. It also focuses on geographic land barriers."
},
{
"code": null,
"e": 5519,
"s": 4889,
"text": "Government-to-business (G2B): Government-to-business is the interchange of services between Government and Business firms. It is productive for both government and business firms. G2B provides access to pertinent forms needed to observe. It also contains many services interchanged between business sectors and government. Similarly, Government-to-business provides timely business information. A business organization can have easy and easy online access to government agencies. G2B plays an important role in business development. It upgrades the efficiency and quality of communication and transparency of government projects."
},
{
"code": null,
"e": 6215,
"s": 5519,
"text": "Government-to-Government (G2G): The Government-to-Government mentions the interaction between different government departments, firms, and agencies. This increases the efficiency of government processes. In G2G, government agencies can share the same database using online communication. The government departments can work together. This service can increase international discretion and relations. G2G services can be at the local level or at the international level. It can convey to both global government and local government. It also provides a safe and secure inter-relationship between domestic and foreign governments. G2G builds a universal database for all members to upgrade service."
},
{
"code": null,
"e": 6668,
"s": 6215,
"text": "Government-to-Employee (G2E): The Government-to-Employee is the internal part of G2G section. It aims to bring employees together and improvise knowledge sharing. It provides online facilities to the employees. Similarly, applying for leave, reviewing salary payment record and checking the balance of holiday. The G2E sector yields human resource training and development. So, G2E is also the correlation between employees and government institutions."
},
{
"code": null,
"e": 6697,
"s": 6668,
"text": "Advantages of E-Governance: "
},
{
"code": null,
"e": 7026,
"s": 6697,
"text": "The supreme goal of e-governance is to be able to provide an increased portfolio of public services to citizens in a systematic and cost effective way. It allows for government transparency because it allows the public to be informed about what the government is working on as well as the policies they are trying to implement. "
},
{
"code": null,
"e": 7141,
"s": 7026,
"text": "The main advantage while executing electronic government will be to enhance the efficiency of the current system. "
},
{
"code": null,
"e": 7335,
"s": 7141,
"text": "Another advantage is that it increases transparency in the administration, reduces costs, increases revenue growth, and also improves relationships between the public and the civic authorities."
},
{
"code": null,
"e": 7367,
"s": 7335,
"text": "Disadvantages of E-Governance: "
},
{
"code": null,
"e": 7613,
"s": 7367,
"text": "The main disadvantage regarding e-governance is the absence of fairness in public access to the internet, of trustworthy information on the web, and disguised agendas of government groups that could have an impact and could bias public opinions."
},
{
"code": null,
"e": 7624,
"s": 7613,
"text": "krishna_97"
},
{
"code": null,
"e": 7634,
"s": 7624,
"text": "sayanc170"
},
{
"code": null,
"e": 7655,
"s": 7634,
"text": "Information-Security"
},
{
"code": null,
"e": 7673,
"s": 7655,
"text": "Computer Networks"
},
{
"code": null,
"e": 7691,
"s": 7673,
"text": "Computer Networks"
}
] |
Rat Maze With Multiple Jumps | Practice | GeeksforGeeks
|
A Maze is given as n*n matrix of blocks where source block is the upper left most block i.e., matrix[0][0] and destination block is lower rightmost block i.e., matrix[n-1][n-1]. A rat starts from source and has to reach the destination. The rat can move in only two directions: first forward if possible or down. If multiple solutions exist, the shortest earliest hop will be accepted. For the same hop distance at any point, forward will be preferred over downward. In the maze matrix, 0 means the block is the dead end and non-zero number means the block can be used in the path from source to destination. The non-zero value of mat[i][j] indicates number of maximum jumps rat can make from cell mat[i][j]. In this variation, Rat is allowed to jump multiple steps at a time instead of 1. Find a matrix which describes the position the rat to reach at the destination.
Example:
Input: {{2,1,0,0},{3,0,0,1},{0,1,0,1},
{0,0,0,1}}
Output: {{1,0,0,0},{1,0,0,1},{0,0,0,1},
{0,0,0,1}}
Explanation: Rat started with matrix[0][0] and
can jump up to 2 steps right/down. First check
matrix[0][1] as it is 1, next check
matrix[0][2] ,this won't lead to the solution.
Then check matrix[1][0], as this is 3(non-zero)
,so we can make 3 jumps to reach matrix[1][3].
From matrix[1][3] we can move downwards taking
1 jump each time to reach destination at
matrix[3][3].
Example 2:
Input: {{2,1,0,0},{2,0,0,1},{0,1,0,1},
{0,0,0,1}}
Output: {{-1}}
Explanation: As no path exists so, -1.
Your Task:
You don't need to read or print anyhting, Your task is to complete the function ShortestDistance() which takes the matrix as input parameter and returns a matrix of size n if path exists otherwise returns a matrix of 1x1 which contains -1. In output matrix, 1 at (i, j) represents the cell is taken into the path otherwise 0 if any path exists.
Expected Time Complexity: O(n*n*k) where k is max(matrix[i][j])
Expected Space Complexity: O(1)
Constraints:
1 <= n <= 50
1 <= matrix[i][j] <= 20
+1
sharma39vishal1 day ago
// { Driver Code Starts#include<bits/stdc++.h>using namespace std;
// } Driver Code Endsclass Solution {public:void sol(int i,int j,vector<vector<int>>&matrix,vector<vector<int>>ans,vector<vector<int>>&bans,int &gotit){if(gotit==1){ return;} if(i==matrix.size()-1&&j==matrix[0].size()-1){ ans[matrix.size()-1][matrix.size()-1]=1; for(int r=0;r<matrix.size();r++){ for(int v=0;v<matrix.size();v++){ // cout<<ans[r][v]<<" "; bans[r][v]=ans[r][v]; } // cout<<endl; } gotit=1; return ; } int n=matrix.size(); for(int k=1;k<=matrix[i][j];k++){ if(j+k<n&&matrix[i][j+k]!=0){ ans[i][j]=1; sol(i,j+k,matrix,ans,bans,gotit); ans[i][j]=0; } if(i+k<n&&matrix[i+k][j]!=0){ ans[i][j]=1; sol(i+k,j,matrix,ans,bans,gotit); ans[i][j]=0; } }}vector<vector<int>> ShortestDistance(vector<vector<int>>&matrix){ vector<vector<int>>ans(matrix.size(),vector<int>(matrix[0].size(),0)); vector<vector<int>>bans(matrix.size(),vector<int>(matrix[0].size(),0)); matrix[matrix.size()-1][matrix[0].size()-1]=1; int gotit=0; sol(0,0,matrix,ans,bans,gotit); if(gotit==0){ vector<vector<int>>noWay(1,vector<int>(1,-1));
return noWay; } return bans;}
};
// { Driver Code Starts.int main(){int tc;cin >> tc;while(tc--){ int n; cin >> n; vector<vector<int>>matrix(n, vector<int>(n,0)); for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ cin >> matrix[i][j]; } } Solution obj; vector<vector<int>> ans = obj.ShortestDistance(matrix); for(auto i: ans){ for(auto j: i){ cout << j << " "; } cout << "\n"; }}return 0;} // } Driver Code Ends
0
sharma39vishal
This comment was deleted.
0
tthakare733 weeks ago
//java solution -> TC -> 0.45
class Solution{
public static int N, M;
public static boolean check(int i, int j, int[][] matrix){
return (i >= 0 && j >= 0 && i < N && j < M && matrix[i][j] != 0);
}
public static int[][] shortestPath(int[][] mat, int[][] matrix, int i, int j){
if(i == N - 1 && j == M -1) {
mat[i][j] = new Integer(1);
return mat;
}
if(check(i, j, matrix)){
for(int noPath = 1; noPath <= matrix[i][j]; noPath++){
//right
int[][] right = shortestPath(mat, matrix, i, j+noPath);
if(right[N-1][M-1] == 1) {
right[i][j] = new Integer(1);
return right;
}
//bottom
int[][] bottom = shortestPath(mat, matrix, i+noPath, j);
if(bottom[N-1][M-1] == 1) {
bottom[i][j] = new Integer(1);
return bottom;
}
}
}
return mat;
}
public int[][] ShortestDistance(int[][] matrix){
// Code here
N = matrix.length;
M = matrix[0].length;
int[][] mat = new int[N][M];
int[][] noWay = new int[1][1];
noWay[0][0] = -1;
int[][] Result = shortestPath(mat, matrix, 0, 0);
if(Result[N-1][M-1] != 0){
return Result;
}
return noWay;
}
}
+2
ahmadashad07861 month ago
bool findPath(vector<vector<int>>&m, vector<vector<int>>&res, int i, int j, int n){ if(i<0||j<0||i>=n||j>=n) return false; if(i==n-1&&j==n-1){ res[i][j]=1; return true; } res[i][j]=1; int d=m[i][j]; for(int k=1; k<=d; k++){ if(findPath(m, res, i,j+k, n)) return true; if(findPath(m, res, i+k,j, n)) return true; } res[i][j]=0; return false; } vector<vector<int>> ShortestDistance(vector<vector<int>>&matrix){ // Code here int n=matrix.size(); vector<vector<int>> res(n,vector<int>(n,0)); vector<vector<int>> ans(1); ans[0].push_back(-1); if(matrix[0][0]==0&&n>1) return ans; if(findPath(matrix, res,0,0,n)) return res; return ans;}
0
100rab_h1 month ago
O(1) Space Complexity
bool isSafe(int i, int j, int n, vector<vector<int>> &matrix) {
return (i < n && j < n && matrix[i][j] != 0);
}
bool distanceRec(vector<vector<int>> &matrix, int n, int i, int j) {
if (i == n - 1 && j == n - 1) {
matrix[i][j] = -1;
return true;
}
if(isSafe(i, j, n, matrix)) {
int x = matrix[i][j];
matrix[i][j] = -1;
for (int a = 1; a <= x; a++) {
if (distanceRec(matrix, n, i, j + a) == true) return true;
if (distanceRec(matrix, n, i + a, j) == true) return true;
}
matrix[i][j] = 0;
}
return false;
}
vector<vector<int>> ShortestDistance(vector<vector<int>>&matrix){
// Code here
int n = matrix.size();
bool flag = distanceRec(matrix, n, 0, 0);
if (flag) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if(matrix[i][j] == -1) matrix[i][j] = 1;
else matrix[i][j] = 0;
}
}
return matrix;
}
else return {{-1}};
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints.
|
[
{
"code": null,
"e": 1110,
"s": 238,
"text": "A Maze is given as n*n matrix of blocks where source block is the upper left most block i.e., matrix[0][0] and destination block is lower rightmost block i.e., matrix[n-1][n-1]. A rat starts from source and has to reach the destination. The rat can move in only two directions: first forward if possible or down. If multiple solutions exist, the shortest earliest hop will be accepted. For the same hop distance at any point, forward will be preferred over downward. In the maze matrix, 0 means the block is the dead end and non-zero number means the block can be used in the path from source to destination. The non-zero value of mat[i][j] indicates number of maximum jumps rat can make from cell mat[i][j]. In this variation, Rat is allowed to jump multiple steps at a time instead of 1. Find a matrix which describes the position the rat to reach at the destination.\n "
},
{
"code": null,
"e": 1119,
"s": 1110,
"text": "Example:"
},
{
"code": null,
"e": 1602,
"s": 1119,
"text": "Input: {{2,1,0,0},{3,0,0,1},{0,1,0,1},\n{0,0,0,1}}\nOutput: {{1,0,0,0},{1,0,0,1},{0,0,0,1},\n{0,0,0,1}}\nExplanation: Rat started with matrix[0][0] and \ncan jump up to 2 steps right/down. First check \nmatrix[0][1] as it is 1, next check \nmatrix[0][2] ,this won't lead to the solution. \nThen check matrix[1][0], as this is 3(non-zero)\n,so we can make 3 jumps to reach matrix[1][3]. \nFrom matrix[1][3] we can move downwards taking \n1 jump each time to reach destination at \nmatrix[3][3].\n"
},
{
"code": null,
"e": 1613,
"s": 1602,
"text": "Example 2:"
},
{
"code": null,
"e": 1718,
"s": 1613,
"text": "Input: {{2,1,0,0},{2,0,0,1},{0,1,0,1},\n{0,0,0,1}}\nOutput: {{-1}}\nExplanation: As no path exists so, -1.\n"
},
{
"code": null,
"e": 2078,
"s": 1720,
"text": "Your Task:\nYou don't need to read or print anyhting, Your task is to complete the function ShortestDistance() which takes the matrix as input parameter and returns a matrix of size n if path exists otherwise returns a matrix of 1x1 which contains -1. In output matrix, 1 at (i, j) represents the cell is taken into the path otherwise 0 if any path exists.\n "
},
{
"code": null,
"e": 2176,
"s": 2078,
"text": "Expected Time Complexity: O(n*n*k) where k is max(matrix[i][j])\nExpected Space Complexity: O(1)\n "
},
{
"code": null,
"e": 2226,
"s": 2176,
"text": "Constraints:\n1 <= n <= 50\n1 <= matrix[i][j] <= 20"
},
{
"code": null,
"e": 2229,
"s": 2226,
"text": "+1"
},
{
"code": null,
"e": 2253,
"s": 2229,
"text": "sharma39vishal1 day ago"
},
{
"code": null,
"e": 2320,
"s": 2253,
"text": "// { Driver Code Starts#include<bits/stdc++.h>using namespace std;"
},
{
"code": null,
"e": 3479,
"s": 2320,
"text": "// } Driver Code Endsclass Solution {public:void sol(int i,int j,vector<vector<int>>&matrix,vector<vector<int>>ans,vector<vector<int>>&bans,int &gotit){if(gotit==1){ return;} if(i==matrix.size()-1&&j==matrix[0].size()-1){ ans[matrix.size()-1][matrix.size()-1]=1; for(int r=0;r<matrix.size();r++){ for(int v=0;v<matrix.size();v++){ // cout<<ans[r][v]<<\" \"; bans[r][v]=ans[r][v]; } // cout<<endl; } gotit=1; return ; } int n=matrix.size(); for(int k=1;k<=matrix[i][j];k++){ if(j+k<n&&matrix[i][j+k]!=0){ ans[i][j]=1; sol(i,j+k,matrix,ans,bans,gotit); ans[i][j]=0; } if(i+k<n&&matrix[i+k][j]!=0){ ans[i][j]=1; sol(i+k,j,matrix,ans,bans,gotit); ans[i][j]=0; } }}vector<vector<int>> ShortestDistance(vector<vector<int>>&matrix){ vector<vector<int>>ans(matrix.size(),vector<int>(matrix[0].size(),0)); vector<vector<int>>bans(matrix.size(),vector<int>(matrix[0].size(),0)); matrix[matrix.size()-1][matrix[0].size()-1]=1; int gotit=0; sol(0,0,matrix,ans,bans,gotit); if(gotit==0){ vector<vector<int>>noWay(1,vector<int>(1,-1));"
},
{
"code": null,
"e": 3520,
"s": 3479,
"text": " return noWay; } return bans;}"
},
{
"code": null,
"e": 3523,
"s": 3520,
"text": "};"
},
{
"code": null,
"e": 3917,
"s": 3523,
"text": "// { Driver Code Starts.int main(){int tc;cin >> tc;while(tc--){ int n; cin >> n; vector<vector<int>>matrix(n, vector<int>(n,0)); for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ cin >> matrix[i][j]; } } Solution obj; vector<vector<int>> ans = obj.ShortestDistance(matrix); for(auto i: ans){ for(auto j: i){ cout << j << \" \"; } cout << \"\\n\"; }}return 0;} // } Driver Code Ends"
},
{
"code": null,
"e": 3919,
"s": 3917,
"text": "0"
},
{
"code": null,
"e": 3934,
"s": 3919,
"text": "sharma39vishal"
},
{
"code": null,
"e": 3960,
"s": 3934,
"text": "This comment was deleted."
},
{
"code": null,
"e": 3962,
"s": 3960,
"text": "0"
},
{
"code": null,
"e": 3984,
"s": 3962,
"text": "tthakare733 weeks ago"
},
{
"code": null,
"e": 5484,
"s": 3984,
"text": "//java solution -> TC -> 0.45\nclass Solution{\n public static int N, M;\n \n public static boolean check(int i, int j, int[][] matrix){\n return (i >= 0 && j >= 0 && i < N && j < M && matrix[i][j] != 0); \n } \n \n public static int[][] shortestPath(int[][] mat, int[][] matrix, int i, int j){\n if(i == N - 1 && j == M -1) {\n mat[i][j] = new Integer(1); \n return mat;\n }\n \n if(check(i, j, matrix)){\n for(int noPath = 1; noPath <= matrix[i][j]; noPath++){\n //right\n int[][] right = shortestPath(mat, matrix, i, j+noPath);\n if(right[N-1][M-1] == 1) {\n right[i][j] = new Integer(1);\n return right;\n }\n //bottom\n int[][] bottom = shortestPath(mat, matrix, i+noPath, j);\n if(bottom[N-1][M-1] == 1) {\n bottom[i][j] = new Integer(1);\n return bottom;\n }\n }\n }\n \n return mat;\n }\n public int[][] ShortestDistance(int[][] matrix){\n // Code here\n N = matrix.length;\n M = matrix[0].length;\n int[][] mat = new int[N][M];\n int[][] noWay = new int[1][1];\n noWay[0][0] = -1;\n int[][] Result = shortestPath(mat, matrix, 0, 0);\n if(Result[N-1][M-1] != 0){\n return Result;\n }\n return noWay;\n }\n}"
},
{
"code": null,
"e": 5487,
"s": 5484,
"text": "+2"
},
{
"code": null,
"e": 5513,
"s": 5487,
"text": "ahmadashad07861 month ago"
},
{
"code": null,
"e": 6262,
"s": 5513,
"text": "bool findPath(vector<vector<int>>&m, vector<vector<int>>&res, int i, int j, int n){ if(i<0||j<0||i>=n||j>=n) return false; if(i==n-1&&j==n-1){ res[i][j]=1; return true; } res[i][j]=1; int d=m[i][j]; for(int k=1; k<=d; k++){ if(findPath(m, res, i,j+k, n)) return true; if(findPath(m, res, i+k,j, n)) return true; } res[i][j]=0; return false; } vector<vector<int>> ShortestDistance(vector<vector<int>>&matrix){ // Code here int n=matrix.size(); vector<vector<int>> res(n,vector<int>(n,0)); vector<vector<int>> ans(1); ans[0].push_back(-1); if(matrix[0][0]==0&&n>1) return ans; if(findPath(matrix, res,0,0,n)) return res; return ans;}"
},
{
"code": null,
"e": 6264,
"s": 6262,
"text": "0"
},
{
"code": null,
"e": 6284,
"s": 6264,
"text": "100rab_h1 month ago"
},
{
"code": null,
"e": 6306,
"s": 6284,
"text": "O(1) Space Complexity"
},
{
"code": null,
"e": 7436,
"s": 6306,
"text": "bool isSafe(int i, int j, int n, vector<vector<int>> &matrix) {\n return (i < n && j < n && matrix[i][j] != 0);\n }\n\n bool distanceRec(vector<vector<int>> &matrix, int n, int i, int j) {\n \n if (i == n - 1 && j == n - 1) {\n matrix[i][j] = -1;\n return true;\n }\n if(isSafe(i, j, n, matrix)) {\n int x = matrix[i][j];\n matrix[i][j] = -1;\n for (int a = 1; a <= x; a++) {\n if (distanceRec(matrix, n, i, j + a) == true) return true;\n if (distanceRec(matrix, n, i + a, j) == true) return true;\n }\n matrix[i][j] = 0;\n }\n return false;\n }\n \n\tvector<vector<int>> ShortestDistance(vector<vector<int>>&matrix){\n\t // Code here\n\t int n = matrix.size();\n\t bool flag = distanceRec(matrix, n, 0, 0);\n\t if (flag) {\n\t for (int i = 0; i < n; i++) {\n\t for (int j = 0; j < n; j++) {\n\t if(matrix[i][j] == -1) matrix[i][j] = 1;\n\t else matrix[i][j] = 0;\n\t }\n\t }\n\t return matrix;\n\t }\n\t else return {{-1}};\n\t \n\t}"
},
{
"code": null,
"e": 7582,
"s": 7436,
"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": 7618,
"s": 7582,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7628,
"s": 7618,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7638,
"s": 7628,
"text": "\nContest\n"
},
{
"code": null,
"e": 7701,
"s": 7638,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7886,
"s": 7701,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 8170,
"s": 7886,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 8316,
"s": 8170,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 8393,
"s": 8316,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 8434,
"s": 8393,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 8462,
"s": 8434,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 8533,
"s": 8462,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 8720,
"s": 8533,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Finding the outlier points from Matplotlib
|
28 Jan, 2021
Outliers are the data points that differ from other observations or those which lie at a distance from the other data. They are mainly generated due to some experimental error which may cause several problems in statistical analysis. While in a big dataset it is quite obvious that some data will be further from the sample mean. These outliers need to be found and handle wisely.
We can use boxplots for the necessary.
Above is a diagram of boxplot created to display the summary of data values along with its median, first quartile, third quartile, minimum and maximum. And the data points out of the lower and upper whiskers are outliers. In between the first and third quartile of whisker lies the interquartile region above which a vertical line passes known as the median. For further details refer to the blog Box plot using python. Following are the methods to find outliers from a boxplot :
1.Visualizing through matplotlib boxplot using plt.boxplot().
2.Using 1.5 IQR rule.
Example:
Python3
# Adding librariesimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt # random integers between 1 to 20arr = np.random.randint(1, 20, size=30) # two outliers takenarr1 = np.append(arr, [27, 30]) print('Thus the array becomes{}'.format(arr1))
Output:
array([4, 12, 15, 7, 13, 2, 12, 11, 10, 12, 15, 5, 9, 16, 17, 2, 10, 15, 4, 16, 14, 19, 12, 8, 13, 3, 16, 10, 1, 13, 27, 30])
Visualizing by matplotlib boxplot using plt.boxplot()
Python3
plt.boxplot(arr1)fig = plt.figure(figsize =(10, 7))plt.show()
Output:
So from the above figure, we can witness the two outliers.
1.5 IQR Rule
Steps in 1.5IQR rule:-
Finding the median, quartile, and interquartile regions
Calculate 1.5*IQR below the first quartile and check for low outliers.
Calculate 1.5*IQR above the third quartile and check for outliers.
Python
# finding the 1st quartileq1 = np.quantile(arr1, 0.25) # finding the 3rd quartileq3 = np.quantile(arr1, 0.75)med = np.median(arr1) # finding the iqr regioniqr = q3-q1 # finding upper and lower whiskersupper_bound = q3+(1.5*iqr)lower_bound = q1-(1.5*iqr)print(iqr, upper_bound, lower_bound)
Output:
8.25 26.375 -6.625
Python3
outliers = arr1[(arr1 <= lower_bound) | (arr1 >= upper_bound)]print('The following are the outliers in the boxplot:{}'.format(outliers))
Output:
The following are the outliers in the boxplot:[27 30]
Thus, the outliers have been detected using the rule. Now eliminating them and plotting a graph with the data points-
Python3
# boxplot of data within the whiskerarr2 = arr1[(arr1 >= lower_bound) & (arr1 <= upper_bound)]plt.figure(figsize=(12, 7))plt.boxplot(arr2)plt.show()
Output :
barnadipdey2510
Picked
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n28 Jan, 2021"
},
{
"code": null,
"e": 434,
"s": 53,
"text": "Outliers are the data points that differ from other observations or those which lie at a distance from the other data. They are mainly generated due to some experimental error which may cause several problems in statistical analysis. While in a big dataset it is quite obvious that some data will be further from the sample mean. These outliers need to be found and handle wisely."
},
{
"code": null,
"e": 473,
"s": 434,
"text": "We can use boxplots for the necessary."
},
{
"code": null,
"e": 953,
"s": 473,
"text": "Above is a diagram of boxplot created to display the summary of data values along with its median, first quartile, third quartile, minimum and maximum. And the data points out of the lower and upper whiskers are outliers. In between the first and third quartile of whisker lies the interquartile region above which a vertical line passes known as the median. For further details refer to the blog Box plot using python. Following are the methods to find outliers from a boxplot :"
},
{
"code": null,
"e": 1037,
"s": 953,
"text": "1.Visualizing through matplotlib boxplot using plt.boxplot().\n2.Using 1.5 IQR rule."
},
{
"code": null,
"e": 1046,
"s": 1037,
"text": "Example:"
},
{
"code": null,
"e": 1054,
"s": 1046,
"text": "Python3"
},
{
"code": "# Adding librariesimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt # random integers between 1 to 20arr = np.random.randint(1, 20, size=30) # two outliers takenarr1 = np.append(arr, [27, 30]) print('Thus the array becomes{}'.format(arr1))",
"e": 1313,
"s": 1054,
"text": null
},
{
"code": null,
"e": 1321,
"s": 1313,
"text": "Output:"
},
{
"code": null,
"e": 1455,
"s": 1321,
"text": "array([4, 12, 15, 7, 13, 2, 12, 11, 10, 12, 15, 5, 9, 16, 17, 2, 10, 15, 4, 16, 14, 19, 12, 8, 13, 3, 16, 10, 1, 13, 27, 30])"
},
{
"code": null,
"e": 1509,
"s": 1455,
"text": "Visualizing by matplotlib boxplot using plt.boxplot()"
},
{
"code": null,
"e": 1517,
"s": 1509,
"text": "Python3"
},
{
"code": "plt.boxplot(arr1)fig = plt.figure(figsize =(10, 7))plt.show()",
"e": 1579,
"s": 1517,
"text": null
},
{
"code": null,
"e": 1843,
"s": 1582,
"text": "Output: "
},
{
"code": null,
"e": 1906,
"s": 1847,
"text": "So from the above figure, we can witness the two outliers."
},
{
"code": null,
"e": 1921,
"s": 1908,
"text": "1.5 IQR Rule"
},
{
"code": null,
"e": 1944,
"s": 1921,
"text": "Steps in 1.5IQR rule:-"
},
{
"code": null,
"e": 2000,
"s": 1944,
"text": "Finding the median, quartile, and interquartile regions"
},
{
"code": null,
"e": 2071,
"s": 2000,
"text": "Calculate 1.5*IQR below the first quartile and check for low outliers."
},
{
"code": null,
"e": 2138,
"s": 2071,
"text": "Calculate 1.5*IQR above the third quartile and check for outliers."
},
{
"code": null,
"e": 2147,
"s": 2140,
"text": "Python"
},
{
"code": "# finding the 1st quartileq1 = np.quantile(arr1, 0.25) # finding the 3rd quartileq3 = np.quantile(arr1, 0.75)med = np.median(arr1) # finding the iqr regioniqr = q3-q1 # finding upper and lower whiskersupper_bound = q3+(1.5*iqr)lower_bound = q1-(1.5*iqr)print(iqr, upper_bound, lower_bound)",
"e": 2437,
"s": 2147,
"text": null
},
{
"code": null,
"e": 2445,
"s": 2437,
"text": "Output:"
},
{
"code": null,
"e": 2464,
"s": 2445,
"text": "8.25 26.375 -6.625"
},
{
"code": null,
"e": 2472,
"s": 2464,
"text": "Python3"
},
{
"code": "outliers = arr1[(arr1 <= lower_bound) | (arr1 >= upper_bound)]print('The following are the outliers in the boxplot:{}'.format(outliers))",
"e": 2609,
"s": 2472,
"text": null
},
{
"code": null,
"e": 2617,
"s": 2609,
"text": "Output:"
},
{
"code": null,
"e": 2671,
"s": 2617,
"text": "The following are the outliers in the boxplot:[27 30]"
},
{
"code": null,
"e": 2790,
"s": 2671,
"text": "Thus, the outliers have been detected using the rule. Now eliminating them and plotting a graph with the data points- "
},
{
"code": null,
"e": 2798,
"s": 2790,
"text": "Python3"
},
{
"code": "# boxplot of data within the whiskerarr2 = arr1[(arr1 >= lower_bound) & (arr1 <= upper_bound)]plt.figure(figsize=(12, 7))plt.boxplot(arr2)plt.show()",
"e": 2947,
"s": 2798,
"text": null
},
{
"code": null,
"e": 2956,
"s": 2947,
"text": "Output :"
},
{
"code": null,
"e": 2972,
"s": 2956,
"text": "barnadipdey2510"
},
{
"code": null,
"e": 2979,
"s": 2972,
"text": "Picked"
},
{
"code": null,
"e": 2997,
"s": 2979,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 3021,
"s": 2997,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3028,
"s": 3021,
"text": "Python"
},
{
"code": null,
"e": 3047,
"s": 3028,
"text": "Technical Scripter"
}
] |
Order DataFrame rows according to vector with specific order in R
|
26 Mar, 2021
In this article, we will see how to sort data frame rows based on the values of a vector with a specific order. There are two functions by which we can sort data frame rows based on the values of a vector.
match() function
left_join() function
Example dataset:
data <- data.frame(x1 = 1:5,
x2 = letters[1:5],
x3 = 6:10)
data
x1 x2 x3
1 1 a 6
2 2 b 7
3 3 c 8
4 4 d 9
5 5 e 10
Vector with specific ordering:
vec <- c("b", "e", "a", "c", "d")
vec
# "b" "e" "a" "c" "d"
Method 1: Using match() function to Sort Data Frame According to Vector.
Match returns a vector of the positions of (first) matches of its first argument in its second.
Syntax: match(x, table, nomatch = NA_integer_, incomparables = NULL)
Parameters:
X: Vector or NULL: the values to be matched. Long vectors are supported.
table: vector or NULL: the values to be matched against. Long vectors are not supported.
nomatch: the value to be returned in the case when no match is found. Note that it is coerced to integer.
incomparables: A vector of values that cannot be matched. Any value in x matching a value in this vector is assigned the nomatch value. For historical reasons, FALSE is equivalent to NULL.
Code:
R
data <- data.frame(x1 = 1:5, x2 = letters[1:5], x3 = 6:10)vec <- c("b", "e", "a", "c", "d") new_dataset <- data[match(vec, data$x2), ] new_dataset
Output:
x1 x2 x3
2 2 b 7
5 5 e 10
1 1 a 6
3 3 c 8
4 4 d 9
As we can see from the above output the new data frame is sorted based on the values of the vector.
Method 2: Using left_join() Function of dplyr Package:
First, we have to install and load the dplyr package: now we can use left_join() method to sort the data frame based on the values on the vector.
Syntax: left_join(x, y, by = NULL, copy = FALSE, suffix = c(“.x”, “.y”), ...)
Parameters:
x, y: tbls to join
by: a character vector of variables to join by. If NULL, the default, *_join() will do a natural join, using all variables with common names across the two tables. A message lists the variables so that you can check they’re right (to suppress the message, simply explicitly list the variables that you want to join).
copy: If x and y are not from the same data source, and copy is TRUE, then y will be copied into the same src as x. This allows you to join tables across srcs, but it is a potentially expensive operation so you must opt into it.
suffix: If there are non-joined duplicate variables in x and y, these suffixes will be added to the output to disambiguate them. Should be a character vector of length 2.
Code:
R
install.packages("dplyr") library("dplyr")data <- data.frame(x1 = 1:5, x2 = letters[ 1 : 5] , x3 = 6:10) vec <- c("b", "e", "a", "c", "d") new_dataset <- left_join(data.frame(x2 = vec), data, by = "x2")print(new_dataset)
Output:
x2 x1 x3
1 b 2 7
2 e 5 10
3 a 1 6
4 c 3 8
5 d 4 9
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Mar, 2021"
},
{
"code": null,
"e": 235,
"s": 28,
"text": "In this article, we will see how to sort data frame rows based on the values of a vector with a specific order. There are two functions by which we can sort data frame rows based on the values of a vector. "
},
{
"code": null,
"e": 252,
"s": 235,
"text": "match() function"
},
{
"code": null,
"e": 273,
"s": 252,
"text": "left_join() function"
},
{
"code": null,
"e": 290,
"s": 273,
"text": "Example dataset:"
},
{
"code": null,
"e": 525,
"s": 290,
"text": "data <- data.frame(x1 = 1:5, \n x2 = letters[1:5],\n x3 = 6:10)\n \ndata\n x1 x2 x3\n1 1 a 6\n2 2 b 7\n3 3 c 8\n4 4 d 9\n5 5 e 10"
},
{
"code": null,
"e": 556,
"s": 525,
"text": "Vector with specific ordering:"
},
{
"code": null,
"e": 674,
"s": 556,
"text": "vec <- c(\"b\", \"e\", \"a\", \"c\", \"d\") \nvec \n# \"b\" \"e\" \"a\" \"c\" \"d\""
},
{
"code": null,
"e": 747,
"s": 674,
"text": "Method 1: Using match() function to Sort Data Frame According to Vector."
},
{
"code": null,
"e": 843,
"s": 747,
"text": "Match returns a vector of the positions of (first) matches of its first argument in its second."
},
{
"code": null,
"e": 912,
"s": 843,
"text": "Syntax: match(x, table, nomatch = NA_integer_, incomparables = NULL)"
},
{
"code": null,
"e": 924,
"s": 912,
"text": "Parameters:"
},
{
"code": null,
"e": 997,
"s": 924,
"text": "X: Vector or NULL: the values to be matched. Long vectors are supported."
},
{
"code": null,
"e": 1086,
"s": 997,
"text": "table: vector or NULL: the values to be matched against. Long vectors are not supported."
},
{
"code": null,
"e": 1192,
"s": 1086,
"text": "nomatch: the value to be returned in the case when no match is found. Note that it is coerced to integer."
},
{
"code": null,
"e": 1381,
"s": 1192,
"text": "incomparables: A vector of values that cannot be matched. Any value in x matching a value in this vector is assigned the nomatch value. For historical reasons, FALSE is equivalent to NULL."
},
{
"code": null,
"e": 1387,
"s": 1381,
"text": "Code:"
},
{
"code": null,
"e": 1389,
"s": 1387,
"text": "R"
},
{
"code": "data <- data.frame(x1 = 1:5, x2 = letters[1:5], x3 = 6:10)vec <- c(\"b\", \"e\", \"a\", \"c\", \"d\") new_dataset <- data[match(vec, data$x2), ] new_dataset ",
"e": 1633,
"s": 1389,
"text": null
},
{
"code": null,
"e": 1641,
"s": 1633,
"text": "Output:"
},
{
"code": null,
"e": 1707,
"s": 1641,
"text": " x1 x2 x3\n2 2 b 7\n5 5 e 10\n1 1 a 6\n3 3 c 8\n4 4 d 9"
},
{
"code": null,
"e": 1807,
"s": 1707,
"text": "As we can see from the above output the new data frame is sorted based on the values of the vector."
},
{
"code": null,
"e": 1862,
"s": 1807,
"text": "Method 2: Using left_join() Function of dplyr Package:"
},
{
"code": null,
"e": 2008,
"s": 1862,
"text": "First, we have to install and load the dplyr package: now we can use left_join() method to sort the data frame based on the values on the vector."
},
{
"code": null,
"e": 2086,
"s": 2008,
"text": "Syntax: left_join(x, y, by = NULL, copy = FALSE, suffix = c(“.x”, “.y”), ...)"
},
{
"code": null,
"e": 2098,
"s": 2086,
"text": "Parameters:"
},
{
"code": null,
"e": 2117,
"s": 2098,
"text": "x, y: tbls to join"
},
{
"code": null,
"e": 2434,
"s": 2117,
"text": "by: a character vector of variables to join by. If NULL, the default, *_join() will do a natural join, using all variables with common names across the two tables. A message lists the variables so that you can check they’re right (to suppress the message, simply explicitly list the variables that you want to join)."
},
{
"code": null,
"e": 2663,
"s": 2434,
"text": "copy: If x and y are not from the same data source, and copy is TRUE, then y will be copied into the same src as x. This allows you to join tables across srcs, but it is a potentially expensive operation so you must opt into it."
},
{
"code": null,
"e": 2834,
"s": 2663,
"text": "suffix: If there are non-joined duplicate variables in x and y, these suffixes will be added to the output to disambiguate them. Should be a character vector of length 2."
},
{
"code": null,
"e": 2840,
"s": 2834,
"text": "Code:"
},
{
"code": null,
"e": 2842,
"s": 2840,
"text": "R"
},
{
"code": "install.packages(\"dplyr\") library(\"dplyr\")data <- data.frame(x1 = 1:5, x2 = letters[ 1 : 5] , x3 = 6:10) vec <- c(\"b\", \"e\", \"a\", \"c\", \"d\") new_dataset <- left_join(data.frame(x2 = vec), data, by = \"x2\")print(new_dataset) ",
"e": 3215,
"s": 2842,
"text": null
},
{
"code": null,
"e": 3223,
"s": 3215,
"text": "Output:"
},
{
"code": null,
"e": 3288,
"s": 3223,
"text": " x2 x1 x3\n1 b 2 7\n2 e 5 10\n3 a 1 6\n4 c 3 8\n5 d 4 9"
},
{
"code": null,
"e": 3295,
"s": 3288,
"text": "Picked"
},
{
"code": null,
"e": 3316,
"s": 3295,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 3328,
"s": 3316,
"text": "R-DataFrame"
},
{
"code": null,
"e": 3339,
"s": 3328,
"text": "R Language"
},
{
"code": null,
"e": 3350,
"s": 3339,
"text": "R Programs"
}
] |
Character Classification in C++ : cctype - GeeksforGeeks
|
08 Mar, 2022
Character classification in C++ is possible using functions specified in function library. These functions are included in the <cctype> header file.
Numerous functions to classify characters are discussed below:1. isalpha(): This function returns true if the character is an alphabet else returns false. All the characters from a-z and A-Z return true according to this function.
Syntax:
int isalpha ( char c );
Example:
C++
// C++ program to demonstrate isalpha()#include <cctype>#include <iostream>using namespace std; // Driver Codeint main(){ // initializing character array char ch[5] = "g1"; // checking for isalpha() function for (int i = 0; i < 2; i++) { if (isalpha(ch[i])) cout << ch[i] << " is alphabet" << endl; else cout << ch[i] << " is not alphabet" << endl; }}
g is alphabet
1 is not alphabet
2. isalnum(): This function returns true if the character is an alphabet or a number else returns false. All the characters from a-z, A-Z, and all numbers return true according to this function.
Syntax:
int isalnum ( char c );
Example:
C++
// C++ program to demonstrate isalnum()#include <cctype>#include <iostream>using namespace std; // Driver Codeint main(){ // initializing character array char ch[5] = "g1"; // checking for isalnum() function for (int i = 0; i < 2; i++) { if (isalnum(ch[i])) cout << ch[i] << " is alphanumeric" << endl; else cout << ch[i] << " is not alphanumeric" << endl; }}
g is alphanumeric
1 is alphanumeric
3. isdigit(): This function returns true if the character is a number else returns false. All Numbers return true according to this function.
Syntax:
int isdigit ( char c );
Example:
CPP
// C++ program to demonstrate isdigit()#include <cctype>#include <iostream>using namespace std; int main(){ // initializing character array char ch[5] = "g1"; // checking for isdigit() function for (int i = 0; i < 2; i++) { if (isdigit(ch[i])) cout << ch[i] << " is digit" << endl; else cout << ch[i] << " is not digit" << endl; }}
g is not digit
1 is digit
4. isblank(): This function returns true if the character is a space or tab else returns false.
Syntax:
int isblank ( char c );
Example:
C++
// C++ program to demonstrate isblank()#include <cctype>#include <iostream>using namespace std; // Driver Codeint main(){ // initializing character array char ch[4] = " \n\t"; // checking for isblank() function for (int i = 0; i < 3; i++) { if (isblank(ch[i])) cout << " Character is blank" << endl; else cout << " Character is not blank" << endl; }}
Character is blank
Character is not blank
Character is blank
5. isspace(): This function returns true if the character is a space or tab or whitespace control code ( Eg.\n,\r ) else returns false.
Syntax:
int isspace ( char c );
Example:
C++
// C++ program to demonstrate isspace()#include <cctype>#include <iostream>using namespace std; // Driver Codeint main(){ // initializing character array char ch[4] = " \n\t"; // checking for isspace() function for (int i = 0; i < 3; i++) { if (isspace(ch[i])) cout << " Character is space" << endl; else cout << " Character is not space" << endl; }}
Character is space
Character is space
Character is space
6. iscntrl(): This function returns true if the character is tab or any control code else returns false.
Syntax:
int iscntrl ( char c );
Example:
CPP
// C++ program to demonstrate iscntrl()#include <cctype>#include <iostream>using namespace std; // Driver Codeint main(){ // initializing character array char ch[4] = " \n\t"; // checking for iscntrl() function for (int i = 0; i < 3; i++) { if (iscntrl(ch[i])) cout << " Character is control code " << endl; else cout << " Character is not control code" << endl; }}
Character is not control code
Character is control code
Character is control code
7. isprint(): This function returns true if the character is printable on the console i.e. all characters except control code else return false.
Syntax:
int isprint ( char c );
Example:
C++
// C++ program to demonstrate isprint()#include <cctype>#include <iostream>using namespace std; // Driver Codeint main(){ // initializing character array char ch[6] = "\t@gf1"; // checking for isprint() function for (int i = 0; i < 5; i++) { if (isprint(ch[i])) cout << ch[i] << " is printable character " << endl; else cout << ch[i] << " is not printable Character" << endl; }}
is not printable Character
@ is printable character
g is printable character
f is printable character
1 is printable character
8. isxdigit(): This function returns true if character is hexadecimal i.e 0-9 and a-f else returns false.
Syntax:
int isxdigit ( char c );
Example:
C++
// C++ program to demonstrate isxdigit()#include <cctype>#include <iostream>using namespace std; // Driver Codeint main(){ // initializing character array char ch[6] = "\t@gf1"; // checking for isxdigit() function for (int i = 0; i < 5; i++) { if (isxdigit(ch[i])) cout << ch[i] << " is hexadecimal Character" << endl; else cout << ch[i] << " is not hexadecimal Character" << endl; }}
is not hexadecimal Character
@ is not hexadecimal Character
g is not hexadecimal Character
f is hexadecimal Character
1 is hexadecimal Character
9. ispunct(): This function returns true if the character is punctuation mark else returns false.
Syntax:
int ispunct ( char c );
Example:
CPP
// C++ program to demonstrate ispunct()#include <cctype>#include <iostream>using namespace std; // Driver Codeint main(){ // initializing character array char ch[6] = "\t@gf1"; // checking for ispunct() function for (int i = 0; i < 5; i++) { if (ispunct(ch[i])) cout << ch[i] << " is punctuation mark" << endl; else cout << ch[i] << " is not punctuation mark" << endl; }}
is not punctuation mark
@ is punctuation mark
g is not punctuation mark
f is not punctuation mark
1 is not punctuation mark
This article is contributed by Manjeet Singh(S.Nandini). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
anshikajain26
simmytarika5
CPP-Library
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Map in C++ Standard Template Library (STL)
Bitwise Operators in C/C++
Operator Overloading in C++
Constructors in C++
Templates in C++ with Examples
vector erase() and clear() in C++
Socket Programming in C/C++
Substring in C++
Multidimensional Arrays in C / C++
Copy Constructor in C++
|
[
{
"code": null,
"e": 25521,
"s": 25493,
"text": "\n08 Mar, 2022"
},
{
"code": null,
"e": 25670,
"s": 25521,
"text": "Character classification in C++ is possible using functions specified in function library. These functions are included in the <cctype> header file."
},
{
"code": null,
"e": 25901,
"s": 25670,
"text": "Numerous functions to classify characters are discussed below:1. isalpha(): This function returns true if the character is an alphabet else returns false. All the characters from a-z and A-Z return true according to this function."
},
{
"code": null,
"e": 25909,
"s": 25901,
"text": "Syntax:"
},
{
"code": null,
"e": 25933,
"s": 25909,
"text": "int isalpha ( char c );"
},
{
"code": null,
"e": 25942,
"s": 25933,
"text": "Example:"
},
{
"code": null,
"e": 25946,
"s": 25942,
"text": "C++"
},
{
"code": "// C++ program to demonstrate isalpha()#include <cctype>#include <iostream>using namespace std; // Driver Codeint main(){ // initializing character array char ch[5] = \"g1\"; // checking for isalpha() function for (int i = 0; i < 2; i++) { if (isalpha(ch[i])) cout << ch[i] << \" is alphabet\" << endl; else cout << ch[i] << \" is not alphabet\" << endl; }}",
"e": 26350,
"s": 25946,
"text": null
},
{
"code": null,
"e": 26382,
"s": 26350,
"text": "g is alphabet\n1 is not alphabet"
},
{
"code": null,
"e": 26577,
"s": 26382,
"text": "2. isalnum(): This function returns true if the character is an alphabet or a number else returns false. All the characters from a-z, A-Z, and all numbers return true according to this function."
},
{
"code": null,
"e": 26585,
"s": 26577,
"text": "Syntax:"
},
{
"code": null,
"e": 26609,
"s": 26585,
"text": "int isalnum ( char c );"
},
{
"code": null,
"e": 26618,
"s": 26609,
"text": "Example:"
},
{
"code": null,
"e": 26622,
"s": 26618,
"text": "C++"
},
{
"code": "// C++ program to demonstrate isalnum()#include <cctype>#include <iostream>using namespace std; // Driver Codeint main(){ // initializing character array char ch[5] = \"g1\"; // checking for isalnum() function for (int i = 0; i < 2; i++) { if (isalnum(ch[i])) cout << ch[i] << \" is alphanumeric\" << endl; else cout << ch[i] << \" is not alphanumeric\" << endl; }}",
"e": 27034,
"s": 26622,
"text": null
},
{
"code": null,
"e": 27070,
"s": 27034,
"text": "g is alphanumeric\n1 is alphanumeric"
},
{
"code": null,
"e": 27212,
"s": 27070,
"text": "3. isdigit(): This function returns true if the character is a number else returns false. All Numbers return true according to this function."
},
{
"code": null,
"e": 27220,
"s": 27212,
"text": "Syntax:"
},
{
"code": null,
"e": 27244,
"s": 27220,
"text": "int isdigit ( char c );"
},
{
"code": null,
"e": 27253,
"s": 27244,
"text": "Example:"
},
{
"code": null,
"e": 27257,
"s": 27253,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate isdigit()#include <cctype>#include <iostream>using namespace std; int main(){ // initializing character array char ch[5] = \"g1\"; // checking for isdigit() function for (int i = 0; i < 2; i++) { if (isdigit(ch[i])) cout << ch[i] << \" is digit\" << endl; else cout << ch[i] << \" is not digit\" << endl; }}",
"e": 27641,
"s": 27257,
"text": null
},
{
"code": null,
"e": 27667,
"s": 27641,
"text": "g is not digit\n1 is digit"
},
{
"code": null,
"e": 27763,
"s": 27667,
"text": "4. isblank(): This function returns true if the character is a space or tab else returns false."
},
{
"code": null,
"e": 27771,
"s": 27763,
"text": "Syntax:"
},
{
"code": null,
"e": 27795,
"s": 27771,
"text": "int isblank ( char c );"
},
{
"code": null,
"e": 27804,
"s": 27795,
"text": "Example:"
},
{
"code": null,
"e": 27808,
"s": 27804,
"text": "C++"
},
{
"code": "// C++ program to demonstrate isblank()#include <cctype>#include <iostream>using namespace std; // Driver Codeint main(){ // initializing character array char ch[4] = \" \\n\\t\"; // checking for isblank() function for (int i = 0; i < 3; i++) { if (isblank(ch[i])) cout << \" Character is blank\" << endl; else cout << \" Character is not blank\" << endl; }}",
"e": 28211,
"s": 27808,
"text": null
},
{
"code": null,
"e": 28275,
"s": 28211,
"text": " Character is blank\n Character is not blank\n Character is blank"
},
{
"code": null,
"e": 28411,
"s": 28275,
"text": "5. isspace(): This function returns true if the character is a space or tab or whitespace control code ( Eg.\\n,\\r ) else returns false."
},
{
"code": null,
"e": 28419,
"s": 28411,
"text": "Syntax:"
},
{
"code": null,
"e": 28443,
"s": 28419,
"text": "int isspace ( char c );"
},
{
"code": null,
"e": 28452,
"s": 28443,
"text": "Example:"
},
{
"code": null,
"e": 28456,
"s": 28452,
"text": "C++"
},
{
"code": "// C++ program to demonstrate isspace()#include <cctype>#include <iostream>using namespace std; // Driver Codeint main(){ // initializing character array char ch[4] = \" \\n\\t\"; // checking for isspace() function for (int i = 0; i < 3; i++) { if (isspace(ch[i])) cout << \" Character is space\" << endl; else cout << \" Character is not space\" << endl; }}",
"e": 28859,
"s": 28456,
"text": null
},
{
"code": null,
"e": 28919,
"s": 28859,
"text": " Character is space\n Character is space\n Character is space"
},
{
"code": null,
"e": 29024,
"s": 28919,
"text": "6. iscntrl(): This function returns true if the character is tab or any control code else returns false."
},
{
"code": null,
"e": 29032,
"s": 29024,
"text": "Syntax:"
},
{
"code": null,
"e": 29056,
"s": 29032,
"text": "int iscntrl ( char c );"
},
{
"code": null,
"e": 29065,
"s": 29056,
"text": "Example:"
},
{
"code": null,
"e": 29069,
"s": 29065,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate iscntrl()#include <cctype>#include <iostream>using namespace std; // Driver Codeint main(){ // initializing character array char ch[4] = \" \\n\\t\"; // checking for iscntrl() function for (int i = 0; i < 3; i++) { if (iscntrl(ch[i])) cout << \" Character is control code \" << endl; else cout << \" Character is not control code\" << endl; }}",
"e": 29503,
"s": 29069,
"text": null
},
{
"code": null,
"e": 29590,
"s": 29503,
"text": " Character is not control code\n Character is control code \n Character is control code "
},
{
"code": null,
"e": 29735,
"s": 29590,
"text": "7. isprint(): This function returns true if the character is printable on the console i.e. all characters except control code else return false."
},
{
"code": null,
"e": 29743,
"s": 29735,
"text": "Syntax:"
},
{
"code": null,
"e": 29767,
"s": 29743,
"text": "int isprint ( char c );"
},
{
"code": null,
"e": 29776,
"s": 29767,
"text": "Example:"
},
{
"code": null,
"e": 29780,
"s": 29776,
"text": "C++"
},
{
"code": "// C++ program to demonstrate isprint()#include <cctype>#include <iostream>using namespace std; // Driver Codeint main(){ // initializing character array char ch[6] = \"\\t@gf1\"; // checking for isprint() function for (int i = 0; i < 5; i++) { if (isprint(ch[i])) cout << ch[i] << \" is printable character \" << endl; else cout << ch[i] << \" is not printable Character\" << endl; }}",
"e": 30243,
"s": 29780,
"text": null
},
{
"code": null,
"e": 30379,
"s": 30243,
"text": " is not printable Character\n@ is printable character \ng is printable character \nf is printable character \n1 is printable character "
},
{
"code": null,
"e": 30485,
"s": 30379,
"text": "8. isxdigit(): This function returns true if character is hexadecimal i.e 0-9 and a-f else returns false."
},
{
"code": null,
"e": 30493,
"s": 30485,
"text": "Syntax:"
},
{
"code": null,
"e": 30518,
"s": 30493,
"text": "int isxdigit ( char c );"
},
{
"code": null,
"e": 30527,
"s": 30518,
"text": "Example:"
},
{
"code": null,
"e": 30531,
"s": 30527,
"text": "C++"
},
{
"code": "// C++ program to demonstrate isxdigit()#include <cctype>#include <iostream>using namespace std; // Driver Codeint main(){ // initializing character array char ch[6] = \"\\t@gf1\"; // checking for isxdigit() function for (int i = 0; i < 5; i++) { if (isxdigit(ch[i])) cout << ch[i] << \" is hexadecimal Character\" << endl; else cout << ch[i] << \" is not hexadecimal Character\" << endl; }}",
"e": 31000,
"s": 30531,
"text": null
},
{
"code": null,
"e": 31150,
"s": 31000,
"text": " is not hexadecimal Character\n@ is not hexadecimal Character\ng is not hexadecimal Character\nf is hexadecimal Character\n1 is hexadecimal Character"
},
{
"code": null,
"e": 31248,
"s": 31150,
"text": "9. ispunct(): This function returns true if the character is punctuation mark else returns false."
},
{
"code": null,
"e": 31256,
"s": 31248,
"text": "Syntax:"
},
{
"code": null,
"e": 31280,
"s": 31256,
"text": "int ispunct ( char c );"
},
{
"code": null,
"e": 31289,
"s": 31280,
"text": "Example:"
},
{
"code": null,
"e": 31293,
"s": 31289,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate ispunct()#include <cctype>#include <iostream>using namespace std; // Driver Codeint main(){ // initializing character array char ch[6] = \"\\t@gf1\"; // checking for ispunct() function for (int i = 0; i < 5; i++) { if (ispunct(ch[i])) cout << ch[i] << \" is punctuation mark\" << endl; else cout << ch[i] << \" is not punctuation mark\" << endl; }}",
"e": 31733,
"s": 31293,
"text": null
},
{
"code": null,
"e": 31862,
"s": 31733,
"text": " is not punctuation mark\n@ is punctuation mark\ng is not punctuation mark\nf is not punctuation mark\n1 is not punctuation mark"
},
{
"code": null,
"e": 32295,
"s": 31862,
"text": "This article is contributed by Manjeet Singh(S.Nandini). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 32309,
"s": 32295,
"text": "anshikajain26"
},
{
"code": null,
"e": 32322,
"s": 32309,
"text": "simmytarika5"
},
{
"code": null,
"e": 32334,
"s": 32322,
"text": "CPP-Library"
},
{
"code": null,
"e": 32338,
"s": 32334,
"text": "C++"
},
{
"code": null,
"e": 32342,
"s": 32338,
"text": "CPP"
},
{
"code": null,
"e": 32440,
"s": 32342,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32483,
"s": 32440,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 32510,
"s": 32483,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 32538,
"s": 32510,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 32558,
"s": 32538,
"text": "Constructors in C++"
},
{
"code": null,
"e": 32589,
"s": 32558,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 32623,
"s": 32589,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 32651,
"s": 32623,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 32668,
"s": 32651,
"text": "Substring in C++"
},
{
"code": null,
"e": 32703,
"s": 32668,
"text": "Multidimensional Arrays in C / C++"
}
] |
CPU control design and Interfaces - GeeksforGeeks
|
19 Nov, 2018
MBR ← PC
MAR ← X
PC ← Y
Memory ← MBR
I. Function locals and parameters
II. Register saves and restores
III. Instruction fetches
M [SP]
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Replace Values in a List in Python?
Epam Interview Experience for Junior Software Engineer
EPAM Interview Experience | On-Campus 2022
How to Read Text Files with Pandas?
Python Data Structures and Algorithms
Data Science With Python Tutorial
Top 10 Programming Languages to Learn in 2022
|
[
{
"code": null,
"e": 28855,
"s": 28827,
"text": "\n19 Nov, 2018"
},
{
"code": null,
"e": 28917,
"s": 28855,
"text": " MBR ← PC \n MAR ← X \n PC ← Y \n Memory ← MBR"
},
{
"code": null,
"e": 29011,
"s": 28917,
"text": "I. Function locals and parameters\nII. Register saves and restores\nIII. Instruction fetches "
},
{
"code": null,
"e": 29020,
"s": 29011,
"text": " M [SP]"
},
{
"code": null,
"e": 29118,
"s": 29020,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 29171,
"s": 29118,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 29233,
"s": 29171,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 29274,
"s": 29233,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 29317,
"s": 29274,
"text": "How to Replace Values in a List in Python?"
},
{
"code": null,
"e": 29372,
"s": 29317,
"text": "Epam Interview Experience for Junior Software Engineer"
},
{
"code": null,
"e": 29415,
"s": 29372,
"text": "EPAM Interview Experience | On-Campus 2022"
},
{
"code": null,
"e": 29451,
"s": 29415,
"text": "How to Read Text Files with Pandas?"
},
{
"code": null,
"e": 29489,
"s": 29451,
"text": "Python Data Structures and Algorithms"
},
{
"code": null,
"e": 29523,
"s": 29489,
"text": "Data Science With Python Tutorial"
}
] |
Bootstrap .btn-link class
|
Deemphasize a button by making it look like a link while maintaining button behavior using the btn-link class in Bootstrap −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<button type = "button" class = "btn btn-link">Link Button</button>
</body>
</html>
|
[
{
"code": null,
"e": 1187,
"s": 1062,
"text": "Deemphasize a button by making it look like a link while maintaining button behavior using the btn-link class in Bootstrap −"
},
{
"code": null,
"e": 1197,
"s": 1187,
"text": "Live Demo"
},
{
"code": null,
"e": 1780,
"s": 1197,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <button type = \"button\" class = \"btn btn-link\">Link Button</button>\n </body>\n</html>"
}
] |
Make an element invisible with Bootstrap
|
To make an element invisible with Bootstrap, use the invisible class.
You can try to run the following code to hide an element −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "container">
<h2>Cricket Boards</h2>
<p>The <abbr title = "International Cricket Council">ICC</abbr> governs cricket boards.</p>
<p class = "invisible">BCCI is also governed by ICC. (This element is invisible)</p>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1132,
"s": 1062,
"text": "To make an element invisible with Bootstrap, use the invisible class."
},
{
"code": null,
"e": 1191,
"s": 1132,
"text": "You can try to run the following code to hide an element −"
},
{
"code": null,
"e": 1201,
"s": 1191,
"text": "Live Demo"
},
{
"code": null,
"e": 1778,
"s": 1201,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container\">\n <h2>Cricket Boards</h2>\n <p>The <abbr title = \"International Cricket Council\">ICC</abbr> governs cricket boards.</p>\n <p class = \"invisible\">BCCI is also governed by ICC. (This element is invisible)</p>\n </div>\n </body>\n</html>"
}
] |
Reverse Vowels of a string in C++
|
Given a string, the task is to reverse all the vowels present in the given string. For example,
Input-1 −
a = “tutor”
Output −
totur
Explanation − Reversing the string “tutor” will generate the output as “totur.
Input-2 −
a = “mathematics”
Output −
mithametacs
Explanation − Reversing the string “mathematics” will generate the output as “mithametacs”.
Given a string, we have to reverse all the vowels present in it. There are several approaches to solve this particular problem but we have to solve this in linear time O(n).
Thus, the better method to solve this problem is to use the Two-Pointer approach in which we will take two pointers low and high which will be pointing initially to the leftmost element and rightmost element. In two nested loops, we will check if the leftmost character is a vowel and the rightmost character is vowel also then swap the element and move the right pointer.
Take input a string.
Take input a string.
A Boolean function to check if the character is a vowel or not.
A Boolean function to check if the character is a vowel or not.
A function reverseVowel(string &str) takes a string as input and reverse the vowels present in the string.
A function reverseVowel(string &str) takes a string as input and reverse the vowels present in the string.
Initialize two pointers low and high which point to ‘0’ and last character respectively.
Initialize two pointers low and high which point to ‘0’ and last character respectively.
Checking the leftmost and rightmost characters if they are vowels then swap the character in-place and decrement the rightmost pointer.
Checking the leftmost and rightmost characters if they are vowels then swap the character in-place and decrement the rightmost pointer.
Repeating the steps until all the characters of the string are not visited.
Repeating the steps until all the characters of the string are not visited.
Live Demo
#include <bits/stdc++.h>
using namespace std;
bool isVowel(char ch) {
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U';
}
string reverseVowel(string &s){
int low = 0;
int high = s.size() - 1;
while (low < high) {
while (low < high && !isVowel(s[low])) {
low ++;
}
while (low < high && !isVowel(s[high])) {
high --;
}
swap(s[low++], s[high--]);
}
return s;
}
int main(){
string a= "tutorialspoint";
string ans= reverseVowel(a);
cout<<ans;
return 0;
}
Running the above code will generate the output as,
titorailspount
Since the given string “tutorialspoint” contains vowels, after reversing the vowels, it will generate the output as, “titorailspount”.
|
[
{
"code": null,
"e": 1158,
"s": 1062,
"text": "Given a string, the task is to reverse all the vowels present in the given string. For example,"
},
{
"code": null,
"e": 1168,
"s": 1158,
"text": "Input-1 −"
},
{
"code": null,
"e": 1180,
"s": 1168,
"text": "a = “tutor”"
},
{
"code": null,
"e": 1189,
"s": 1180,
"text": "Output −"
},
{
"code": null,
"e": 1195,
"s": 1189,
"text": "totur"
},
{
"code": null,
"e": 1274,
"s": 1195,
"text": "Explanation − Reversing the string “tutor” will generate the output as “totur."
},
{
"code": null,
"e": 1284,
"s": 1274,
"text": "Input-2 −"
},
{
"code": null,
"e": 1302,
"s": 1284,
"text": "a = “mathematics”"
},
{
"code": null,
"e": 1311,
"s": 1302,
"text": "Output −"
},
{
"code": null,
"e": 1323,
"s": 1311,
"text": "mithametacs"
},
{
"code": null,
"e": 1415,
"s": 1323,
"text": "Explanation − Reversing the string “mathematics” will generate the output as “mithametacs”."
},
{
"code": null,
"e": 1589,
"s": 1415,
"text": "Given a string, we have to reverse all the vowels present in it. There are several approaches to solve this particular problem but we have to solve this in linear time O(n)."
},
{
"code": null,
"e": 1962,
"s": 1589,
"text": "Thus, the better method to solve this problem is to use the Two-Pointer approach in which we will take two pointers low and high which will be pointing initially to the leftmost element and rightmost element. In two nested loops, we will check if the leftmost character is a vowel and the rightmost character is vowel also then swap the element and move the right pointer."
},
{
"code": null,
"e": 1983,
"s": 1962,
"text": "Take input a string."
},
{
"code": null,
"e": 2004,
"s": 1983,
"text": "Take input a string."
},
{
"code": null,
"e": 2068,
"s": 2004,
"text": "A Boolean function to check if the character is a vowel or not."
},
{
"code": null,
"e": 2132,
"s": 2068,
"text": "A Boolean function to check if the character is a vowel or not."
},
{
"code": null,
"e": 2239,
"s": 2132,
"text": "A function reverseVowel(string &str) takes a string as input and reverse the vowels present in the string."
},
{
"code": null,
"e": 2346,
"s": 2239,
"text": "A function reverseVowel(string &str) takes a string as input and reverse the vowels present in the string."
},
{
"code": null,
"e": 2435,
"s": 2346,
"text": "Initialize two pointers low and high which point to ‘0’ and last character respectively."
},
{
"code": null,
"e": 2524,
"s": 2435,
"text": "Initialize two pointers low and high which point to ‘0’ and last character respectively."
},
{
"code": null,
"e": 2660,
"s": 2524,
"text": "Checking the leftmost and rightmost characters if they are vowels then swap the character in-place and decrement the rightmost pointer."
},
{
"code": null,
"e": 2796,
"s": 2660,
"text": "Checking the leftmost and rightmost characters if they are vowels then swap the character in-place and decrement the rightmost pointer."
},
{
"code": null,
"e": 2872,
"s": 2796,
"text": "Repeating the steps until all the characters of the string are not visited."
},
{
"code": null,
"e": 2948,
"s": 2872,
"text": "Repeating the steps until all the characters of the string are not visited."
},
{
"code": null,
"e": 2959,
"s": 2948,
"text": " Live Demo"
},
{
"code": null,
"e": 3572,
"s": 2959,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nbool isVowel(char ch) {\n return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U';\n}\nstring reverseVowel(string &s){\n int low = 0;\n int high = s.size() - 1;\n while (low < high) {\n while (low < high && !isVowel(s[low])) {\n low ++;\n }\n while (low < high && !isVowel(s[high])) {\n high --;\n }\n swap(s[low++], s[high--]);\n }\n return s;\n}\nint main(){\n string a= \"tutorialspoint\";\n string ans= reverseVowel(a);\n cout<<ans;\n return 0;\n}"
},
{
"code": null,
"e": 3624,
"s": 3572,
"text": "Running the above code will generate the output as,"
},
{
"code": null,
"e": 3639,
"s": 3624,
"text": "titorailspount"
},
{
"code": null,
"e": 3774,
"s": 3639,
"text": "Since the given string “tutorialspoint” contains vowels, after reversing the vowels, it will generate the output as, “titorailspount”."
}
] |
What is Boosting in Machine Learning? | by z_ai | Towards Data Science
|
In this post, we will see a simple and intuitive explanation of Boosting algorithms: what they are, why they are so powerful, some of the different types, and how they are trained and used to make predictions.
We will avoid all the heavy maths and go for a clear, simple, but in depth explanation that can be easily understood. However, additional material and resources will be left at the end of the post, in case you want to dive further into the topic.
Before we start, here you have some additional resources to skyrocket your Machine Learning career
Awesome Machine Learning Resources:- For learning resources go to How to Learn Machine Learning! - For professional resources (jobs, events, skill tests) go to AIgents.co — A career community for Data Scientists & Machine Learning Engineers
z-ai.medium.com
Traditionally, building a Machine Learning application consisted on taking a single learner, like a Logistic Regressor, a Decision Tree, Support Vector Machine, or an Artificial Neural Network, feeding it data, and teaching it to perform a certain task through this data.
Then ensemble methods were born, which involve using many learners to enhance the performance of any single one of them individually. These methods can be described as techniques that use a group of weak learners (those who on average achieve only slightly better results than a random model) together, in order to create a stronger, aggregated one.
Generally, ensemble methods are built by grouping variants of individual Decision Trees, as we will see later.
Boosting models fall inside this family of ensemble methods.
Boosting, initially named Hypothesis Boosting, consists on the idea of filtering or weighting the data that is used to train our team of weak learners, so that each new learner gives more weight or is only trained with observations that have been poorly classified by the previous learners.
By doing this our team of models learns to make accurate predictions on all kinds of data, not just on the most common or easy observations. Also, if one of the individual models is very bad at making predictions on some kind of observation, it does not matter, as the other N-1 models will most likely make up for it.
Boosting should not be confused with Bagging, which is the other main family of ensemble methods: while in bagging the weak learners are trained in parallel using randomness, in boosting the learners are trained sequentially, in order to be able to perform the task of data weighting/filtering described in the previous paragraph.
As we can see from the previous image, in boosting the models can have different importance or weights (represented in the different sizes of the learners), while in bagging all learners have the same weight in the final decision.
Also, in boosting, the data set is weighted (represented by the different sizes of the data points), so that observations that were incorrectly classified by classifier n are given more importance in the training of model n + 1, while in bagging the training samples are taken randomly from the whole population.
Now that we have seen what boosting is, and its differences with bagging, let's see why it works so well!
In general, ensemble methods reduce the bias and variance of our Machine Learning models. If you don’t know what bias and variance are don’t worry, I got you covered with this article.
Ensemble methods help increase the stability and performance of machine learning models by eliminating the dependency of a single estimator. This can be clearly seen with a Bagging example: Random Forest.
Random Forest are, as their name suggests, a group of individual Decision trees that make up a forest. These individual trees are quite prone to overfiting the data, and despite being very simple and intuitive models, they’re not so great at making predictions.
However, if we use many trees these problems disappear, as each tree is trained with different samples of data and different features, resulting in a stronger and more robust model overall.
With boosting, this works in the same way, but while in bagging each model is trained independently, in boosting the N models are trained sequentially, taking into account the success of the previous model and increasing the weights of the data that this previous model has had the highest error on, which makes the subsequent models focus on the most difficult data observations.
Also, the individual models that perform the best on the weighted training samples, will become stronger (get a higher weight), and therefore have a higher impact on the final prediction.
Alright, this sounds lovely, but how are these models actually trained?
The training process depends on the Boosting algorithm that we are using (Adaboost vs LigthGBM vs XGBoost...), but generally it follows this pattern:
All the data samples start with the same weights. These samples are used to train an individual model (a Decision Tree lets say).The prediction error for each sample is calculated, increasing the weights of those samples which have had a greater error, to make them more important for the training of following individual model.Depending on how well this individual model did on its predictions, it gets assigned an importance/weight or amount of say. A model that outputs very good predictions will have a high amount of say in the final decision.The weighted data is passed on to the posterior model, and 2) and 3) are repeated.Number 4) is repeated until we have reached an certain number of models or until the error is bellow a certain threshold.
All the data samples start with the same weights. These samples are used to train an individual model (a Decision Tree lets say).
The prediction error for each sample is calculated, increasing the weights of those samples which have had a greater error, to make them more important for the training of following individual model.
Depending on how well this individual model did on its predictions, it gets assigned an importance/weight or amount of say. A model that outputs very good predictions will have a high amount of say in the final decision.
The weighted data is passed on to the posterior model, and 2) and 3) are repeated.
Number 4) is repeated until we have reached an certain number of models or until the error is bellow a certain threshold.
In some cases, boosting models are trained with an specific fixed weight for each learner (called learning rate) and instead of giving each sample an individual weight, the models are trained trying to predict the differences between the previous predictions on the samples and the real values of the objective variable. This difference are what we call residuals.
We will speak about this more later, when we see the different kind of boosting models, however, the main characteristic of the family still remains: the sequential training on many individual learners to create a more powerful, aggregated model.
Awesome! Now that we know how Boosting models are trained, let's see how they are used to make predictions on new data.
They way a boosting model makes predictions on new data is very simple. When we get a new observation with its features, it is passed through every one of the individual models, having each model make its own prediction.
Then, taking into account the weight of each one of these models, all these predictions are scaled and combined, and a final global prediction is given.
To end, lets explore the characteristics of the most common Boosting models out there.
Short for Adaptive Boosting, AdaBoost works by the exact process described before of training sequentially, predicting, and updating the weights of the miss-classified samples and of the corresponding weak models.
It is mostly used with Decision Tree Stumps: decision trees with just a root node and two leave nodes, where only 1 feature of the data is evaluated. As we can see, by taking into account only 1 feature of our data to make predictions, each stump is a very very weak model. However, by combining many of them, a very robust and accurate ensemble model can be built.
If you want to know more about AdaBoost, check out the following video by StatQuest.
Very similar to AdaBoost, Gradient Boosting Machines train weak learners sequentially, adding more and more estimators, but instead of adapting the weights of the data, it tries to predict the residual errors made by the previous estimators.
Because of this, we no longer have sample weights, and all the weak models have the same amount of say or importance. Again, most times, Decision trees are used as the base predictors, however, they’re not stumps, but bigger, fixed sized trees. GBMs use a learning rate and takes a small steps towards better results, in a similar manner conceptually to what is done in Gradient Descent.
Again, if you wanna dive deeper, check out the video by StatQuest.
Short for eXtreme gradient boosting, like in Gradient boosting, we fit our trees to the residuals of the previous trees predictions, however, instead of using conventional, fixed size decision trees, XGBoost uses a different kind of trees: XGBoost trees we could call them.
It builds these trees by calculating similarity scores between the observations that end up in a leave node. Also, XGBoost allows for regularisation, reducing the possible overfitting of our individual trees and therefore of the overall ensemble model.
Lastly, XGBoost is optimised to push the limit of the computational resources of boosted tree algorithms, making it a very high performance and fast algorithm in terms of time and computation.
You can watch the following video XGBoost Part 1: Regression, to get a deeper vision of what XGBoost is all about.
Light Gradient Boosting Machines, known by the short name of LigthGBM, are yet another turnaround of improvements for Gradient Boosting algorithms. Instead of using a level-wise growing strategy for the decision trees like in XGBoost, it uses a leaf-wise growth strategy, giving it the chance to achieve a higher error reduction per jump than other tree based algorithms. Also, compared to XGBoost, LigthGBM is generally faster, specially on large data sets.
You can learn more about it on its official docu page.
z-ai.medium.com
That is it! As always, I hope you enjoyed the post, and that I managed to help you understand what boosting is, how it works, and why it is so powerful.
Here you can find some additional resources in case you want to learn more about the topic:
Thoughts on Hypothesis Boosting, Michael Kearns.
A Gentle Introduction to Gradient Boosting on MachineLearningMastery.
A Decision-Theoretic Generalization of On-Line Learning and an Application to Boosting
QuantDare: Boosting vs Bagging
The best Machine Learning books reviewed
If you liked this post then feel free to follow me on Twitter at @jaimezorno. Also, you can take a look at my other posts on Data Science and Machine Learning here. Have a good read!
If you want to learn more about Machine Learning and Artificial Intelligence follow me on Medium, and stay tuned for my next posts! Also, you can check out this repository for more resources on Machine Learning and AI!
Cover Image from Unsplash.
All other images are self made.
|
[
{
"code": null,
"e": 381,
"s": 171,
"text": "In this post, we will see a simple and intuitive explanation of Boosting algorithms: what they are, why they are so powerful, some of the different types, and how they are trained and used to make predictions."
},
{
"code": null,
"e": 628,
"s": 381,
"text": "We will avoid all the heavy maths and go for a clear, simple, but in depth explanation that can be easily understood. However, additional material and resources will be left at the end of the post, in case you want to dive further into the topic."
},
{
"code": null,
"e": 727,
"s": 628,
"text": "Before we start, here you have some additional resources to skyrocket your Machine Learning career"
},
{
"code": null,
"e": 968,
"s": 727,
"text": "Awesome Machine Learning Resources:- For learning resources go to How to Learn Machine Learning! - For professional resources (jobs, events, skill tests) go to AIgents.co — A career community for Data Scientists & Machine Learning Engineers"
},
{
"code": null,
"e": 984,
"s": 968,
"text": "z-ai.medium.com"
},
{
"code": null,
"e": 1256,
"s": 984,
"text": "Traditionally, building a Machine Learning application consisted on taking a single learner, like a Logistic Regressor, a Decision Tree, Support Vector Machine, or an Artificial Neural Network, feeding it data, and teaching it to perform a certain task through this data."
},
{
"code": null,
"e": 1606,
"s": 1256,
"text": "Then ensemble methods were born, which involve using many learners to enhance the performance of any single one of them individually. These methods can be described as techniques that use a group of weak learners (those who on average achieve only slightly better results than a random model) together, in order to create a stronger, aggregated one."
},
{
"code": null,
"e": 1717,
"s": 1606,
"text": "Generally, ensemble methods are built by grouping variants of individual Decision Trees, as we will see later."
},
{
"code": null,
"e": 1778,
"s": 1717,
"text": "Boosting models fall inside this family of ensemble methods."
},
{
"code": null,
"e": 2069,
"s": 1778,
"text": "Boosting, initially named Hypothesis Boosting, consists on the idea of filtering or weighting the data that is used to train our team of weak learners, so that each new learner gives more weight or is only trained with observations that have been poorly classified by the previous learners."
},
{
"code": null,
"e": 2388,
"s": 2069,
"text": "By doing this our team of models learns to make accurate predictions on all kinds of data, not just on the most common or easy observations. Also, if one of the individual models is very bad at making predictions on some kind of observation, it does not matter, as the other N-1 models will most likely make up for it."
},
{
"code": null,
"e": 2719,
"s": 2388,
"text": "Boosting should not be confused with Bagging, which is the other main family of ensemble methods: while in bagging the weak learners are trained in parallel using randomness, in boosting the learners are trained sequentially, in order to be able to perform the task of data weighting/filtering described in the previous paragraph."
},
{
"code": null,
"e": 2950,
"s": 2719,
"text": "As we can see from the previous image, in boosting the models can have different importance or weights (represented in the different sizes of the learners), while in bagging all learners have the same weight in the final decision."
},
{
"code": null,
"e": 3263,
"s": 2950,
"text": "Also, in boosting, the data set is weighted (represented by the different sizes of the data points), so that observations that were incorrectly classified by classifier n are given more importance in the training of model n + 1, while in bagging the training samples are taken randomly from the whole population."
},
{
"code": null,
"e": 3369,
"s": 3263,
"text": "Now that we have seen what boosting is, and its differences with bagging, let's see why it works so well!"
},
{
"code": null,
"e": 3554,
"s": 3369,
"text": "In general, ensemble methods reduce the bias and variance of our Machine Learning models. If you don’t know what bias and variance are don’t worry, I got you covered with this article."
},
{
"code": null,
"e": 3759,
"s": 3554,
"text": "Ensemble methods help increase the stability and performance of machine learning models by eliminating the dependency of a single estimator. This can be clearly seen with a Bagging example: Random Forest."
},
{
"code": null,
"e": 4021,
"s": 3759,
"text": "Random Forest are, as their name suggests, a group of individual Decision trees that make up a forest. These individual trees are quite prone to overfiting the data, and despite being very simple and intuitive models, they’re not so great at making predictions."
},
{
"code": null,
"e": 4211,
"s": 4021,
"text": "However, if we use many trees these problems disappear, as each tree is trained with different samples of data and different features, resulting in a stronger and more robust model overall."
},
{
"code": null,
"e": 4592,
"s": 4211,
"text": "With boosting, this works in the same way, but while in bagging each model is trained independently, in boosting the N models are trained sequentially, taking into account the success of the previous model and increasing the weights of the data that this previous model has had the highest error on, which makes the subsequent models focus on the most difficult data observations."
},
{
"code": null,
"e": 4780,
"s": 4592,
"text": "Also, the individual models that perform the best on the weighted training samples, will become stronger (get a higher weight), and therefore have a higher impact on the final prediction."
},
{
"code": null,
"e": 4852,
"s": 4780,
"text": "Alright, this sounds lovely, but how are these models actually trained?"
},
{
"code": null,
"e": 5002,
"s": 4852,
"text": "The training process depends on the Boosting algorithm that we are using (Adaboost vs LigthGBM vs XGBoost...), but generally it follows this pattern:"
},
{
"code": null,
"e": 5754,
"s": 5002,
"text": "All the data samples start with the same weights. These samples are used to train an individual model (a Decision Tree lets say).The prediction error for each sample is calculated, increasing the weights of those samples which have had a greater error, to make them more important for the training of following individual model.Depending on how well this individual model did on its predictions, it gets assigned an importance/weight or amount of say. A model that outputs very good predictions will have a high amount of say in the final decision.The weighted data is passed on to the posterior model, and 2) and 3) are repeated.Number 4) is repeated until we have reached an certain number of models or until the error is bellow a certain threshold."
},
{
"code": null,
"e": 5884,
"s": 5754,
"text": "All the data samples start with the same weights. These samples are used to train an individual model (a Decision Tree lets say)."
},
{
"code": null,
"e": 6084,
"s": 5884,
"text": "The prediction error for each sample is calculated, increasing the weights of those samples which have had a greater error, to make them more important for the training of following individual model."
},
{
"code": null,
"e": 6305,
"s": 6084,
"text": "Depending on how well this individual model did on its predictions, it gets assigned an importance/weight or amount of say. A model that outputs very good predictions will have a high amount of say in the final decision."
},
{
"code": null,
"e": 6388,
"s": 6305,
"text": "The weighted data is passed on to the posterior model, and 2) and 3) are repeated."
},
{
"code": null,
"e": 6510,
"s": 6388,
"text": "Number 4) is repeated until we have reached an certain number of models or until the error is bellow a certain threshold."
},
{
"code": null,
"e": 6875,
"s": 6510,
"text": "In some cases, boosting models are trained with an specific fixed weight for each learner (called learning rate) and instead of giving each sample an individual weight, the models are trained trying to predict the differences between the previous predictions on the samples and the real values of the objective variable. This difference are what we call residuals."
},
{
"code": null,
"e": 7122,
"s": 6875,
"text": "We will speak about this more later, when we see the different kind of boosting models, however, the main characteristic of the family still remains: the sequential training on many individual learners to create a more powerful, aggregated model."
},
{
"code": null,
"e": 7242,
"s": 7122,
"text": "Awesome! Now that we know how Boosting models are trained, let's see how they are used to make predictions on new data."
},
{
"code": null,
"e": 7463,
"s": 7242,
"text": "They way a boosting model makes predictions on new data is very simple. When we get a new observation with its features, it is passed through every one of the individual models, having each model make its own prediction."
},
{
"code": null,
"e": 7616,
"s": 7463,
"text": "Then, taking into account the weight of each one of these models, all these predictions are scaled and combined, and a final global prediction is given."
},
{
"code": null,
"e": 7703,
"s": 7616,
"text": "To end, lets explore the characteristics of the most common Boosting models out there."
},
{
"code": null,
"e": 7917,
"s": 7703,
"text": "Short for Adaptive Boosting, AdaBoost works by the exact process described before of training sequentially, predicting, and updating the weights of the miss-classified samples and of the corresponding weak models."
},
{
"code": null,
"e": 8283,
"s": 7917,
"text": "It is mostly used with Decision Tree Stumps: decision trees with just a root node and two leave nodes, where only 1 feature of the data is evaluated. As we can see, by taking into account only 1 feature of our data to make predictions, each stump is a very very weak model. However, by combining many of them, a very robust and accurate ensemble model can be built."
},
{
"code": null,
"e": 8368,
"s": 8283,
"text": "If you want to know more about AdaBoost, check out the following video by StatQuest."
},
{
"code": null,
"e": 8610,
"s": 8368,
"text": "Very similar to AdaBoost, Gradient Boosting Machines train weak learners sequentially, adding more and more estimators, but instead of adapting the weights of the data, it tries to predict the residual errors made by the previous estimators."
},
{
"code": null,
"e": 8998,
"s": 8610,
"text": "Because of this, we no longer have sample weights, and all the weak models have the same amount of say or importance. Again, most times, Decision trees are used as the base predictors, however, they’re not stumps, but bigger, fixed sized trees. GBMs use a learning rate and takes a small steps towards better results, in a similar manner conceptually to what is done in Gradient Descent."
},
{
"code": null,
"e": 9065,
"s": 8998,
"text": "Again, if you wanna dive deeper, check out the video by StatQuest."
},
{
"code": null,
"e": 9339,
"s": 9065,
"text": "Short for eXtreme gradient boosting, like in Gradient boosting, we fit our trees to the residuals of the previous trees predictions, however, instead of using conventional, fixed size decision trees, XGBoost uses a different kind of trees: XGBoost trees we could call them."
},
{
"code": null,
"e": 9592,
"s": 9339,
"text": "It builds these trees by calculating similarity scores between the observations that end up in a leave node. Also, XGBoost allows for regularisation, reducing the possible overfitting of our individual trees and therefore of the overall ensemble model."
},
{
"code": null,
"e": 9785,
"s": 9592,
"text": "Lastly, XGBoost is optimised to push the limit of the computational resources of boosted tree algorithms, making it a very high performance and fast algorithm in terms of time and computation."
},
{
"code": null,
"e": 9900,
"s": 9785,
"text": "You can watch the following video XGBoost Part 1: Regression, to get a deeper vision of what XGBoost is all about."
},
{
"code": null,
"e": 10359,
"s": 9900,
"text": "Light Gradient Boosting Machines, known by the short name of LigthGBM, are yet another turnaround of improvements for Gradient Boosting algorithms. Instead of using a level-wise growing strategy for the decision trees like in XGBoost, it uses a leaf-wise growth strategy, giving it the chance to achieve a higher error reduction per jump than other tree based algorithms. Also, compared to XGBoost, LigthGBM is generally faster, specially on large data sets."
},
{
"code": null,
"e": 10414,
"s": 10359,
"text": "You can learn more about it on its official docu page."
},
{
"code": null,
"e": 10430,
"s": 10414,
"text": "z-ai.medium.com"
},
{
"code": null,
"e": 10583,
"s": 10430,
"text": "That is it! As always, I hope you enjoyed the post, and that I managed to help you understand what boosting is, how it works, and why it is so powerful."
},
{
"code": null,
"e": 10675,
"s": 10583,
"text": "Here you can find some additional resources in case you want to learn more about the topic:"
},
{
"code": null,
"e": 10724,
"s": 10675,
"text": "Thoughts on Hypothesis Boosting, Michael Kearns."
},
{
"code": null,
"e": 10794,
"s": 10724,
"text": "A Gentle Introduction to Gradient Boosting on MachineLearningMastery."
},
{
"code": null,
"e": 10881,
"s": 10794,
"text": "A Decision-Theoretic Generalization of On-Line Learning and an Application to Boosting"
},
{
"code": null,
"e": 10912,
"s": 10881,
"text": "QuantDare: Boosting vs Bagging"
},
{
"code": null,
"e": 10953,
"s": 10912,
"text": "The best Machine Learning books reviewed"
},
{
"code": null,
"e": 11136,
"s": 10953,
"text": "If you liked this post then feel free to follow me on Twitter at @jaimezorno. Also, you can take a look at my other posts on Data Science and Machine Learning here. Have a good read!"
},
{
"code": null,
"e": 11355,
"s": 11136,
"text": "If you want to learn more about Machine Learning and Artificial Intelligence follow me on Medium, and stay tuned for my next posts! Also, you can check out this repository for more resources on Machine Learning and AI!"
},
{
"code": null,
"e": 11382,
"s": 11355,
"text": "Cover Image from Unsplash."
}
] |
Analytics on FIFA 2019 Players!. Football analytics and modelling of the... | by Dhanush | Towards Data Science
|
In this post we will perform simple data analysis and modelling of the FIFA 2019 complete player dataset following the CRISP-DM process . The dataset has been collected Kaggle. Dataset contains 1 CSV file.
FIFA 2019 is football simulation video game developed as a part of Electronic Arts’ FIFA series. It is the 26th instalment in the FIFA series selling over approximately 20 million units.
Let’s dive in!
In a sport like football, each player adds a significant value to the team’s success. It is important to understand player’s skills. How age could play an impact on potential of the player ? Which player is best at which profile? The study also focuses on evaluating the player’s overall performance based on the performance indicators and how various models evaluates on the prepared data.
As a second stage of CRISP DM, it is important to explore the data and address data mining questions using data visualizaton and querying. The data set consist of 89 columns but we will limit ourself to the following columns:
Index(['Name', 'Age', 'Overall', 'Potential', 'Value', 'Wage', 'Special', 'Preferred Foot', 'International Reputation', 'Weak Foot', 'Skill Moves', 'Crossing', 'Finishing', 'HeadingAccuracy', 'ShortPassing', 'Volleys', 'Dribbling', 'Curve', 'FKAccuracy', 'LongPassing', 'BallControl', 'Acceleration', 'SprintSpeed', 'Agility', 'Reactions', 'Balance', 'ShotPower', 'Jumping', 'Stamina', 'Strength', 'LongShots', 'Aggression', 'Interceptions', 'Positioning', 'Vision', 'Penalties', 'Composure', 'Marking', 'StandingTackle', 'SlidingTackle', 'GKDiving', 'GKHandling', 'GKKicking', 'GKPositioning', 'GKReflexes'], dtype='object')
Best players in various aspect?
Best players in various aspect?
It can be observed that the following players are rated the best at the respective fields. It can be seen that K. Mbappé has the highest potential, Cristiano Ronaldo has the best skill moves, Naido has the highest heading accuracy etc.
2. Most Preferred Foot of the Players?
3. Effect of football foot on player’s potential
It can be observed from the above plot, that the potential of the hardly depends on whether the player is left foot or a right foot.
3. Does Age have an Impact on Potential?
It can be observed from the barplot that with increase in age, the potential of the player tends to fall.
It can be observed from the heatmap that the Overall performance is positively correlated with majority of the performance indicators.
Third stage of CRISP-DM is data preparation. The data is cleaned (handling the categorical data and missing values to predict overall performance) and prepared to achieve the outcome. Linear Regression model is built to predict the overall performance of a player based on the performance scores.
Further we have fitted the data into various models — Random forest regressor, K neared neighbours and Decision tree regressor and evaluated the models using the following metrics:
Mean Absolute ErrorR SquareMean Square Error
Mean Absolute Error
R Square
Mean Square Error
In this article, we performed simple data analysis on the FIFA 2019 complete player dataset .
We looked at which player is good at a specific performance indicator. For Example: L. Messi is best at Finishing.We then looked at how age has an influence on the potential of the player i.e. with increase in age, potential of the player decreases.Build a model that predicts the overall performance of a player, given his skill scores for each of the performance indicator.Finally, we evaluated our linear regression model against KNearestRegressor, DecisionTreeRegressor, RandomForestRegressor
We looked at which player is good at a specific performance indicator. For Example: L. Messi is best at Finishing.
We then looked at how age has an influence on the potential of the player i.e. with increase in age, potential of the player decreases.
Build a model that predicts the overall performance of a player, given his skill scores for each of the performance indicator.
Finally, we evaluated our linear regression model against KNearestRegressor, DecisionTreeRegressor, RandomForestRegressor
The findings here are observational, a lot more analysis remains:
How will YOU solve the Problem?
All the codes are available in my Github Repository.
|
[
{
"code": null,
"e": 378,
"s": 172,
"text": "In this post we will perform simple data analysis and modelling of the FIFA 2019 complete player dataset following the CRISP-DM process . The dataset has been collected Kaggle. Dataset contains 1 CSV file."
},
{
"code": null,
"e": 565,
"s": 378,
"text": "FIFA 2019 is football simulation video game developed as a part of Electronic Arts’ FIFA series. It is the 26th instalment in the FIFA series selling over approximately 20 million units."
},
{
"code": null,
"e": 580,
"s": 565,
"text": "Let’s dive in!"
},
{
"code": null,
"e": 971,
"s": 580,
"text": "In a sport like football, each player adds a significant value to the team’s success. It is important to understand player’s skills. How age could play an impact on potential of the player ? Which player is best at which profile? The study also focuses on evaluating the player’s overall performance based on the performance indicators and how various models evaluates on the prepared data."
},
{
"code": null,
"e": 1197,
"s": 971,
"text": "As a second stage of CRISP DM, it is important to explore the data and address data mining questions using data visualizaton and querying. The data set consist of 89 columns but we will limit ourself to the following columns:"
},
{
"code": null,
"e": 1876,
"s": 1197,
"text": "Index(['Name', 'Age', 'Overall', 'Potential', 'Value', 'Wage', 'Special', 'Preferred Foot', 'International Reputation', 'Weak Foot', 'Skill Moves', 'Crossing', 'Finishing', 'HeadingAccuracy', 'ShortPassing', 'Volleys', 'Dribbling', 'Curve', 'FKAccuracy', 'LongPassing', 'BallControl', 'Acceleration', 'SprintSpeed', 'Agility', 'Reactions', 'Balance', 'ShotPower', 'Jumping', 'Stamina', 'Strength', 'LongShots', 'Aggression', 'Interceptions', 'Positioning', 'Vision', 'Penalties', 'Composure', 'Marking', 'StandingTackle', 'SlidingTackle', 'GKDiving', 'GKHandling', 'GKKicking', 'GKPositioning', 'GKReflexes'], dtype='object')"
},
{
"code": null,
"e": 1908,
"s": 1876,
"text": "Best players in various aspect?"
},
{
"code": null,
"e": 1940,
"s": 1908,
"text": "Best players in various aspect?"
},
{
"code": null,
"e": 2177,
"s": 1940,
"text": "It can be observed that the following players are rated the best at the respective fields. It can be seen that K. Mbappé has the highest potential, Cristiano Ronaldo has the best skill moves, Naido has the highest heading accuracy etc."
},
{
"code": null,
"e": 2216,
"s": 2177,
"text": "2. Most Preferred Foot of the Players?"
},
{
"code": null,
"e": 2265,
"s": 2216,
"text": "3. Effect of football foot on player’s potential"
},
{
"code": null,
"e": 2398,
"s": 2265,
"text": "It can be observed from the above plot, that the potential of the hardly depends on whether the player is left foot or a right foot."
},
{
"code": null,
"e": 2439,
"s": 2398,
"text": "3. Does Age have an Impact on Potential?"
},
{
"code": null,
"e": 2545,
"s": 2439,
"text": "It can be observed from the barplot that with increase in age, the potential of the player tends to fall."
},
{
"code": null,
"e": 2680,
"s": 2545,
"text": "It can be observed from the heatmap that the Overall performance is positively correlated with majority of the performance indicators."
},
{
"code": null,
"e": 2977,
"s": 2680,
"text": "Third stage of CRISP-DM is data preparation. The data is cleaned (handling the categorical data and missing values to predict overall performance) and prepared to achieve the outcome. Linear Regression model is built to predict the overall performance of a player based on the performance scores."
},
{
"code": null,
"e": 3158,
"s": 2977,
"text": "Further we have fitted the data into various models — Random forest regressor, K neared neighbours and Decision tree regressor and evaluated the models using the following metrics:"
},
{
"code": null,
"e": 3203,
"s": 3158,
"text": "Mean Absolute ErrorR SquareMean Square Error"
},
{
"code": null,
"e": 3223,
"s": 3203,
"text": "Mean Absolute Error"
},
{
"code": null,
"e": 3232,
"s": 3223,
"text": "R Square"
},
{
"code": null,
"e": 3250,
"s": 3232,
"text": "Mean Square Error"
},
{
"code": null,
"e": 3344,
"s": 3250,
"text": "In this article, we performed simple data analysis on the FIFA 2019 complete player dataset ."
},
{
"code": null,
"e": 3841,
"s": 3344,
"text": "We looked at which player is good at a specific performance indicator. For Example: L. Messi is best at Finishing.We then looked at how age has an influence on the potential of the player i.e. with increase in age, potential of the player decreases.Build a model that predicts the overall performance of a player, given his skill scores for each of the performance indicator.Finally, we evaluated our linear regression model against KNearestRegressor, DecisionTreeRegressor, RandomForestRegressor"
},
{
"code": null,
"e": 3956,
"s": 3841,
"text": "We looked at which player is good at a specific performance indicator. For Example: L. Messi is best at Finishing."
},
{
"code": null,
"e": 4092,
"s": 3956,
"text": "We then looked at how age has an influence on the potential of the player i.e. with increase in age, potential of the player decreases."
},
{
"code": null,
"e": 4219,
"s": 4092,
"text": "Build a model that predicts the overall performance of a player, given his skill scores for each of the performance indicator."
},
{
"code": null,
"e": 4341,
"s": 4219,
"text": "Finally, we evaluated our linear regression model against KNearestRegressor, DecisionTreeRegressor, RandomForestRegressor"
},
{
"code": null,
"e": 4407,
"s": 4341,
"text": "The findings here are observational, a lot more analysis remains:"
},
{
"code": null,
"e": 4439,
"s": 4407,
"text": "How will YOU solve the Problem?"
}
] |
Predict Customer Churn (the right way) using PyCaret | by Moez Ali | Towards Data Science
|
Customer retention is one of the primary KPI for companies with a subscription-based business model. Competition is tough particularly in the SaaS market where customers are free to choose from plenty of providers. One bad experience and customer may just move to the competitor resulting in customer churn.
Customer churn is the percentage of customers that stopped using your company’s product or service during a certain time frame. One of the ways to calculate a churn rate is to divide the number of customers lost during a given time interval by the number of active customers at the beginning of the period. For example, if you got 1000 customers and lost 50 last month, then your monthly churn rate is 5 percent.
Predicting customer churn is a challenging but extremely important business problem especially in industries where the cost of customer acquisition (CAC) is high such as technology, telecom, finance, etc. The ability to predict that a particular customer is at a high risk of churning, while there is still time to do something about it, represents a huge additional potential revenue source for companies.
The primary objective of the customer churn predictive model is to retain customers at the highest risk of churn by proactively engaging with them. For example: Offer a gift voucher or any promotional pricing and lock them in for an additional year or two to extend their lifetime value to the company.
There are two broad concepts to understand here:
We want a customer churn predictive model to predict the churn in advance (let’s say one month in advance, three months in advance, or even six months in advance — it all depends on the use-case). This means that you have to be extremely careful of the cut-off date i.e. You shouldn’t be using any information after the cut-off date as a feature in the machine learning model, otherwise it will be leakage. The period before the cut-off date is known as the Event.
Normally for customer churn prediction, you will have to work a little bit to create a target column, it’s generally not available in the form you would want it. For example, you want to predict if the customer will churn within the next quarter, and so you will iterate through all the active customers as of your event cut-off date and check if they left the company in the next quarter or not (1 for yes, 0 for no). The quarter in this case is called Performance Window.
Now that you understand how the data is sourced and churn target is created (which is one of the most challenging parts of the problem), let’s discuss how this machine learning model will be used in the business. Read the below diagram from left-to-right:
A model is trained on customer churn history (event period for X features and performance window for target variable).
Every month active customer base is passed onto Machine Learning Predictive Model to return the probability of churn for each customer (in business lingo, this is sometimes called a score of churn).
The list will be sorted from highest to lowest probability value (or score as they say it) and the customer retention teams will start engaging with the customer to stop the churn, normally by offering some kind of promotion or gift card to lock in few more years.
Customers that have a very low probability of churn (or essentially model predicts no-churn) are happy customers. No actions are taken on them.
In this section, I will demonstrate the complete end-to-end workflow for machine learning model training & selection, hyperparameter tuning, analysis, and interpretation of the results. I will also discuss the metrics that you can optimize and why conventional metrics like AUC, Accuracy, Recall may not be suitable for the customer churn models. I will be using PyCaret — an open-source, low-code machine learning library to perform this experiment. This tutorial assumes you have basic knowledge of PyCaret.
PyCaret is an open-source, low-code machine learning library and end-to-end model management tool built-in Python for automating machine learning workflows. PyCaret is known for its ease of use, simplicity, and ability to quickly and efficiently build and deploy end-to-end machine learning pipelines. To learn more about PyCaret, check out their GitHub.
# install pycaretpip install pycaret
For this tutorial, I am using a Telecom Customer Churn dataset from Kaggle. The dataset already contains the target column that we can use as is. You can read this dataset directly from this GitHub link. (Shoutout to srees1988)
# import librariesimport pandas as pdimport numpy as np# read csv datadata = pd.read_csv('https://raw.githubusercontent.com/srees1988/predict-churn-py/main/customer_churn_data.csv')
# check data typesdata.dtypes
Notice that TotalCharges is of an object type instead of float64. Upon investigation, I figured out there are some blank spaces in this column which has caused Python to force the data type as object . To fix that, we will have to trim blank spaces before changing the data type.
# replace blanks with np.nandata['TotalCharges'] = data['TotalCharges'].replace(' ', np.nan)# convert to float64data['TotalCharges'] = data['TotalCharges'].astype('float64')
Intuitively contract type, tenure (length of stay of the customer), and pricing plans are very important information when it comes to customer churn or retention. Let’s explore the relationship:
Notice that most churn can be seen in the contracts that are “Month-to-Month”. Makes sense, ofcourse. Also, I can see that as the tenure increases and so are the total charges, the likelihood of customers with high tenure and low charges is less compared to customers with high tenure and high charges.
Missing Values
# check missing valuesdata.isnull().sum()
Notice that because we replaced blank values with np.nan there are now 11 rows with missing values in TotalCharges. No problem — I will leave it with PyCaret to impute it automatically.
Common to all modules in PyCaret, the setup is the first and the only mandatory step in any machine learning experiment performed in PyCaret. This function takes care of all the data preparation required prior to training models. Besides performing some basic default processing tasks, PyCaret also offers a wide array of pre-processing features. To learn more about all the preprocessing functionalities in PyCaret, you can see this link.
# init setupfrom pycaret.classification import *s = setup(data, target = 'Churn', ignore_features = ['customerID'])
Whenever you initialize the setup function in PyCaret, it profiles the dataset and infers the data types for all input features. In this case, you can see except for tenure MonthlyCharges and TotalCharges , everything else is categorical, which is correct, you can now press enter to continue. If data types are not inferred correctly (which can happen sometimes), you can use numeric_feature and categorical_feature to overwrite the data types.
Also, notice that I have passed ignore_features = ['customerID'] in the setup function so that it is not considered when training the models. The good thing about this is PyCaret will not remove the column from the dataset, it will just ignore it behind the scene for model training. As such when you generate predictions at the end, you don’t need to worry about joining IDs back by yourself.
Now that data preparation is done, let’s start the training process by using compare_models functionality. This function trains all the algorithms available in the model library and evaluates multiple performance metrics using cross-validation.
# compare all modelsbest_model = compare_models(sort='AUC')
The best model based on AUC is Gradient Boosting Classifier . AUC using 10-fold cross-validation is 0.8472.
# print best_model parametersprint(best_model)
You can use the tune_model function from PyCaret to automatically tune the hyperparameters of the model.
# tune best modeltuned_best_model = tune_model(best_model)
Notice that AUC has slightly increased from 0.8472 to 0.8478 .
# AUC Plotplot_model(tuned_best_model, plot = 'auc')
# Feature Importance Plotplot_model(tuned_gbc, plot = 'feature')
# Confusion Matrixplot_model(tuned_best_model, plot = 'confusion_matrix')
This confusion matrix is on the test set which includes 30% of our data (2,113 rows) We have 309 True Positives (15%) — these are the customers for which we will be able to extend the lifetime value. If we wouldn’t have predicted, then there was no opportunity for intervention.
We also have 138 (7%) False Positives where we will lose money because the promotion offered to these customers will just be an extra cost.
1,388 (66%) are True Negatives (good customers) and 278 (13%) are False Negative (this is a missed opportunity).
So far we have trained multiple models to select the best model giving the highest AUC, followed by tuning the hyperparameters of the best model to squeeze a little more performance in terms of AUC. However, the best AUC doesn’t necessarily translate into the best model for business.
In a churn model, often the reward of true positives is way different than the cost of false positives. Let’s use the following assumptions:
$1,000 voucher will be offered to all the customers identified as churn (True Positive + False Positive);
If we are able to stop the churn, we will gain $5,000 in customer lifetime value.
Using these assumptions and the confusion matrix above, we can calculate the $ impact of this model:
It’s a good model but the problem is it’s not a business-smart model. It is doing a pretty good job compared to if you have no model but how can we train and select a model that maximizes the business value. In order to achieve that we have to train, select, and optimize models using business metrics instead of any conventional metric like AUC or Accuracy.
Thanks to PyCaret, it is extremely easy to achieve this using add_metric function.
# create a custom functiondef calculate_profit(y, y_pred): tp = np.where((y_pred==1) & (y==1), (5000-1000), 0) fp = np.where((y_pred==1) & (y==0), -1000, 0) return np.sum([tp,fp])# add metric to PyCaretadd_metric('profit', 'Profit', calculate_profit)
Now let’s run compare_models and see the magic.
# compare all modelsbest_model = compare_models(sort='Profit')
Notice that a new column Profit is added this time and surprisingly Naive Bayes which is a pretty bad model in terms of AUC is the best model when it comes to profit. Let’s see how:
# confusion matrixplot_model(best_model, plot = 'confusion_matrix')
The total number of customers is still the same (2,113 customers in the test set), what’s changed is now how the model is making errors over false positives and false negatives. Let’s put some $ value against it, using the same assumptions (as above):
BAM! We have just increased profit by ~$400,000 with a model that does 2% less in AUC than the best model. How does this happen? Well, for starters, AUC or any other out-of-the-box classification metric (Accuracy, Recall, Precision, F1, Kappa, etc.) is not a business-smart metric, so it does not take into account the risk and reward proposition. Adding a custom metric and using it for model selection or optimization is a great idea and right way to go with.
I hope you will appreciate the simplicity and ease of use in PyCaret. With only a few lines of code, we were able to train multiple models and select the one that matters to the business. I am a regular blogger and I mostly write about PyCaret and its use-cases in the real world, If you would like to be notified automatically, you can follow me on Medium, LinkedIn, and Twitter.
There is no limit to what you can achieve using this lightweight workflow automation library in Python. If you find this useful, please do not forget to give us ⭐️ on our GitHub repository.
To hear more about PyCaret follow us on LinkedIn and Youtube.
Join us on our slack channel. Invite link here.
DocumentationBlogGitHubStackOverflowInstall PyCaretNotebook TutorialsContribute in PyCaret
|
[
{
"code": null,
"e": 480,
"s": 172,
"text": "Customer retention is one of the primary KPI for companies with a subscription-based business model. Competition is tough particularly in the SaaS market where customers are free to choose from plenty of providers. One bad experience and customer may just move to the competitor resulting in customer churn."
},
{
"code": null,
"e": 893,
"s": 480,
"text": "Customer churn is the percentage of customers that stopped using your company’s product or service during a certain time frame. One of the ways to calculate a churn rate is to divide the number of customers lost during a given time interval by the number of active customers at the beginning of the period. For example, if you got 1000 customers and lost 50 last month, then your monthly churn rate is 5 percent."
},
{
"code": null,
"e": 1300,
"s": 893,
"text": "Predicting customer churn is a challenging but extremely important business problem especially in industries where the cost of customer acquisition (CAC) is high such as technology, telecom, finance, etc. The ability to predict that a particular customer is at a high risk of churning, while there is still time to do something about it, represents a huge additional potential revenue source for companies."
},
{
"code": null,
"e": 1603,
"s": 1300,
"text": "The primary objective of the customer churn predictive model is to retain customers at the highest risk of churn by proactively engaging with them. For example: Offer a gift voucher or any promotional pricing and lock them in for an additional year or two to extend their lifetime value to the company."
},
{
"code": null,
"e": 1652,
"s": 1603,
"text": "There are two broad concepts to understand here:"
},
{
"code": null,
"e": 2117,
"s": 1652,
"text": "We want a customer churn predictive model to predict the churn in advance (let’s say one month in advance, three months in advance, or even six months in advance — it all depends on the use-case). This means that you have to be extremely careful of the cut-off date i.e. You shouldn’t be using any information after the cut-off date as a feature in the machine learning model, otherwise it will be leakage. The period before the cut-off date is known as the Event."
},
{
"code": null,
"e": 2591,
"s": 2117,
"text": "Normally for customer churn prediction, you will have to work a little bit to create a target column, it’s generally not available in the form you would want it. For example, you want to predict if the customer will churn within the next quarter, and so you will iterate through all the active customers as of your event cut-off date and check if they left the company in the next quarter or not (1 for yes, 0 for no). The quarter in this case is called Performance Window."
},
{
"code": null,
"e": 2847,
"s": 2591,
"text": "Now that you understand how the data is sourced and churn target is created (which is one of the most challenging parts of the problem), let’s discuss how this machine learning model will be used in the business. Read the below diagram from left-to-right:"
},
{
"code": null,
"e": 2966,
"s": 2847,
"text": "A model is trained on customer churn history (event period for X features and performance window for target variable)."
},
{
"code": null,
"e": 3165,
"s": 2966,
"text": "Every month active customer base is passed onto Machine Learning Predictive Model to return the probability of churn for each customer (in business lingo, this is sometimes called a score of churn)."
},
{
"code": null,
"e": 3430,
"s": 3165,
"text": "The list will be sorted from highest to lowest probability value (or score as they say it) and the customer retention teams will start engaging with the customer to stop the churn, normally by offering some kind of promotion or gift card to lock in few more years."
},
{
"code": null,
"e": 3574,
"s": 3430,
"text": "Customers that have a very low probability of churn (or essentially model predicts no-churn) are happy customers. No actions are taken on them."
},
{
"code": null,
"e": 4084,
"s": 3574,
"text": "In this section, I will demonstrate the complete end-to-end workflow for machine learning model training & selection, hyperparameter tuning, analysis, and interpretation of the results. I will also discuss the metrics that you can optimize and why conventional metrics like AUC, Accuracy, Recall may not be suitable for the customer churn models. I will be using PyCaret — an open-source, low-code machine learning library to perform this experiment. This tutorial assumes you have basic knowledge of PyCaret."
},
{
"code": null,
"e": 4439,
"s": 4084,
"text": "PyCaret is an open-source, low-code machine learning library and end-to-end model management tool built-in Python for automating machine learning workflows. PyCaret is known for its ease of use, simplicity, and ability to quickly and efficiently build and deploy end-to-end machine learning pipelines. To learn more about PyCaret, check out their GitHub."
},
{
"code": null,
"e": 4476,
"s": 4439,
"text": "# install pycaretpip install pycaret"
},
{
"code": null,
"e": 4704,
"s": 4476,
"text": "For this tutorial, I am using a Telecom Customer Churn dataset from Kaggle. The dataset already contains the target column that we can use as is. You can read this dataset directly from this GitHub link. (Shoutout to srees1988)"
},
{
"code": null,
"e": 4886,
"s": 4704,
"text": "# import librariesimport pandas as pdimport numpy as np# read csv datadata = pd.read_csv('https://raw.githubusercontent.com/srees1988/predict-churn-py/main/customer_churn_data.csv')"
},
{
"code": null,
"e": 4916,
"s": 4886,
"text": "# check data typesdata.dtypes"
},
{
"code": null,
"e": 5196,
"s": 4916,
"text": "Notice that TotalCharges is of an object type instead of float64. Upon investigation, I figured out there are some blank spaces in this column which has caused Python to force the data type as object . To fix that, we will have to trim blank spaces before changing the data type."
},
{
"code": null,
"e": 5370,
"s": 5196,
"text": "# replace blanks with np.nandata['TotalCharges'] = data['TotalCharges'].replace(' ', np.nan)# convert to float64data['TotalCharges'] = data['TotalCharges'].astype('float64')"
},
{
"code": null,
"e": 5565,
"s": 5370,
"text": "Intuitively contract type, tenure (length of stay of the customer), and pricing plans are very important information when it comes to customer churn or retention. Let’s explore the relationship:"
},
{
"code": null,
"e": 5868,
"s": 5565,
"text": "Notice that most churn can be seen in the contracts that are “Month-to-Month”. Makes sense, ofcourse. Also, I can see that as the tenure increases and so are the total charges, the likelihood of customers with high tenure and low charges is less compared to customers with high tenure and high charges."
},
{
"code": null,
"e": 5883,
"s": 5868,
"text": "Missing Values"
},
{
"code": null,
"e": 5925,
"s": 5883,
"text": "# check missing valuesdata.isnull().sum()"
},
{
"code": null,
"e": 6111,
"s": 5925,
"text": "Notice that because we replaced blank values with np.nan there are now 11 rows with missing values in TotalCharges. No problem — I will leave it with PyCaret to impute it automatically."
},
{
"code": null,
"e": 6551,
"s": 6111,
"text": "Common to all modules in PyCaret, the setup is the first and the only mandatory step in any machine learning experiment performed in PyCaret. This function takes care of all the data preparation required prior to training models. Besides performing some basic default processing tasks, PyCaret also offers a wide array of pre-processing features. To learn more about all the preprocessing functionalities in PyCaret, you can see this link."
},
{
"code": null,
"e": 6667,
"s": 6551,
"text": "# init setupfrom pycaret.classification import *s = setup(data, target = 'Churn', ignore_features = ['customerID'])"
},
{
"code": null,
"e": 7113,
"s": 6667,
"text": "Whenever you initialize the setup function in PyCaret, it profiles the dataset and infers the data types for all input features. In this case, you can see except for tenure MonthlyCharges and TotalCharges , everything else is categorical, which is correct, you can now press enter to continue. If data types are not inferred correctly (which can happen sometimes), you can use numeric_feature and categorical_feature to overwrite the data types."
},
{
"code": null,
"e": 7507,
"s": 7113,
"text": "Also, notice that I have passed ignore_features = ['customerID'] in the setup function so that it is not considered when training the models. The good thing about this is PyCaret will not remove the column from the dataset, it will just ignore it behind the scene for model training. As such when you generate predictions at the end, you don’t need to worry about joining IDs back by yourself."
},
{
"code": null,
"e": 7752,
"s": 7507,
"text": "Now that data preparation is done, let’s start the training process by using compare_models functionality. This function trains all the algorithms available in the model library and evaluates multiple performance metrics using cross-validation."
},
{
"code": null,
"e": 7812,
"s": 7752,
"text": "# compare all modelsbest_model = compare_models(sort='AUC')"
},
{
"code": null,
"e": 7920,
"s": 7812,
"text": "The best model based on AUC is Gradient Boosting Classifier . AUC using 10-fold cross-validation is 0.8472."
},
{
"code": null,
"e": 7967,
"s": 7920,
"text": "# print best_model parametersprint(best_model)"
},
{
"code": null,
"e": 8072,
"s": 7967,
"text": "You can use the tune_model function from PyCaret to automatically tune the hyperparameters of the model."
},
{
"code": null,
"e": 8131,
"s": 8072,
"text": "# tune best modeltuned_best_model = tune_model(best_model)"
},
{
"code": null,
"e": 8194,
"s": 8131,
"text": "Notice that AUC has slightly increased from 0.8472 to 0.8478 ."
},
{
"code": null,
"e": 8247,
"s": 8194,
"text": "# AUC Plotplot_model(tuned_best_model, plot = 'auc')"
},
{
"code": null,
"e": 8312,
"s": 8247,
"text": "# Feature Importance Plotplot_model(tuned_gbc, plot = 'feature')"
},
{
"code": null,
"e": 8386,
"s": 8312,
"text": "# Confusion Matrixplot_model(tuned_best_model, plot = 'confusion_matrix')"
},
{
"code": null,
"e": 8665,
"s": 8386,
"text": "This confusion matrix is on the test set which includes 30% of our data (2,113 rows) We have 309 True Positives (15%) — these are the customers for which we will be able to extend the lifetime value. If we wouldn’t have predicted, then there was no opportunity for intervention."
},
{
"code": null,
"e": 8805,
"s": 8665,
"text": "We also have 138 (7%) False Positives where we will lose money because the promotion offered to these customers will just be an extra cost."
},
{
"code": null,
"e": 8918,
"s": 8805,
"text": "1,388 (66%) are True Negatives (good customers) and 278 (13%) are False Negative (this is a missed opportunity)."
},
{
"code": null,
"e": 9203,
"s": 8918,
"text": "So far we have trained multiple models to select the best model giving the highest AUC, followed by tuning the hyperparameters of the best model to squeeze a little more performance in terms of AUC. However, the best AUC doesn’t necessarily translate into the best model for business."
},
{
"code": null,
"e": 9344,
"s": 9203,
"text": "In a churn model, often the reward of true positives is way different than the cost of false positives. Let’s use the following assumptions:"
},
{
"code": null,
"e": 9450,
"s": 9344,
"text": "$1,000 voucher will be offered to all the customers identified as churn (True Positive + False Positive);"
},
{
"code": null,
"e": 9532,
"s": 9450,
"text": "If we are able to stop the churn, we will gain $5,000 in customer lifetime value."
},
{
"code": null,
"e": 9633,
"s": 9532,
"text": "Using these assumptions and the confusion matrix above, we can calculate the $ impact of this model:"
},
{
"code": null,
"e": 9992,
"s": 9633,
"text": "It’s a good model but the problem is it’s not a business-smart model. It is doing a pretty good job compared to if you have no model but how can we train and select a model that maximizes the business value. In order to achieve that we have to train, select, and optimize models using business metrics instead of any conventional metric like AUC or Accuracy."
},
{
"code": null,
"e": 10075,
"s": 9992,
"text": "Thanks to PyCaret, it is extremely easy to achieve this using add_metric function."
},
{
"code": null,
"e": 10335,
"s": 10075,
"text": "# create a custom functiondef calculate_profit(y, y_pred): tp = np.where((y_pred==1) & (y==1), (5000-1000), 0) fp = np.where((y_pred==1) & (y==0), -1000, 0) return np.sum([tp,fp])# add metric to PyCaretadd_metric('profit', 'Profit', calculate_profit)"
},
{
"code": null,
"e": 10383,
"s": 10335,
"text": "Now let’s run compare_models and see the magic."
},
{
"code": null,
"e": 10446,
"s": 10383,
"text": "# compare all modelsbest_model = compare_models(sort='Profit')"
},
{
"code": null,
"e": 10628,
"s": 10446,
"text": "Notice that a new column Profit is added this time and surprisingly Naive Bayes which is a pretty bad model in terms of AUC is the best model when it comes to profit. Let’s see how:"
},
{
"code": null,
"e": 10696,
"s": 10628,
"text": "# confusion matrixplot_model(best_model, plot = 'confusion_matrix')"
},
{
"code": null,
"e": 10948,
"s": 10696,
"text": "The total number of customers is still the same (2,113 customers in the test set), what’s changed is now how the model is making errors over false positives and false negatives. Let’s put some $ value against it, using the same assumptions (as above):"
},
{
"code": null,
"e": 11410,
"s": 10948,
"text": "BAM! We have just increased profit by ~$400,000 with a model that does 2% less in AUC than the best model. How does this happen? Well, for starters, AUC or any other out-of-the-box classification metric (Accuracy, Recall, Precision, F1, Kappa, etc.) is not a business-smart metric, so it does not take into account the risk and reward proposition. Adding a custom metric and using it for model selection or optimization is a great idea and right way to go with."
},
{
"code": null,
"e": 11791,
"s": 11410,
"text": "I hope you will appreciate the simplicity and ease of use in PyCaret. With only a few lines of code, we were able to train multiple models and select the one that matters to the business. I am a regular blogger and I mostly write about PyCaret and its use-cases in the real world, If you would like to be notified automatically, you can follow me on Medium, LinkedIn, and Twitter."
},
{
"code": null,
"e": 11981,
"s": 11791,
"text": "There is no limit to what you can achieve using this lightweight workflow automation library in Python. If you find this useful, please do not forget to give us ⭐️ on our GitHub repository."
},
{
"code": null,
"e": 12043,
"s": 11981,
"text": "To hear more about PyCaret follow us on LinkedIn and Youtube."
},
{
"code": null,
"e": 12091,
"s": 12043,
"text": "Join us on our slack channel. Invite link here."
}
] |
PHP ArgumentCountError
|
PHP parser throws ArgumentCountError when arguments passed to a user defined function or method are less than those in its definition. ArgumentCountError class is inherited from TypeError class
In Following example, a user defined function add() is defined to receive two arguments. However, if less than required number of arguments is provided while calling, ArgumentCountError will be thrown which can be handled with catch block.
Live Demo
<?php
function add($x, $y){
return $x+$y;
}
try{
echo add(10);
}
catch (ArgumentCountError $e){
echo $e->getMessage();
}
?>
This will produce following result −
Too few arguments to function add(), 1 passed in C:\xampp\php\test.php on line 6 and exactly 2 expected
In Following example, setdata() method in myclass is defined to have two formal arguments. When this method is called with less arguments, ArgumentCountException is thrown
<?php
class myclass{
private $name;
private $age;
function setdata($name, $age){
$this->name=$name;
$this->age=$age;
}
}
try{
$obj=new myclass();
obj->setdata();
}
catch (ArgumentCountError $e){
echo $e->getMessage();
}
?>
This will produce following result −
Too few arguments to function myclass::setdata(), 0 passed in C:\xampp\php\test.php on line 15 and exactly 2 expected
ArgumentCountException is also thrown in case built-in function is given inappropriate or invalid number of arguments. However, strict-types mode must be set
Live Demo
<?php
declare(strict_types = 1);
try{
echo strlen("Hello", "World");
}
catch (ArgumentCountError $e){
echo $e->getMessage();
}
?>
This will produce following result −
strlen() expects exactly 1 parameter, 2 given
|
[
{
"code": null,
"e": 1256,
"s": 1062,
"text": "PHP parser throws ArgumentCountError when arguments passed to a user defined function or method are less than those in its definition. ArgumentCountError class is inherited from TypeError class"
},
{
"code": null,
"e": 1496,
"s": 1256,
"text": "In Following example, a user defined function add() is defined to receive two arguments. However, if less than required number of arguments is provided while calling, ArgumentCountError will be thrown which can be handled with catch block."
},
{
"code": null,
"e": 1507,
"s": 1496,
"text": " Live Demo"
},
{
"code": null,
"e": 1640,
"s": 1507,
"text": "<?php\nfunction add($x, $y){\n return $x+$y;\n}\ntry{\n echo add(10);\n}\ncatch (ArgumentCountError $e){\n echo $e->getMessage();\n}\n?>"
},
{
"code": null,
"e": 1677,
"s": 1640,
"text": "This will produce following result −"
},
{
"code": null,
"e": 1781,
"s": 1677,
"text": "Too few arguments to function add(), 1 passed in C:\\xampp\\php\\test.php on line 6 and exactly 2 expected"
},
{
"code": null,
"e": 1953,
"s": 1781,
"text": "In Following example, setdata() method in myclass is defined to have two formal arguments. When this method is called with less arguments, ArgumentCountException is thrown"
},
{
"code": null,
"e": 2209,
"s": 1953,
"text": "<?php\nclass myclass{\n private $name;\n private $age;\n function setdata($name, $age){\n $this->name=$name;\n $this->age=$age;\n }\n}\ntry{\n $obj=new myclass();\n obj->setdata();\n}\ncatch (ArgumentCountError $e){\n echo $e->getMessage();\n}\n?>"
},
{
"code": null,
"e": 2246,
"s": 2209,
"text": "This will produce following result −"
},
{
"code": null,
"e": 2364,
"s": 2246,
"text": "Too few arguments to function myclass::setdata(), 0 passed in C:\\xampp\\php\\test.php on line 15 and exactly 2 expected"
},
{
"code": null,
"e": 2522,
"s": 2364,
"text": "ArgumentCountException is also thrown in case built-in function is given inappropriate or invalid number of arguments. However, strict-types mode must be set"
},
{
"code": null,
"e": 2533,
"s": 2522,
"text": " Live Demo"
},
{
"code": null,
"e": 2669,
"s": 2533,
"text": "<?php\ndeclare(strict_types = 1);\ntry{\n echo strlen(\"Hello\", \"World\");\n}\ncatch (ArgumentCountError $e){\n echo $e->getMessage();\n}\n?>"
},
{
"code": null,
"e": 2706,
"s": 2669,
"text": "This will produce following result −"
},
{
"code": null,
"e": 2752,
"s": 2706,
"text": "strlen() expects exactly 1 parameter, 2 given"
}
] |
Count ways to make sum of odd and even indexed elements equal by removing an array element - GeeksforGeeks
|
27 Jun, 2021
Given an array, arr[] of size N, the task is to find the count of array indices such that removing an element from these indices makes the sum of even-indexed and odd-indexed array elements equal.
Examples:
Input: arr[] = { 2, 1, 6, 4 } Output: 1 Explanation: Removing arr[1] from the array modifies arr[] to { 2, 6, 4 } such that, arr[0] + arr[2] = arr[1]. Therefore, the required output is 1.
Input: arr[] = { 1, 1, 1 } Output: 3 Explanation: Removing arr[0] from the given array modifies arr[] to { 1, 1 } such that arr[0] = arr[1] Removing arr[1] from the given array modifies arr[] to { 1, 1 } such that arr[0] = arr[1] Removing arr[2] from the given array modifies arr[] to { 1, 1 } such that arr[0] = arr[1] Therefore, the required output is 3.
Naive Approach: The simplest approach to solve this problem is to traverse the array and for each array element, check if removing the element from the array makes the sum of even-indexed and odd-indexed array elements equal or not. If found to be true, then increment the count. Finally, print the count.
Time Complexity: O(N2) Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the observation that removing any element from the given array makes even indices of succeeding elements as odd and odd indices of the succeeding elements as even. Follow the steps below to solve the problem:
Initialize two variables, say evenSum and oddSum, to store the sum of odd-indexed and even-indexed elements of the given array respectively.
Traverse the array using variable i.
Remove every ith element of the array and update the sum of the remaining even-indexed elements and the odd-indexed elements based on the above observation. Check if the sums are equal or not. If found to be true, then increment the count.
Finally, print the count obtained.
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 count array indices// whose removal makes sum of odd and// even indexed elements equalint cntIndexesToMakeBalance(int arr[], int n){ // If size of the array is 1 if (n == 1) { return 1; } // If size of the array is 2 if (n == 2) return 0; // Stores sum of even-indexed // elements of the given array int sumEven = 0; // Stores sum of odd-indexed // elements of the given array int sumOdd = 0; // Traverse the array for (int i = 0; i < n; i++) { // If i is an even number if (i % 2 == 0) { // Update sumEven sumEven += arr[i]; } // If i is an odd number else { // Update sumOdd sumOdd += arr[i]; } } // Stores sum of even-indexed // array elements till i-th index int currOdd = 0; // Stores sum of odd-indexed // array elements till i-th index int currEven = arr[0]; // Stores count of indices whose // removal makes sum of odd and // even indexed elements equal int res = 0; // Stores sum of even-indexed elements // after removing the i-th element int newEvenSum = 0; // Stores sum of odd-indexed elements // after removing the i-th element int newOddSum = 0; // Traverse the array for (int i = 1; i < n - 1; i++) { // If i is an odd number if (i % 2) { // Update currOdd currOdd += arr[i]; // Update newEvenSum newEvenSum = currEven + sumOdd - currOdd; // Update newOddSum newOddSum = currOdd + sumEven - currEven - arr[i]; } // If i is an even number else { // Update currEven currEven += arr[i]; // Update newOddSum newOddSum = currOdd + sumEven - currEven; // Update newEvenSum newEvenSum = currEven + sumOdd - currOdd - arr[i]; } // If newEvenSum is equal to newOddSum if (newEvenSum == newOddSum) { // Increase the count res++; } } // If sum of even-indexed and odd-indexed // elements is equal by removing the first element if (sumOdd == sumEven - arr[0]) { // Increase the count res++; } // If length of the array // is an odd number if (n % 2 == 1) { // If sum of even-indexed and odd-indexed // elements is equal by removing the last element if (sumOdd == sumEven - arr[n - 1]) { // Increase the count res++; } } // If length of the array // is an even number else { // If sum of even-indexed and odd-indexed // elements is equal by removing the last element if (sumEven == sumOdd - arr[n - 1]) { // Increase the count res++; } } return res;} // Driver Codeint main(){ int arr[] = { 1, 1, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << cntIndexesToMakeBalance(arr, n); return 0;}
// Java program to implement// the above approachclass GFG { // Function to count array indices // whose removal makes sum of odd and // even indexed elements equal static int cntIndexesToMakeBalance(int arr[], int n) { // If size of the array is 1 if (n == 1) { return 1; } // If size of the array is 2 if (n == 2) return 0; // Stores sum of even-indexed // elements of the given array int sumEven = 0; // Stores sum of odd-indexed // elements of the given array int sumOdd = 0; // Traverse the array for (int i = 0; i < n; i++) { // If i is an even number if (i % 2 == 0) { // Update sumEven sumEven += arr[i]; } // If i is an odd number else { // Update sumOdd sumOdd += arr[i]; } } // Stores sum of even-indexed // array elements till i-th index int currOdd = 0; // Stores sum of odd-indexed // array elements till i-th index int currEven = arr[0]; // Stores count of indices whose // removal makes sum of odd and // even indexed elements equal int res = 0; // Stores sum of even-indexed elements // after removing the i-th element int newEvenSum = 0; // Stores sum of odd-indexed elements // after removing the i-th element int newOddSum = 0; // Traverse the array for (int i = 1; i < n - 1; i++) { // If i is an odd number if (i % 2 != 0) { // Update currOdd currOdd += arr[i]; // Update newEvenSum newEvenSum = currEven + sumOdd - currOdd; // Update newOddSum newOddSum = currOdd + sumEven - currEven - arr[i]; } // If i is an even number else { // Update currEven currEven += arr[i]; // Update newOddSum newOddSum = currOdd + sumEven - currEven; // Update newEvenSum newEvenSum = currEven + sumOdd - currOdd - arr[i]; } // If newEvenSum is equal to newOddSum if (newEvenSum == newOddSum) { // Increase the count res++; } } // If sum of even-indexed and odd-indexed // elements is equal by removing the first element if (sumOdd == sumEven - arr[0]) { // Increase the count res++; } // If length of the array // is an odd number if (n % 2 == 1) { // If sum of even-indexed and odd-indexed // elements is equal by removing the last element if (sumOdd == sumEven - arr[n - 1]) { // Increase the count res++; } } // If length of the array // is an even number else { // If sum of even-indexed and odd-indexed // elements is equal by removing the last element if (sumEven == sumOdd - arr[n - 1]) { // Increase the count res++; } } return res; } // Driver Code public static void main (String[] args) { int arr[] = { 1, 1, 1 }; int n = arr.length; System.out.println(cntIndexesToMakeBalance(arr, n)); }} // This code is contributed by AnkitRai01
# Python3 program to implement# the above approach # Function to count array indices# whose removal makes sum of odd and# even indexed elements equaldef cntIndexesToMakeBalance(arr, n): # If size of the array is 1 if (n == 1): return 1 # If size of the array is 2 if (n == 2): return 0 # Stores sum of even-indexed # elements of the given array sumEven = 0 # Stores sum of odd-indexed # elements of the given array sumOdd = 0 # Traverse the array for i in range(n): # If i is an even number if (i % 2 == 0): # Update sumEven sumEven += arr[i] # If i is an odd number else: # Update sumOdd sumOdd += arr[i] # Stores sum of even-indexed # array elements till i-th index currOdd = 0 # Stores sum of odd-indexed # array elements till i-th index currEven = arr[0] # Stores count of indices whose # removal makes sum of odd and # even indexed elements equal res = 0 # Stores sum of even-indexed elements # after removing the i-th element newEvenSum = 0 # Stores sum of odd-indexed elements # after removing the i-th element newOddSum = 0 # Traverse the array for i in range(1, n - 1): # If i is an odd number if (i % 2): # Update currOdd currOdd += arr[i] # Update newEvenSum newEvenSum = (currEven + sumOdd - currOdd) # Update newOddSum newOddSum = (currOdd + sumEven - currEven - arr[i]) # If i is an even number else: # Update currEven currEven += arr[i] # Update newOddSum newOddSum = (currOdd + sumEven - currEven) # Update newEvenSum newEvenSum = (currEven + sumOdd - currOdd - arr[i]) # If newEvenSum is equal to newOddSum if (newEvenSum == newOddSum): # Increase the count res += 1 # If sum of even-indexed and odd-indexed # elements is equal by removing the first # element if (sumOdd == sumEven - arr[0]): # Increase the count res += 1 # If length of the array # is an odd number if (n % 2 == 1): # If sum of even-indexed and odd-indexed # elements is equal by removing the last # element if (sumOdd == sumEven - arr[n - 1]): # Increase the count res += 1 # If length of the array # is an even number else: # If sum of even-indexed and odd-indexed # elements is equal by removing the last # element if (sumEven == sumOdd - arr[n - 1]): # Increase the count res += 1 return res # Driver Codeif __name__ == "__main__" : arr = [ 1, 1, 1 ] n = len(arr) print(cntIndexesToMakeBalance(arr, n)) # This code is contributed by AnkitRai01
// C# program to implement// the above approach using System; class GFG { // Function to count array indices // whose removal makes sum of odd and // even indexed elements equal static int cntIndexesToMakeBalance(int[] arr, int n) { // If size of the array is 1 if (n == 1) { return 1; } // If size of the array is 2 if (n == 2) return 0; // Stores sum of even-indexed // elements of the given array int sumEven = 0; // Stores sum of odd-indexed // elements of the given array int sumOdd = 0; // Traverse the array for (int i = 0; i < n; i++) { // If i is an even number if (i % 2 == 0) { // Update sumEven sumEven += arr[i]; } // If i is an odd number else { // Update sumOdd sumOdd += arr[i]; } } // Stores sum of even-indexed // array elements till i-th index int currOdd = 0; // Stores sum of odd-indexed // array elements till i-th index int currEven = arr[0]; // Stores count of indices whose // removal makes sum of odd and // even indexed elements equal int res = 0; // Stores sum of even-indexed elements // after removing the i-th element int newEvenSum = 0; // Stores sum of odd-indexed elements // after removing the i-th element int newOddSum = 0; // Traverse the array for (int i = 1; i < n - 1; i++) { // If i is an odd number if (i % 2 != 0) { // Update currOdd currOdd += arr[i]; // Update newEvenSum newEvenSum = currEven + sumOdd - currOdd; // Update newOddSum newOddSum = currOdd + sumEven - currEven - arr[i]; } // If i is an even number else { // Update currEven currEven += arr[i]; // Update newOddSum newOddSum = currOdd + sumEven - currEven; // Update newEvenSum newEvenSum = currEven + sumOdd - currOdd - arr[i]; } // If newEvenSum is equal to newOddSum if (newEvenSum == newOddSum) { // Increase the count res++; } } // If sum of even-indexed and odd-indexed // elements is equal by removing the first element if (sumOdd == sumEven - arr[0]) { // Increase the count res++; } // If length of the array // is an odd number if (n % 2 == 1) { // If sum of even-indexed and odd-indexed // elements is equal by removing the last element if (sumOdd == sumEven - arr[n - 1]) { // Increase the count res++; } } // If length of the array // is an even number else { // If sum of even-indexed and odd-indexed // elements is equal by removing the last element if (sumEven == sumOdd - arr[n - 1]) { // Increase the count res++; } } return res; } // Drivers Code public static void Main () { int[] arr = { 1, 1, 1 }; int n = arr.Length; Console.WriteLine(cntIndexesToMakeBalance(arr, n)); } } // This code is contributed by susmitakundugoaldanga
<script> // Javascript program to implement// the above approach // Function to count array indices// whose removal makes sum of odd and// even indexed elements equalfunction cntIndexesToMakeBalance(arr, n){ // If size of the array is 1 if (n == 1) { return 1; } // If size of the array is 2 if (n == 2) return 0; // Stores sum of even-indexed // elements of the given array let sumEven = 0; // Stores sum of odd-indexed // elements of the given array let sumOdd = 0; // Traverse the array for (let i = 0; i < n; i++) { // If i is an even number if (i % 2 == 0) { // Update sumEven sumEven += arr[i]; } // If i is an odd number else { // Update sumOdd sumOdd += arr[i]; } } // Stores sum of even-indexed // array elements till i-th index let currOdd = 0; // Stores sum of odd-indexed // array elements till i-th index let currEven = arr[0]; // Stores count of indices whose // removal makes sum of odd and // even indexed elements equal let res = 0; // Stores sum of even-indexed elements // after removing the i-th element let newEvenSum = 0; // Stores sum of odd-indexed elements // after removing the i-th element let newOddSum = 0; // Traverse the array for (let i = 1; i < n - 1; i++) { // If i is an odd number if (i % 2) { // Update currOdd currOdd += arr[i]; // Update newEvenSum newEvenSum = currEven + sumOdd - currOdd; // Update newOddSum newOddSum = currOdd + sumEven - currEven - arr[i]; } // If i is an even number else { // Update currEven currEven += arr[i]; // Update newOddSum newOddSum = currOdd + sumEven - currEven; // Update newEvenSum newEvenSum = currEven + sumOdd - currOdd - arr[i]; } // If newEvenSum is equal to newOddSum if (newEvenSum == newOddSum) { // Increase the count res++; } } // If sum of even-indexed and odd-indexed // elements is equal by removing the first element if (sumOdd == sumEven - arr[0]) { // Increase the count res++; } // If length of the array // is an odd number if (n % 2 == 1) { // If sum of even-indexed and odd-indexed // elements is equal by removing the last element if (sumOdd == sumEven - arr[n - 1]) { // Increase the count res++; } } // If length of the array // is an even number else { // If sum of even-indexed and odd-indexed // elements is equal by removing the last element if (sumEven == sumOdd - arr[n - 1]) { // Increase the count res++; } } return res;} // Driver Code let arr = [ 1, 1, 1 ]; let n = arr.length; document.write(cntIndexesToMakeBalance(arr, n)); // This code is contributed by Mayank Tyagi</script>
3
Time Complexity: O(N) Auxiliary Space: O(1)
ankthon
susmitakundugoaldanga
mayanktyagi1709
achy97
Dunzo
interview-preparation
Arrays
Greedy
Mathematical
Dunzo
Arrays
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Huffman Coding | Greedy Algo-3
Write a program to print all permutations of a given string
|
[
{
"code": null,
"e": 25416,
"s": 25388,
"text": "\n27 Jun, 2021"
},
{
"code": null,
"e": 25613,
"s": 25416,
"text": "Given an array, arr[] of size N, the task is to find the count of array indices such that removing an element from these indices makes the sum of even-indexed and odd-indexed array elements equal."
},
{
"code": null,
"e": 25623,
"s": 25613,
"text": "Examples:"
},
{
"code": null,
"e": 25812,
"s": 25623,
"text": "Input: arr[] = { 2, 1, 6, 4 } Output: 1 Explanation: Removing arr[1] from the array modifies arr[] to { 2, 6, 4 } such that, arr[0] + arr[2] = arr[1]. Therefore, the required output is 1. "
},
{
"code": null,
"e": 26169,
"s": 25812,
"text": "Input: arr[] = { 1, 1, 1 } Output: 3 Explanation: Removing arr[0] from the given array modifies arr[] to { 1, 1 } such that arr[0] = arr[1] Removing arr[1] from the given array modifies arr[] to { 1, 1 } such that arr[0] = arr[1] Removing arr[2] from the given array modifies arr[] to { 1, 1 } such that arr[0] = arr[1] Therefore, the required output is 3."
},
{
"code": null,
"e": 26475,
"s": 26169,
"text": "Naive Approach: The simplest approach to solve this problem is to traverse the array and for each array element, check if removing the element from the array makes the sum of even-indexed and odd-indexed array elements equal or not. If found to be true, then increment the count. Finally, print the count."
},
{
"code": null,
"e": 26520,
"s": 26475,
"text": "Time Complexity: O(N2) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 26794,
"s": 26520,
"text": "Efficient Approach: The above approach can be optimized based on the observation that removing any element from the given array makes even indices of succeeding elements as odd and odd indices of the succeeding elements as even. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 26935,
"s": 26794,
"text": "Initialize two variables, say evenSum and oddSum, to store the sum of odd-indexed and even-indexed elements of the given array respectively."
},
{
"code": null,
"e": 26972,
"s": 26935,
"text": "Traverse the array using variable i."
},
{
"code": null,
"e": 27212,
"s": 26972,
"text": "Remove every ith element of the array and update the sum of the remaining even-indexed elements and the odd-indexed elements based on the above observation. Check if the sums are equal or not. If found to be true, then increment the count."
},
{
"code": null,
"e": 27247,
"s": 27212,
"text": "Finally, print the count obtained."
},
{
"code": null,
"e": 27298,
"s": 27247,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27302,
"s": 27298,
"text": "C++"
},
{
"code": null,
"e": 27307,
"s": 27302,
"text": "Java"
},
{
"code": null,
"e": 27315,
"s": 27307,
"text": "Python3"
},
{
"code": null,
"e": 27318,
"s": 27315,
"text": "C#"
},
{
"code": null,
"e": 27329,
"s": 27318,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to count array indices// whose removal makes sum of odd and// even indexed elements equalint cntIndexesToMakeBalance(int arr[], int n){ // If size of the array is 1 if (n == 1) { return 1; } // If size of the array is 2 if (n == 2) return 0; // Stores sum of even-indexed // elements of the given array int sumEven = 0; // Stores sum of odd-indexed // elements of the given array int sumOdd = 0; // Traverse the array for (int i = 0; i < n; i++) { // If i is an even number if (i % 2 == 0) { // Update sumEven sumEven += arr[i]; } // If i is an odd number else { // Update sumOdd sumOdd += arr[i]; } } // Stores sum of even-indexed // array elements till i-th index int currOdd = 0; // Stores sum of odd-indexed // array elements till i-th index int currEven = arr[0]; // Stores count of indices whose // removal makes sum of odd and // even indexed elements equal int res = 0; // Stores sum of even-indexed elements // after removing the i-th element int newEvenSum = 0; // Stores sum of odd-indexed elements // after removing the i-th element int newOddSum = 0; // Traverse the array for (int i = 1; i < n - 1; i++) { // If i is an odd number if (i % 2) { // Update currOdd currOdd += arr[i]; // Update newEvenSum newEvenSum = currEven + sumOdd - currOdd; // Update newOddSum newOddSum = currOdd + sumEven - currEven - arr[i]; } // If i is an even number else { // Update currEven currEven += arr[i]; // Update newOddSum newOddSum = currOdd + sumEven - currEven; // Update newEvenSum newEvenSum = currEven + sumOdd - currOdd - arr[i]; } // If newEvenSum is equal to newOddSum if (newEvenSum == newOddSum) { // Increase the count res++; } } // If sum of even-indexed and odd-indexed // elements is equal by removing the first element if (sumOdd == sumEven - arr[0]) { // Increase the count res++; } // If length of the array // is an odd number if (n % 2 == 1) { // If sum of even-indexed and odd-indexed // elements is equal by removing the last element if (sumOdd == sumEven - arr[n - 1]) { // Increase the count res++; } } // If length of the array // is an even number else { // If sum of even-indexed and odd-indexed // elements is equal by removing the last element if (sumEven == sumOdd - arr[n - 1]) { // Increase the count res++; } } return res;} // Driver Codeint main(){ int arr[] = { 1, 1, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << cntIndexesToMakeBalance(arr, n); return 0;}",
"e": 30543,
"s": 27329,
"text": null
},
{
"code": "// Java program to implement// the above approachclass GFG { // Function to count array indices // whose removal makes sum of odd and // even indexed elements equal static int cntIndexesToMakeBalance(int arr[], int n) { // If size of the array is 1 if (n == 1) { return 1; } // If size of the array is 2 if (n == 2) return 0; // Stores sum of even-indexed // elements of the given array int sumEven = 0; // Stores sum of odd-indexed // elements of the given array int sumOdd = 0; // Traverse the array for (int i = 0; i < n; i++) { // If i is an even number if (i % 2 == 0) { // Update sumEven sumEven += arr[i]; } // If i is an odd number else { // Update sumOdd sumOdd += arr[i]; } } // Stores sum of even-indexed // array elements till i-th index int currOdd = 0; // Stores sum of odd-indexed // array elements till i-th index int currEven = arr[0]; // Stores count of indices whose // removal makes sum of odd and // even indexed elements equal int res = 0; // Stores sum of even-indexed elements // after removing the i-th element int newEvenSum = 0; // Stores sum of odd-indexed elements // after removing the i-th element int newOddSum = 0; // Traverse the array for (int i = 1; i < n - 1; i++) { // If i is an odd number if (i % 2 != 0) { // Update currOdd currOdd += arr[i]; // Update newEvenSum newEvenSum = currEven + sumOdd - currOdd; // Update newOddSum newOddSum = currOdd + sumEven - currEven - arr[i]; } // If i is an even number else { // Update currEven currEven += arr[i]; // Update newOddSum newOddSum = currOdd + sumEven - currEven; // Update newEvenSum newEvenSum = currEven + sumOdd - currOdd - arr[i]; } // If newEvenSum is equal to newOddSum if (newEvenSum == newOddSum) { // Increase the count res++; } } // If sum of even-indexed and odd-indexed // elements is equal by removing the first element if (sumOdd == sumEven - arr[0]) { // Increase the count res++; } // If length of the array // is an odd number if (n % 2 == 1) { // If sum of even-indexed and odd-indexed // elements is equal by removing the last element if (sumOdd == sumEven - arr[n - 1]) { // Increase the count res++; } } // If length of the array // is an even number else { // If sum of even-indexed and odd-indexed // elements is equal by removing the last element if (sumEven == sumOdd - arr[n - 1]) { // Increase the count res++; } } return res; } // Driver Code public static void main (String[] args) { int arr[] = { 1, 1, 1 }; int n = arr.length; System.out.println(cntIndexesToMakeBalance(arr, n)); }} // This code is contributed by AnkitRai01",
"e": 34500,
"s": 30543,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to count array indices# whose removal makes sum of odd and# even indexed elements equaldef cntIndexesToMakeBalance(arr, n): # If size of the array is 1 if (n == 1): return 1 # If size of the array is 2 if (n == 2): return 0 # Stores sum of even-indexed # elements of the given array sumEven = 0 # Stores sum of odd-indexed # elements of the given array sumOdd = 0 # Traverse the array for i in range(n): # If i is an even number if (i % 2 == 0): # Update sumEven sumEven += arr[i] # If i is an odd number else: # Update sumOdd sumOdd += arr[i] # Stores sum of even-indexed # array elements till i-th index currOdd = 0 # Stores sum of odd-indexed # array elements till i-th index currEven = arr[0] # Stores count of indices whose # removal makes sum of odd and # even indexed elements equal res = 0 # Stores sum of even-indexed elements # after removing the i-th element newEvenSum = 0 # Stores sum of odd-indexed elements # after removing the i-th element newOddSum = 0 # Traverse the array for i in range(1, n - 1): # If i is an odd number if (i % 2): # Update currOdd currOdd += arr[i] # Update newEvenSum newEvenSum = (currEven + sumOdd - currOdd) # Update newOddSum newOddSum = (currOdd + sumEven - currEven - arr[i]) # If i is an even number else: # Update currEven currEven += arr[i] # Update newOddSum newOddSum = (currOdd + sumEven - currEven) # Update newEvenSum newEvenSum = (currEven + sumOdd - currOdd - arr[i]) # If newEvenSum is equal to newOddSum if (newEvenSum == newOddSum): # Increase the count res += 1 # If sum of even-indexed and odd-indexed # elements is equal by removing the first # element if (sumOdd == sumEven - arr[0]): # Increase the count res += 1 # If length of the array # is an odd number if (n % 2 == 1): # If sum of even-indexed and odd-indexed # elements is equal by removing the last # element if (sumOdd == sumEven - arr[n - 1]): # Increase the count res += 1 # If length of the array # is an even number else: # If sum of even-indexed and odd-indexed # elements is equal by removing the last # element if (sumEven == sumOdd - arr[n - 1]): # Increase the count res += 1 return res # Driver Codeif __name__ == \"__main__\" : arr = [ 1, 1, 1 ] n = len(arr) print(cntIndexesToMakeBalance(arr, n)) # This code is contributed by AnkitRai01",
"e": 37527,
"s": 34500,
"text": null
},
{
"code": "// C# program to implement// the above approach using System; class GFG { // Function to count array indices // whose removal makes sum of odd and // even indexed elements equal static int cntIndexesToMakeBalance(int[] arr, int n) { // If size of the array is 1 if (n == 1) { return 1; } // If size of the array is 2 if (n == 2) return 0; // Stores sum of even-indexed // elements of the given array int sumEven = 0; // Stores sum of odd-indexed // elements of the given array int sumOdd = 0; // Traverse the array for (int i = 0; i < n; i++) { // If i is an even number if (i % 2 == 0) { // Update sumEven sumEven += arr[i]; } // If i is an odd number else { // Update sumOdd sumOdd += arr[i]; } } // Stores sum of even-indexed // array elements till i-th index int currOdd = 0; // Stores sum of odd-indexed // array elements till i-th index int currEven = arr[0]; // Stores count of indices whose // removal makes sum of odd and // even indexed elements equal int res = 0; // Stores sum of even-indexed elements // after removing the i-th element int newEvenSum = 0; // Stores sum of odd-indexed elements // after removing the i-th element int newOddSum = 0; // Traverse the array for (int i = 1; i < n - 1; i++) { // If i is an odd number if (i % 2 != 0) { // Update currOdd currOdd += arr[i]; // Update newEvenSum newEvenSum = currEven + sumOdd - currOdd; // Update newOddSum newOddSum = currOdd + sumEven - currEven - arr[i]; } // If i is an even number else { // Update currEven currEven += arr[i]; // Update newOddSum newOddSum = currOdd + sumEven - currEven; // Update newEvenSum newEvenSum = currEven + sumOdd - currOdd - arr[i]; } // If newEvenSum is equal to newOddSum if (newEvenSum == newOddSum) { // Increase the count res++; } } // If sum of even-indexed and odd-indexed // elements is equal by removing the first element if (sumOdd == sumEven - arr[0]) { // Increase the count res++; } // If length of the array // is an odd number if (n % 2 == 1) { // If sum of even-indexed and odd-indexed // elements is equal by removing the last element if (sumOdd == sumEven - arr[n - 1]) { // Increase the count res++; } } // If length of the array // is an even number else { // If sum of even-indexed and odd-indexed // elements is equal by removing the last element if (sumEven == sumOdd - arr[n - 1]) { // Increase the count res++; } } return res; } // Drivers Code public static void Main () { int[] arr = { 1, 1, 1 }; int n = arr.Length; Console.WriteLine(cntIndexesToMakeBalance(arr, n)); } } // This code is contributed by susmitakundugoaldanga",
"e": 41535,
"s": 37527,
"text": null
},
{
"code": "<script> // Javascript program to implement// the above approach // Function to count array indices// whose removal makes sum of odd and// even indexed elements equalfunction cntIndexesToMakeBalance(arr, n){ // If size of the array is 1 if (n == 1) { return 1; } // If size of the array is 2 if (n == 2) return 0; // Stores sum of even-indexed // elements of the given array let sumEven = 0; // Stores sum of odd-indexed // elements of the given array let sumOdd = 0; // Traverse the array for (let i = 0; i < n; i++) { // If i is an even number if (i % 2 == 0) { // Update sumEven sumEven += arr[i]; } // If i is an odd number else { // Update sumOdd sumOdd += arr[i]; } } // Stores sum of even-indexed // array elements till i-th index let currOdd = 0; // Stores sum of odd-indexed // array elements till i-th index let currEven = arr[0]; // Stores count of indices whose // removal makes sum of odd and // even indexed elements equal let res = 0; // Stores sum of even-indexed elements // after removing the i-th element let newEvenSum = 0; // Stores sum of odd-indexed elements // after removing the i-th element let newOddSum = 0; // Traverse the array for (let i = 1; i < n - 1; i++) { // If i is an odd number if (i % 2) { // Update currOdd currOdd += arr[i]; // Update newEvenSum newEvenSum = currEven + sumOdd - currOdd; // Update newOddSum newOddSum = currOdd + sumEven - currEven - arr[i]; } // If i is an even number else { // Update currEven currEven += arr[i]; // Update newOddSum newOddSum = currOdd + sumEven - currEven; // Update newEvenSum newEvenSum = currEven + sumOdd - currOdd - arr[i]; } // If newEvenSum is equal to newOddSum if (newEvenSum == newOddSum) { // Increase the count res++; } } // If sum of even-indexed and odd-indexed // elements is equal by removing the first element if (sumOdd == sumEven - arr[0]) { // Increase the count res++; } // If length of the array // is an odd number if (n % 2 == 1) { // If sum of even-indexed and odd-indexed // elements is equal by removing the last element if (sumOdd == sumEven - arr[n - 1]) { // Increase the count res++; } } // If length of the array // is an even number else { // If sum of even-indexed and odd-indexed // elements is equal by removing the last element if (sumEven == sumOdd - arr[n - 1]) { // Increase the count res++; } } return res;} // Driver Code let arr = [ 1, 1, 1 ]; let n = arr.length; document.write(cntIndexesToMakeBalance(arr, n)); // This code is contributed by Mayank Tyagi</script>",
"e": 44729,
"s": 41535,
"text": null
},
{
"code": null,
"e": 44731,
"s": 44729,
"text": "3"
},
{
"code": null,
"e": 44777,
"s": 44733,
"text": "Time Complexity: O(N) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 44785,
"s": 44777,
"text": "ankthon"
},
{
"code": null,
"e": 44807,
"s": 44785,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 44823,
"s": 44807,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 44830,
"s": 44823,
"text": "achy97"
},
{
"code": null,
"e": 44836,
"s": 44830,
"text": "Dunzo"
},
{
"code": null,
"e": 44858,
"s": 44836,
"text": "interview-preparation"
},
{
"code": null,
"e": 44865,
"s": 44858,
"text": "Arrays"
},
{
"code": null,
"e": 44872,
"s": 44865,
"text": "Greedy"
},
{
"code": null,
"e": 44885,
"s": 44872,
"text": "Mathematical"
},
{
"code": null,
"e": 44891,
"s": 44885,
"text": "Dunzo"
},
{
"code": null,
"e": 44898,
"s": 44891,
"text": "Arrays"
},
{
"code": null,
"e": 44905,
"s": 44898,
"text": "Greedy"
},
{
"code": null,
"e": 44918,
"s": 44905,
"text": "Mathematical"
},
{
"code": null,
"e": 45016,
"s": 44918,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45025,
"s": 45016,
"text": "Comments"
},
{
"code": null,
"e": 45038,
"s": 45025,
"text": "Old Comments"
},
{
"code": null,
"e": 45086,
"s": 45038,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 45130,
"s": 45086,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 45162,
"s": 45130,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 45185,
"s": 45162,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 45199,
"s": 45185,
"text": "Linear Search"
},
{
"code": null,
"e": 45250,
"s": 45199,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 45308,
"s": 45250,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 45359,
"s": 45308,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 45390,
"s": 45359,
"text": "Huffman Coding | Greedy Algo-3"
}
] |
How to get circular buttons in bootstrap 4 ? - GeeksforGeeks
|
08 Jul, 2019
It is an open source toolkit for developing with the HTML, CSS, and JS. It includes several types of buttons, styles, fonts each of them serving its own semantic purpose which is predefined, with a few extras thrown for more control. You can use Bootstrap custom button styles to create your buttons and more with support for multiple sizes, states, and more.Bootstrap does not provide any circular buttons by default. If we want to include circular buttons in a web page then with the help of Bootstrap 4 and a little bit of CSS, you can create your own circular buttons for your web page or application.
Example:
<!DOCTYPE html><html> <head> <title> How to get circular buttons in bootstrap 4 ? </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src= "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style type="text/css"> h1 { color:green; } .xyz { background-size: auto; text-align: center; padding-top: 100px; } .btn-circle.btn-sm { width: 30px; height: 30px; padding: 6px 0px; border-radius: 15px; font-size: 8px; text-align: center; } .btn-circle.btn-md { width: 50px; height: 50px; padding: 7px 10px; border-radius: 25px; font-size: 10px; text-align: center; } .btn-circle.btn-xl { width: 70px; height: 70px; padding: 10px 16px; border-radius: 35px; font-size: 12px; text-align: center; } </style></head> <body class="xyz"> <h1>GeeksforGeeks</h1> <h4>Normal Circle Buttons</h4> <button type="button" class="btn btn-primary btn-circle btn-sm">Blue</button> <button type="button" class="btn btn-secondary btn-circle btn-sm">Gray</button> <button type="button" class="btn btn-success btn-circle btn-sm">Green</button> <button type="button" class="btn btn-danger btn-circle btn-sm">Red</button> <button type="button" class="btn btn-warning btn-circle btn-sm">Yellow</button> <button type="button" class="btn btn-light btn-circle btn-sm">White</button> <button type="button" class="btn btn-dark btn-circle btn-sm">Black</button> <h4>Large Circle Buttons</h4> <button type="button" class="btn btn-primary btn-circle btn-xl">Blue</button> <button type="button" class="btn btn-secondary btn-circle btn-xl">Gray</button> <button type="button" class="btn btn-success btn-circle btn-xl">Green</button> <button type="button" class="btn btn-danger btn-circle btn-xl">Red</button> <button type="button" class="btn btn-warning btn-circle btn-xl">Yellow</button> <button type="button" class="btn btn-light btn-circle btn-xl">White</button> <button type="button" class="btn btn-dark btn-circle btn-xl">Black</button></body> </html>
Output:With the help of the following code we can easily add circular buttons using Bootstrap 4. Following is an image of the various kinds of circular buttons obtained.
Bootstrap-4
Picked
Bootstrap
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to pass data into a bootstrap modal?
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
Difference between Bootstrap 4 and Bootstrap 5
How to Use Bootstrap with React?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24419,
"s": 24391,
"text": "\n08 Jul, 2019"
},
{
"code": null,
"e": 25025,
"s": 24419,
"text": "It is an open source toolkit for developing with the HTML, CSS, and JS. It includes several types of buttons, styles, fonts each of them serving its own semantic purpose which is predefined, with a few extras thrown for more control. You can use Bootstrap custom button styles to create your buttons and more with support for multiple sizes, states, and more.Bootstrap does not provide any circular buttons by default. If we want to include circular buttons in a web page then with the help of Bootstrap 4 and a little bit of CSS, you can create your own circular buttons for your web page or application."
},
{
"code": null,
"e": 25034,
"s": 25025,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to get circular buttons in bootstrap 4 ? </title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src= \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style type=\"text/css\"> h1 { color:green; } .xyz { background-size: auto; text-align: center; padding-top: 100px; } .btn-circle.btn-sm { width: 30px; height: 30px; padding: 6px 0px; border-radius: 15px; font-size: 8px; text-align: center; } .btn-circle.btn-md { width: 50px; height: 50px; padding: 7px 10px; border-radius: 25px; font-size: 10px; text-align: center; } .btn-circle.btn-xl { width: 70px; height: 70px; padding: 10px 16px; border-radius: 35px; font-size: 12px; text-align: center; } </style></head> <body class=\"xyz\"> <h1>GeeksforGeeks</h1> <h4>Normal Circle Buttons</h4> <button type=\"button\" class=\"btn btn-primary btn-circle btn-sm\">Blue</button> <button type=\"button\" class=\"btn btn-secondary btn-circle btn-sm\">Gray</button> <button type=\"button\" class=\"btn btn-success btn-circle btn-sm\">Green</button> <button type=\"button\" class=\"btn btn-danger btn-circle btn-sm\">Red</button> <button type=\"button\" class=\"btn btn-warning btn-circle btn-sm\">Yellow</button> <button type=\"button\" class=\"btn btn-light btn-circle btn-sm\">White</button> <button type=\"button\" class=\"btn btn-dark btn-circle btn-sm\">Black</button> <h4>Large Circle Buttons</h4> <button type=\"button\" class=\"btn btn-primary btn-circle btn-xl\">Blue</button> <button type=\"button\" class=\"btn btn-secondary btn-circle btn-xl\">Gray</button> <button type=\"button\" class=\"btn btn-success btn-circle btn-xl\">Green</button> <button type=\"button\" class=\"btn btn-danger btn-circle btn-xl\">Red</button> <button type=\"button\" class=\"btn btn-warning btn-circle btn-xl\">Yellow</button> <button type=\"button\" class=\"btn btn-light btn-circle btn-xl\">White</button> <button type=\"button\" class=\"btn btn-dark btn-circle btn-xl\">Black</button></body> </html> ",
"e": 27830,
"s": 25034,
"text": null
},
{
"code": null,
"e": 28000,
"s": 27830,
"text": "Output:With the help of the following code we can easily add circular buttons using Bootstrap 4. Following is an image of the various kinds of circular buttons obtained."
},
{
"code": null,
"e": 28012,
"s": 28000,
"text": "Bootstrap-4"
},
{
"code": null,
"e": 28019,
"s": 28012,
"text": "Picked"
},
{
"code": null,
"e": 28029,
"s": 28019,
"text": "Bootstrap"
},
{
"code": null,
"e": 28046,
"s": 28029,
"text": "Web Technologies"
},
{
"code": null,
"e": 28073,
"s": 28046,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28171,
"s": 28073,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28180,
"s": 28171,
"text": "Comments"
},
{
"code": null,
"e": 28193,
"s": 28180,
"text": "Old Comments"
},
{
"code": null,
"e": 28234,
"s": 28193,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 28275,
"s": 28234,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 28338,
"s": 28275,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 28385,
"s": 28338,
"text": "Difference between Bootstrap 4 and Bootstrap 5"
},
{
"code": null,
"e": 28418,
"s": 28385,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 28474,
"s": 28418,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 28507,
"s": 28474,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28569,
"s": 28507,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28612,
"s": 28569,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to redefine a color for a specific value in a Matplotlib colormap?
|
To redefine a color for a specific value in matplotlib colormap, we can take the following steps −
Get a colormap instance, defaulting to rc values if *name* is None using get_cmap() method, with gray colormap.
Get a colormap instance, defaulting to rc values if *name* is None using get_cmap() method, with gray colormap.
Set the color for low out-of-range values when "norm.clip = False" using set_under() method.
Set the color for low out-of-range values when "norm.clip = False" using set_under() method.
Using imshow() method, display data an image, i.e., on a 2D regular raster.
Using imshow() method, display data an image, i.e., on a 2D regular raster.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt, cm
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
cmap = cm.get_cmap('gray')
cmap.set_under('red')
plt.imshow(np.arange(25).reshape(5, 5),
interpolation='none',
cmap=cmap,
vmin=.001)
plt.show()
|
[
{
"code": null,
"e": 1161,
"s": 1062,
"text": "To redefine a color for a specific value in matplotlib colormap, we can take the following steps −"
},
{
"code": null,
"e": 1273,
"s": 1161,
"text": "Get a colormap instance, defaulting to rc values if *name* is None using get_cmap() method, with gray colormap."
},
{
"code": null,
"e": 1385,
"s": 1273,
"text": "Get a colormap instance, defaulting to rc values if *name* is None using get_cmap() method, with gray colormap."
},
{
"code": null,
"e": 1478,
"s": 1385,
"text": "Set the color for low out-of-range values when \"norm.clip = False\" using set_under() method."
},
{
"code": null,
"e": 1571,
"s": 1478,
"text": "Set the color for low out-of-range values when \"norm.clip = False\" using set_under() method."
},
{
"code": null,
"e": 1647,
"s": 1571,
"text": "Using imshow() method, display data an image, i.e., on a 2D regular raster."
},
{
"code": null,
"e": 1723,
"s": 1647,
"text": "Using imshow() method, display data an image, i.e., on a 2D regular raster."
},
{
"code": null,
"e": 1765,
"s": 1723,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1807,
"s": 1765,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2107,
"s": 1807,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt, cm\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ncmap = cm.get_cmap('gray')\ncmap.set_under('red')\nplt.imshow(np.arange(25).reshape(5, 5),\n interpolation='none',\n cmap=cmap,\n vmin=.001)\nplt.show()"
}
] |
Ruby | String Interpolation - GeeksforGeeks
|
24 Sep, 2019
String Interpolation, it is all about combining strings together, but not by using the + operator. String Interpolation works only when we use double quotes (“”) for the string formation. String Interpolation provides an easy way to process String literals. String Interpolation refers to substitution of defined variables or expressions in a given String with respected values. This is how, string Interpolation works, it executes whatever that is executable.Let’s see how to execute numbers and strings.Syntax:
#{variable}
The above syntax specifies that the things inside {} are executable objects or variables.Below are the examples to understand :Example :
# Ruby Program of String Interpolationa = 1b = 4puts "The number #{a} is less than #{b}"
Output :
The number 1 is less than 4
Example:
# Ruby Program of String Interpolation s = 'Groot';n = 16 # takes this as entire new stringputs "s age = n"; # interpolationputs "#{s} age=#{n}"; # if number not converted to string throws an errorputs s+" age="+n.to_s;
s age=n
Groot age=16
Groot age=16
So, the only advantage, We don’t have to convert numbers into a string because ruby takes care of it.
let’s say string=”weds” In string concatenation, if we are concatenating strings like (“hela “+string+” puri”), it creates 3 string objects, it moves from right-to-left, it first creates ” puri” object1, + method sticks the puri with the existing string together and returns weds puri object2 and this again gets stick by + method and forms the final hela weds puri object3. Eventually, the objects(1, 2) created in this process gets terminated as their are of no use.
In String Interpolation, it creates an only one object for (“hela “+string+” puri”) and embeds the existing string(weds)to it. In both the case, in the end, it creates one object but why prefer Interpolation over concatenation. Two reasons, no need for additional conversions of datatypes to string ruby takes care of it and this process is most of the developers kinda use.
Strings can not only contain text. They can also contain control characters. Difference between single or double quotes is that double quotes allow for escape sequences while single quotes do not allow for it.Example :
# Ruby program of sting Interpolationputs 'guardians\nGroot'; # gets executes and prints Groot on a newline.puts "guardians\nGroot"; # takes care of control characters.puts "hela\nweds\tpuri";
Output:
guardians\nGroot
guardians
Groot
hela
weds puri
In above example, \n is the escape sequence that stands for the “newline” character.
Picked
Ruby-String
Ruby
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Enumerator each_with_index function
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
Ruby | Enumerable find() function
Ruby | pop() function
Ruby | Types of Variables
Ruby | Operators
Ruby | Class Method and Variables
Ruby | Types of Iterators
Ruby | Array collect() operation
Ruby | String concat Method
|
[
{
"code": null,
"e": 23986,
"s": 23958,
"text": "\n24 Sep, 2019"
},
{
"code": null,
"e": 24499,
"s": 23986,
"text": "String Interpolation, it is all about combining strings together, but not by using the + operator. String Interpolation works only when we use double quotes (“”) for the string formation. String Interpolation provides an easy way to process String literals. String Interpolation refers to substitution of defined variables or expressions in a given String with respected values. This is how, string Interpolation works, it executes whatever that is executable.Let’s see how to execute numbers and strings.Syntax:"
},
{
"code": null,
"e": 24511,
"s": 24499,
"text": "#{variable}"
},
{
"code": null,
"e": 24648,
"s": 24511,
"text": "The above syntax specifies that the things inside {} are executable objects or variables.Below are the examples to understand :Example :"
},
{
"code": "# Ruby Program of String Interpolationa = 1b = 4puts \"The number #{a} is less than #{b}\"",
"e": 24737,
"s": 24648,
"text": null
},
{
"code": null,
"e": 24746,
"s": 24737,
"text": "Output :"
},
{
"code": null,
"e": 24774,
"s": 24746,
"text": "The number 1 is less than 4"
},
{
"code": null,
"e": 24783,
"s": 24774,
"text": "Example:"
},
{
"code": "# Ruby Program of String Interpolation s = 'Groot';n = 16 # takes this as entire new stringputs \"s age = n\"; # interpolationputs \"#{s} age=#{n}\"; # if number not converted to string throws an errorputs s+\" age=\"+n.to_s;",
"e": 25007,
"s": 24783,
"text": null
},
{
"code": null,
"e": 25042,
"s": 25007,
"text": "s age=n\nGroot age=16\nGroot age=16\n"
},
{
"code": null,
"e": 25144,
"s": 25042,
"text": "So, the only advantage, We don’t have to convert numbers into a string because ruby takes care of it."
},
{
"code": null,
"e": 25613,
"s": 25144,
"text": "let’s say string=”weds” In string concatenation, if we are concatenating strings like (“hela “+string+” puri”), it creates 3 string objects, it moves from right-to-left, it first creates ” puri” object1, + method sticks the puri with the existing string together and returns weds puri object2 and this again gets stick by + method and forms the final hela weds puri object3. Eventually, the objects(1, 2) created in this process gets terminated as their are of no use."
},
{
"code": null,
"e": 25988,
"s": 25613,
"text": "In String Interpolation, it creates an only one object for (“hela “+string+” puri”) and embeds the existing string(weds)to it. In both the case, in the end, it creates one object but why prefer Interpolation over concatenation. Two reasons, no need for additional conversions of datatypes to string ruby takes care of it and this process is most of the developers kinda use."
},
{
"code": null,
"e": 26207,
"s": 25988,
"text": "Strings can not only contain text. They can also contain control characters. Difference between single or double quotes is that double quotes allow for escape sequences while single quotes do not allow for it.Example :"
},
{
"code": "# Ruby program of sting Interpolationputs 'guardians\\nGroot'; # gets executes and prints Groot on a newline.puts \"guardians\\nGroot\"; # takes care of control characters.puts \"hela\\nweds\\tpuri\";",
"e": 26402,
"s": 26207,
"text": null
},
{
"code": null,
"e": 26410,
"s": 26402,
"text": "Output:"
},
{
"code": null,
"e": 26462,
"s": 26410,
"text": "guardians\\nGroot\nguardians\nGroot\nhela\nweds puri\n"
},
{
"code": null,
"e": 26547,
"s": 26462,
"text": "In above example, \\n is the escape sequence that stands for the “newline” character."
},
{
"code": null,
"e": 26554,
"s": 26547,
"text": "Picked"
},
{
"code": null,
"e": 26566,
"s": 26554,
"text": "Ruby-String"
},
{
"code": null,
"e": 26571,
"s": 26566,
"text": "Ruby"
},
{
"code": null,
"e": 26590,
"s": 26571,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26688,
"s": 26590,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26697,
"s": 26688,
"text": "Comments"
},
{
"code": null,
"e": 26710,
"s": 26697,
"text": "Old Comments"
},
{
"code": null,
"e": 26753,
"s": 26710,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 26821,
"s": 26753,
"text": "Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1"
},
{
"code": null,
"e": 26855,
"s": 26821,
"text": "Ruby | Enumerable find() function"
},
{
"code": null,
"e": 26877,
"s": 26855,
"text": "Ruby | pop() function"
},
{
"code": null,
"e": 26903,
"s": 26877,
"text": "Ruby | Types of Variables"
},
{
"code": null,
"e": 26920,
"s": 26903,
"text": "Ruby | Operators"
},
{
"code": null,
"e": 26954,
"s": 26920,
"text": "Ruby | Class Method and Variables"
},
{
"code": null,
"e": 26980,
"s": 26954,
"text": "Ruby | Types of Iterators"
},
{
"code": null,
"e": 27013,
"s": 26980,
"text": "Ruby | Array collect() operation"
}
] |
Using Logistic Regression to Create a Binary and Multiclass Classifier from Basics | by Naveen Venkatesan | Towards Data Science
|
As data science and machine learning have become an integral part of many fields in industry and academic research, basic literacy in these techniques can be very fruitful to identify trends in data, especially when the size of datasets rapidly increase. Having a background in experimental science, linear regression always seemed fairly intuitive, as we often fit our experimental data to theoretical models to extract material properties. Making a classifier (i.e. predicting if Team A will beat Team B based on several prior metrics), however, was not something I had used or had much experience with until I did some reading. In this article, I hope to succinctly describe how to create a classifier from scratch using logistic regression. In practice, you will probably use a package to do this such as scikit-learn or tensorflow, but understanding some of the underlying equations and algorithms will be extremely helpful in knowing what is going on “under the hood”.
Much of the work in this article was inspired by lessons from the Machine Learning class on Coursera taught by Andrew Ng.
We will use Python for all the code in this article, so let’s import all the packages that we will need:
Making discrete predictions is something we do all the time, probably without even thinking too much about how. For example, you’re looking at the menu at a restaurant — you read descriptions of different menu items, remember some tips from a food review you recently read, maybe ask the waiter a few questions, and make a discrete decision of what you want to order. If you have never eaten at this restaurant, you are essentially making an informed prediction based on what you think you will like.
To achieve similar behavior in our predictor algorithm, a great place to start would be to pick a mathematical function that essentially gives a binary output or 0 or 1. To do this, we can use the logistic or sigmoid function, which has the form:
We can code this function in Python and plot it as follows:
As shown in the plot, the sigmoid function rapidly changes from an output of near 0 to near 1 around x = 0. Since the output values are symmetric around y = 0.5, we can use this as the threshold for making out decision, where y ≥ 0.5 outputs 1 and y < 0.5 outputs 0.
To see this in action, let’s train some data!
The scenario we have is as follows — we are building a simple movie recommendation system that takes into account an average user score between 0 and 5 (across all users) and an average critic score between 0 and 5. Our model should then generate a decision boundary based on our input data to predict whether the current user will like the movie, and recommend it to them.
We will a set of random user and critic scores for 100 movies:
Now, let’s generate classifications — in this case, either the user liked the movie (1), or did not (0). To do so, we will use the following decision boundary function. We set the right hand side of this equation to 0 because it defines when the logistic function is equal to 0.5:
Note that in a real dataset, you would have no idea what the decision boundary’s functional form is. For the sake of this tutorial, we are defining a function and adding some noise to it so that the classification is not “perfect”.
Now, we can plot our initial data, where an orange circle represents a movie liked by the user, and a blue circle a movie that was not liked:
To determine how good our decision boundary is, we need to define a penalty for wrong predictions, which we will do by creating a cost function. Our predictions will be made as follows:
When P ≥ 0.5, we output 1 and when P < 0.5, we will output 0, where w0, w1, and w2 are the weights we are optimizing for.
To penalize wrong classifications, we can take advantage of the logarithm function, since log(1) = 0 and log(0) → -∞. We can use this to create two penalty functions as follows:
We can visualize this to more clearly see the effects of these penalty functions:
Using the facts that our outputs (y) are going to be either 0 or 1, we can elegantly combine these two penalty functions in one expression that encompasses both cases:
Now, when our output is 1 and we predict something close to 0 (first term), we incur a steep penalty — similarly, the same scenario occurs when our output is 0 and we predict something close to 1 (second term).
We can now take our penalty function and generalize it to m training examples — the label of the i-th training example is indicated by (i). We will also divide the total cost by m to get the mean penalty (just like in mean squared error in linear regression). This final expression is also known as the cost function. We will refer to our two features (user score and critic score) as x1 and x2.
To find the optimal decision boundary, we must minimize this cost function, which we can do with an algorithm called gradient descent, which essentially does two things: (1) finds the direction of maximum decrease by calculating the gradient of the cost function, and (2) update the weight values by moving along this gradient. To update the weights, we also provide a learning rate (α), which determines how much we move along this gradient. There is a trade-off in choosing a learning rate — too small and our algorithm takes too long to converge; too big, and our algorithm can actually diverge. More information about both gradient descent and the learning rate can be found at the linked articles. We therefore have the following update rule for each weight:
The final piece of the puzzle is calculating the partial derivatives in the above expressions. We can use the chain rule from calculus to break this down as follows:
Now, we can put it all together to get the following gradient expression and gradient descent update rule:
We can now initialize our variables to minimize the cost function.
All the gradient descent operations above are conducive to using matrix multiplication and linear algebra. First, we initialize our variables as following:
We can now rewrite the two earlier expressions for the cost function, gradient, and update function for the weights as follows, where the superscripted T signifies the transpose of the matrix:
Our variables can be initialized as follows (we will set all the weights equal to 0 to begin):
Now that the long wall of math is out of the way, let’s train our classifier model!
We must first define functions for the cost function and the gradient descent update. The following function calculates the cost and the gradient values and returns both:
When defining the gradient descent function, we must add an additional input called num_iters which tells the algorithms the number of iterations to take before returning the final optimized weights.
Now, after doing all that hard work, the following line trains our model!
J, w_train = gradient_descent(X, y, w, 0.5, 2000)
In a real situation, we would have split our training data in order to cross-validate and test our model, but for the purposes of this tutorial, we will use all of the training data.
To ensure that we are in fact decreasing the value of the cost function with each iteration, we can plot this:
And now the moment of truth — we can plot our decision boundary. The way that we will overlay this on our original plot is by defining a grid of points and then calculating the prediction value from the sigmoid function using our trained weights. We can then plot the contour where this prediction value is equal to 0.5.
Et, voilà!
We can now write a function to make predictions based on this trained model:
Now, let’s make a few predictions on new examples:
X_new = np.asarray([[1, 3.4, 4.1], [1, 2.5, 1.7], [1, 4.8, 2.3]])print(predict(X_new, w_train))>>> [[1.] [0.] [1.]]
Now that we’ve done all the hard work of making a binary classifier, extending this to more classes is fairly straightforward. We will use a strategy called one-vs.-all classification, where we train a binary classifier for each distinct class and choose the class that has the largest value returned by the sigmoid function.
Let’s build on the model from our binary example — this time the user can give a movie a score of 0-stars, 1-star, or 2-stars and we are trying to determine the decision boundaries based on user and critic scores.
First, we generate data again and apply two decision boundaries:
Our dataset looks as follows, where blue circles represent 0-stars, orange circles represent 1-star, and red circles represent 2-stars:
For each binary classifier that we train, we will need to relabel the data such that the outputs for our class of interest is set to 1 and all other labels are set to 0. As an example, if we have 3 groups A (0), B (1), and C (2) — we must make three binary classifiers:
(1) A set to 1, B and C set to 0
(2) B set to 1, A and C set to 0
(3) C set to 1, A and B set to 0
We have a function to relabel our data for each classifier:
Now, we do the same model training as in the binary classification section earlier, but three separate times:
Plotting the decision boundaries this time is a little more involved. We must calculate the prediction values at each point in our grid for each of our trained classifiers. We then choose the maximum prediction value at each point and assign it’s respective class based on which of the classifiers led to that maximum value. The contour lines we choose to plot are 0.5 (between 0 and 1) and 1.5 (between 1 and 2):
And after much anticipation, here are our trained decision boundaries!
Finally, let’s make a prediction function. To do this, we will use a little trick — we will make a prediction for each classifier in each of the examples. We will then append each set of predictions as a new column to a predictions matrix. Then, by going along each row and choosing the column index that has the maximum value, we automatically get out the classifier label!
X_new = np.array([[1, 1, 1], [1, 1, 4.2], [1, 4.5, 2.5]])print(predict_multi(X_new, [w_class1, w_class2, w_class3]))>>> [[0] [2] [1]]
There it is! A multiclass classifier made completely from scratch!
Thanks for reading! This article just scratches the surface of logistic regression and classification, but I hope that you enjoyed it. The examples presented can be found here. Again I owe a lot of the inspiration of this article to the Machine Learning class on Coursera taught by Andrew Ng.
|
[
{
"code": null,
"e": 1146,
"s": 171,
"text": "As data science and machine learning have become an integral part of many fields in industry and academic research, basic literacy in these techniques can be very fruitful to identify trends in data, especially when the size of datasets rapidly increase. Having a background in experimental science, linear regression always seemed fairly intuitive, as we often fit our experimental data to theoretical models to extract material properties. Making a classifier (i.e. predicting if Team A will beat Team B based on several prior metrics), however, was not something I had used or had much experience with until I did some reading. In this article, I hope to succinctly describe how to create a classifier from scratch using logistic regression. In practice, you will probably use a package to do this such as scikit-learn or tensorflow, but understanding some of the underlying equations and algorithms will be extremely helpful in knowing what is going on “under the hood”."
},
{
"code": null,
"e": 1268,
"s": 1146,
"text": "Much of the work in this article was inspired by lessons from the Machine Learning class on Coursera taught by Andrew Ng."
},
{
"code": null,
"e": 1373,
"s": 1268,
"text": "We will use Python for all the code in this article, so let’s import all the packages that we will need:"
},
{
"code": null,
"e": 1874,
"s": 1373,
"text": "Making discrete predictions is something we do all the time, probably without even thinking too much about how. For example, you’re looking at the menu at a restaurant — you read descriptions of different menu items, remember some tips from a food review you recently read, maybe ask the waiter a few questions, and make a discrete decision of what you want to order. If you have never eaten at this restaurant, you are essentially making an informed prediction based on what you think you will like."
},
{
"code": null,
"e": 2121,
"s": 1874,
"text": "To achieve similar behavior in our predictor algorithm, a great place to start would be to pick a mathematical function that essentially gives a binary output or 0 or 1. To do this, we can use the logistic or sigmoid function, which has the form:"
},
{
"code": null,
"e": 2181,
"s": 2121,
"text": "We can code this function in Python and plot it as follows:"
},
{
"code": null,
"e": 2448,
"s": 2181,
"text": "As shown in the plot, the sigmoid function rapidly changes from an output of near 0 to near 1 around x = 0. Since the output values are symmetric around y = 0.5, we can use this as the threshold for making out decision, where y ≥ 0.5 outputs 1 and y < 0.5 outputs 0."
},
{
"code": null,
"e": 2494,
"s": 2448,
"text": "To see this in action, let’s train some data!"
},
{
"code": null,
"e": 2868,
"s": 2494,
"text": "The scenario we have is as follows — we are building a simple movie recommendation system that takes into account an average user score between 0 and 5 (across all users) and an average critic score between 0 and 5. Our model should then generate a decision boundary based on our input data to predict whether the current user will like the movie, and recommend it to them."
},
{
"code": null,
"e": 2931,
"s": 2868,
"text": "We will a set of random user and critic scores for 100 movies:"
},
{
"code": null,
"e": 3212,
"s": 2931,
"text": "Now, let’s generate classifications — in this case, either the user liked the movie (1), or did not (0). To do so, we will use the following decision boundary function. We set the right hand side of this equation to 0 because it defines when the logistic function is equal to 0.5:"
},
{
"code": null,
"e": 3444,
"s": 3212,
"text": "Note that in a real dataset, you would have no idea what the decision boundary’s functional form is. For the sake of this tutorial, we are defining a function and adding some noise to it so that the classification is not “perfect”."
},
{
"code": null,
"e": 3586,
"s": 3444,
"text": "Now, we can plot our initial data, where an orange circle represents a movie liked by the user, and a blue circle a movie that was not liked:"
},
{
"code": null,
"e": 3772,
"s": 3586,
"text": "To determine how good our decision boundary is, we need to define a penalty for wrong predictions, which we will do by creating a cost function. Our predictions will be made as follows:"
},
{
"code": null,
"e": 3894,
"s": 3772,
"text": "When P ≥ 0.5, we output 1 and when P < 0.5, we will output 0, where w0, w1, and w2 are the weights we are optimizing for."
},
{
"code": null,
"e": 4072,
"s": 3894,
"text": "To penalize wrong classifications, we can take advantage of the logarithm function, since log(1) = 0 and log(0) → -∞. We can use this to create two penalty functions as follows:"
},
{
"code": null,
"e": 4154,
"s": 4072,
"text": "We can visualize this to more clearly see the effects of these penalty functions:"
},
{
"code": null,
"e": 4322,
"s": 4154,
"text": "Using the facts that our outputs (y) are going to be either 0 or 1, we can elegantly combine these two penalty functions in one expression that encompasses both cases:"
},
{
"code": null,
"e": 4533,
"s": 4322,
"text": "Now, when our output is 1 and we predict something close to 0 (first term), we incur a steep penalty — similarly, the same scenario occurs when our output is 0 and we predict something close to 1 (second term)."
},
{
"code": null,
"e": 4929,
"s": 4533,
"text": "We can now take our penalty function and generalize it to m training examples — the label of the i-th training example is indicated by (i). We will also divide the total cost by m to get the mean penalty (just like in mean squared error in linear regression). This final expression is also known as the cost function. We will refer to our two features (user score and critic score) as x1 and x2."
},
{
"code": null,
"e": 5693,
"s": 4929,
"text": "To find the optimal decision boundary, we must minimize this cost function, which we can do with an algorithm called gradient descent, which essentially does two things: (1) finds the direction of maximum decrease by calculating the gradient of the cost function, and (2) update the weight values by moving along this gradient. To update the weights, we also provide a learning rate (α), which determines how much we move along this gradient. There is a trade-off in choosing a learning rate — too small and our algorithm takes too long to converge; too big, and our algorithm can actually diverge. More information about both gradient descent and the learning rate can be found at the linked articles. We therefore have the following update rule for each weight:"
},
{
"code": null,
"e": 5859,
"s": 5693,
"text": "The final piece of the puzzle is calculating the partial derivatives in the above expressions. We can use the chain rule from calculus to break this down as follows:"
},
{
"code": null,
"e": 5966,
"s": 5859,
"text": "Now, we can put it all together to get the following gradient expression and gradient descent update rule:"
},
{
"code": null,
"e": 6033,
"s": 5966,
"text": "We can now initialize our variables to minimize the cost function."
},
{
"code": null,
"e": 6189,
"s": 6033,
"text": "All the gradient descent operations above are conducive to using matrix multiplication and linear algebra. First, we initialize our variables as following:"
},
{
"code": null,
"e": 6382,
"s": 6189,
"text": "We can now rewrite the two earlier expressions for the cost function, gradient, and update function for the weights as follows, where the superscripted T signifies the transpose of the matrix:"
},
{
"code": null,
"e": 6477,
"s": 6382,
"text": "Our variables can be initialized as follows (we will set all the weights equal to 0 to begin):"
},
{
"code": null,
"e": 6561,
"s": 6477,
"text": "Now that the long wall of math is out of the way, let’s train our classifier model!"
},
{
"code": null,
"e": 6732,
"s": 6561,
"text": "We must first define functions for the cost function and the gradient descent update. The following function calculates the cost and the gradient values and returns both:"
},
{
"code": null,
"e": 6932,
"s": 6732,
"text": "When defining the gradient descent function, we must add an additional input called num_iters which tells the algorithms the number of iterations to take before returning the final optimized weights."
},
{
"code": null,
"e": 7006,
"s": 6932,
"text": "Now, after doing all that hard work, the following line trains our model!"
},
{
"code": null,
"e": 7056,
"s": 7006,
"text": "J, w_train = gradient_descent(X, y, w, 0.5, 2000)"
},
{
"code": null,
"e": 7239,
"s": 7056,
"text": "In a real situation, we would have split our training data in order to cross-validate and test our model, but for the purposes of this tutorial, we will use all of the training data."
},
{
"code": null,
"e": 7350,
"s": 7239,
"text": "To ensure that we are in fact decreasing the value of the cost function with each iteration, we can plot this:"
},
{
"code": null,
"e": 7671,
"s": 7350,
"text": "And now the moment of truth — we can plot our decision boundary. The way that we will overlay this on our original plot is by defining a grid of points and then calculating the prediction value from the sigmoid function using our trained weights. We can then plot the contour where this prediction value is equal to 0.5."
},
{
"code": null,
"e": 7683,
"s": 7671,
"text": "Et, voilà!"
},
{
"code": null,
"e": 7760,
"s": 7683,
"text": "We can now write a function to make predictions based on this trained model:"
},
{
"code": null,
"e": 7811,
"s": 7760,
"text": "Now, let’s make a few predictions on new examples:"
},
{
"code": null,
"e": 7939,
"s": 7811,
"text": "X_new = np.asarray([[1, 3.4, 4.1], [1, 2.5, 1.7], [1, 4.8, 2.3]])print(predict(X_new, w_train))>>> [[1.] [0.] [1.]]"
},
{
"code": null,
"e": 8265,
"s": 7939,
"text": "Now that we’ve done all the hard work of making a binary classifier, extending this to more classes is fairly straightforward. We will use a strategy called one-vs.-all classification, where we train a binary classifier for each distinct class and choose the class that has the largest value returned by the sigmoid function."
},
{
"code": null,
"e": 8479,
"s": 8265,
"text": "Let’s build on the model from our binary example — this time the user can give a movie a score of 0-stars, 1-star, or 2-stars and we are trying to determine the decision boundaries based on user and critic scores."
},
{
"code": null,
"e": 8544,
"s": 8479,
"text": "First, we generate data again and apply two decision boundaries:"
},
{
"code": null,
"e": 8680,
"s": 8544,
"text": "Our dataset looks as follows, where blue circles represent 0-stars, orange circles represent 1-star, and red circles represent 2-stars:"
},
{
"code": null,
"e": 8950,
"s": 8680,
"text": "For each binary classifier that we train, we will need to relabel the data such that the outputs for our class of interest is set to 1 and all other labels are set to 0. As an example, if we have 3 groups A (0), B (1), and C (2) — we must make three binary classifiers:"
},
{
"code": null,
"e": 8983,
"s": 8950,
"text": "(1) A set to 1, B and C set to 0"
},
{
"code": null,
"e": 9016,
"s": 8983,
"text": "(2) B set to 1, A and C set to 0"
},
{
"code": null,
"e": 9049,
"s": 9016,
"text": "(3) C set to 1, A and B set to 0"
},
{
"code": null,
"e": 9109,
"s": 9049,
"text": "We have a function to relabel our data for each classifier:"
},
{
"code": null,
"e": 9219,
"s": 9109,
"text": "Now, we do the same model training as in the binary classification section earlier, but three separate times:"
},
{
"code": null,
"e": 9633,
"s": 9219,
"text": "Plotting the decision boundaries this time is a little more involved. We must calculate the prediction values at each point in our grid for each of our trained classifiers. We then choose the maximum prediction value at each point and assign it’s respective class based on which of the classifiers led to that maximum value. The contour lines we choose to plot are 0.5 (between 0 and 1) and 1.5 (between 1 and 2):"
},
{
"code": null,
"e": 9704,
"s": 9633,
"text": "And after much anticipation, here are our trained decision boundaries!"
},
{
"code": null,
"e": 10079,
"s": 9704,
"text": "Finally, let’s make a prediction function. To do this, we will use a little trick — we will make a prediction for each classifier in each of the examples. We will then append each set of predictions as a new column to a predictions matrix. Then, by going along each row and choosing the column index that has the maximum value, we automatically get out the classifier label!"
},
{
"code": null,
"e": 10225,
"s": 10079,
"text": "X_new = np.array([[1, 1, 1], [1, 1, 4.2], [1, 4.5, 2.5]])print(predict_multi(X_new, [w_class1, w_class2, w_class3]))>>> [[0] [2] [1]]"
},
{
"code": null,
"e": 10292,
"s": 10225,
"text": "There it is! A multiclass classifier made completely from scratch!"
}
] |
Mastering String Methods in Pandas | by Sadrach Pierre, Ph.D. | Towards Data Science
|
Pandas is a popular python library that enables easy to use data structures and data analysis tools. Pandas can be used for reading in data, generating statistics, aggregating, feature engineering for machine learning and much more. The Pandas library also provides a suite of tools for string/text manipulation.
In this post, we will walk through some of the most important string manipulation methods provided by pandas.
Let’s get started!
First, let’s import the Pandas library
import pandas as pd
Now, let’s define an example pandas series containing strings:
s = pd.Series(['python is awesome', 'java is just ok', 'c++ is overrated'])
Let’s print this series:
print(s)
We notice that the series has ‘dtype: object’, which is the default type automatically inferred. In general, it is better to have a dedicated type. Since the release of Pandas 1.0, we are now able to specify dedicated types. Make sure Pandas is updated by executing the following command in a terminal:
pip install -U pandas
We can specify ‘dtype: string’ as follows:
s1 = pd.Series(['python is awesome', 'java is just ok', 'c++ is overrated'], dtype='string')
Let’s print the series:
We can see that the series type is specified. It is best to specify the type, and not use the default ‘dtype: object’ because it allows accidental mixtures of types which is not advisable. For example, with ‘dtype: object’ you can have a series with integers, strings, and floats. For this reason, the contents of a ‘dtype: object’ can be vague.
Next, let’s look at some specific string methods. Let’s consider the ‘count()’ method. Let’s modify our series a bit for this example:
s = pd.Series(['python is awesome. I love python.', 'java is just ok. I like python more', 'c++ is overrated. You should consider learning another language, like java or python.'], dtype="string")
Let’s print the new series:
print(s)
Let’s count the number of times the word ‘python’ appears in each strings:
print(s.str.count('python'))
We see this returns a series of ‘dtype: int64’.
Another method we can look at is the ‘isdigit()’ method which returns a boolean series based on whether or not a string is a digit. Let’s define a new series to demonstrate the use of this method. Let’s say we have a series defined by a list of string digits, where missing string digits have the value ‘unknown’:
s2 = pd.Series(['100', 'unknown', '20', '240', 'unknown', '100'], dtype="string")
If we use the ‘isdigit()’ method, we get:
print(s2.str.isdigit())
We can also use the ‘match()’ method to check for the presence of specific strings. Let’s check for the presence of the string ‘100’:
print(s2.str.match('100'))
We can even check for the presence of ‘un’:
print(s2.str.match('un'))
All of which is in concert with what we’d expect. We can also use methods to change the casing of the string text in our series. Let’s go back to our series containing opinions about different programming languages, ‘s1':
s1 = pd.Series(['python is awesome. I love python.', 'java is just ok. I like python more', 'c++ is overrated. You should consider learning another language, like java or python.'], dtype="string")
We can use the ‘upper()’ method to capitalize the text in the strings in our series:
s_upper = s1.str.upper()print(s_upper)
We also use the ‘lower()’ method:
s_lower = s_upper.str.lower()print(s_lower)
We can also get the length of each string using ‘len()’:
print(s1.str.len())
Let’s consider a few more interesting methods. We can use the ‘strip()’ method to remove whitespace. For this, let’s define and print a new example series containing strings with unwanted whitespace:
s3 = pd.Series([' python', 'java', 'ruby ', 'fortran '])print(s3)
As you can see, there is whitespace to the left of ‘python’ and to the right of ‘ruby’ and ‘fortran’. We can remove this with the ‘strip()’ method:
print(s3.str.strip())
We can also remove whitespace on the left with ‘lstrip’:
print(s3.str.lstrip())
and on the right with ‘rstrip’:
print(s3.str.rstrip())
In the previous two examples I was working with ‘dtype=object’ but, again, try your best to remember to specify ‘dtype=strings’ if you are working with strings.
You can also use the strip methods to remove unwanted characters in your text. Often times, in real text data you have the presence of ‘\n’ which indicates a new line. Let’s modify our series and demonstrate the use of strip in this case:
s3 = pd.Series([' python\n', 'java\n', 'ruby \n', 'fortran \n'])print(s3)
An we can remove the ‘\n’ character with ‘strip()’:
print(s3.str.strip(' \n'))
In this specific example, I’d like to point out a difference in behavior between ‘dtype=object’ and ‘dtype= strings’. If we specify ‘dtype= strings’ and print the series:
s4 = pd.Series([' python\n', 'java\n', 'ruby \n', 'fortran \n'], dtype='string')print(s4)
We see that ‘\n’ has been interpreted. Nonetheless using ‘strip()’ on the newly specified series still works:
print(s4.str.strip(‘ \n’))
The last method we will look at is the ‘replace()’ method. Suppose we have a new series with poorly formatted dollar amounts:
s5 = pd.Series(['$#1200', 'dollar1,000', 'dollar10000', '$500'], dtype="string")print(s5)
We can use the ‘replace()’ method to get rid of the unwanted ‘#’ in the first element:
print(s5.str.replace('#', ''))
We can also replace the text ‘dollar’ with an actual ‘$’ sign:
s5 = s5.str.replace('dollar', '$')print(s5)
Finally, we can remove the ‘,’ from the 2nd element:
s5 = s5.str.replace(',', '')print(s5)
I will stop here but feel free to play around with the methods a bit more. You can try applying some of the Pandas methods to freely available data sets like Yelp or Amazon reviews which can be found on Kaggle or to your own work if it involves processing text data.
To summarize, we discussed some basic Pandas methods for string manipulation. We went over generating boolean series based on the presence of specific strings, checking for the presence of digits in strings, removing unwanted whitespace or characters, and replacing unwanted characters with a character of choice.
There are many more Pandas string methods I did not go over in this post. These include methods for concatenation, indexing, extracting substrings, pattern matching and much more. I will save these methods for a future article. I hope you found this post interesting and/or useful. The code in this post is available on GitHub. Thank you for reading!
|
[
{
"code": null,
"e": 485,
"s": 172,
"text": "Pandas is a popular python library that enables easy to use data structures and data analysis tools. Pandas can be used for reading in data, generating statistics, aggregating, feature engineering for machine learning and much more. The Pandas library also provides a suite of tools for string/text manipulation."
},
{
"code": null,
"e": 595,
"s": 485,
"text": "In this post, we will walk through some of the most important string manipulation methods provided by pandas."
},
{
"code": null,
"e": 614,
"s": 595,
"text": "Let’s get started!"
},
{
"code": null,
"e": 653,
"s": 614,
"text": "First, let’s import the Pandas library"
},
{
"code": null,
"e": 673,
"s": 653,
"text": "import pandas as pd"
},
{
"code": null,
"e": 736,
"s": 673,
"text": "Now, let’s define an example pandas series containing strings:"
},
{
"code": null,
"e": 812,
"s": 736,
"text": "s = pd.Series(['python is awesome', 'java is just ok', 'c++ is overrated'])"
},
{
"code": null,
"e": 837,
"s": 812,
"text": "Let’s print this series:"
},
{
"code": null,
"e": 846,
"s": 837,
"text": "print(s)"
},
{
"code": null,
"e": 1149,
"s": 846,
"text": "We notice that the series has ‘dtype: object’, which is the default type automatically inferred. In general, it is better to have a dedicated type. Since the release of Pandas 1.0, we are now able to specify dedicated types. Make sure Pandas is updated by executing the following command in a terminal:"
},
{
"code": null,
"e": 1171,
"s": 1149,
"text": "pip install -U pandas"
},
{
"code": null,
"e": 1214,
"s": 1171,
"text": "We can specify ‘dtype: string’ as follows:"
},
{
"code": null,
"e": 1307,
"s": 1214,
"text": "s1 = pd.Series(['python is awesome', 'java is just ok', 'c++ is overrated'], dtype='string')"
},
{
"code": null,
"e": 1331,
"s": 1307,
"text": "Let’s print the series:"
},
{
"code": null,
"e": 1677,
"s": 1331,
"text": "We can see that the series type is specified. It is best to specify the type, and not use the default ‘dtype: object’ because it allows accidental mixtures of types which is not advisable. For example, with ‘dtype: object’ you can have a series with integers, strings, and floats. For this reason, the contents of a ‘dtype: object’ can be vague."
},
{
"code": null,
"e": 1812,
"s": 1677,
"text": "Next, let’s look at some specific string methods. Let’s consider the ‘count()’ method. Let’s modify our series a bit for this example:"
},
{
"code": null,
"e": 2025,
"s": 1812,
"text": "s = pd.Series(['python is awesome. I love python.', 'java is just ok. I like python more', 'c++ is overrated. You should consider learning another language, like java or python.'], dtype=\"string\")"
},
{
"code": null,
"e": 2053,
"s": 2025,
"text": "Let’s print the new series:"
},
{
"code": null,
"e": 2062,
"s": 2053,
"text": "print(s)"
},
{
"code": null,
"e": 2137,
"s": 2062,
"text": "Let’s count the number of times the word ‘python’ appears in each strings:"
},
{
"code": null,
"e": 2166,
"s": 2137,
"text": "print(s.str.count('python'))"
},
{
"code": null,
"e": 2214,
"s": 2166,
"text": "We see this returns a series of ‘dtype: int64’."
},
{
"code": null,
"e": 2528,
"s": 2214,
"text": "Another method we can look at is the ‘isdigit()’ method which returns a boolean series based on whether or not a string is a digit. Let’s define a new series to demonstrate the use of this method. Let’s say we have a series defined by a list of string digits, where missing string digits have the value ‘unknown’:"
},
{
"code": null,
"e": 2610,
"s": 2528,
"text": "s2 = pd.Series(['100', 'unknown', '20', '240', 'unknown', '100'], dtype=\"string\")"
},
{
"code": null,
"e": 2652,
"s": 2610,
"text": "If we use the ‘isdigit()’ method, we get:"
},
{
"code": null,
"e": 2676,
"s": 2652,
"text": "print(s2.str.isdigit())"
},
{
"code": null,
"e": 2810,
"s": 2676,
"text": "We can also use the ‘match()’ method to check for the presence of specific strings. Let’s check for the presence of the string ‘100’:"
},
{
"code": null,
"e": 2837,
"s": 2810,
"text": "print(s2.str.match('100'))"
},
{
"code": null,
"e": 2881,
"s": 2837,
"text": "We can even check for the presence of ‘un’:"
},
{
"code": null,
"e": 2907,
"s": 2881,
"text": "print(s2.str.match('un'))"
},
{
"code": null,
"e": 3129,
"s": 2907,
"text": "All of which is in concert with what we’d expect. We can also use methods to change the casing of the string text in our series. Let’s go back to our series containing opinions about different programming languages, ‘s1':"
},
{
"code": null,
"e": 3343,
"s": 3129,
"text": "s1 = pd.Series(['python is awesome. I love python.', 'java is just ok. I like python more', 'c++ is overrated. You should consider learning another language, like java or python.'], dtype=\"string\")"
},
{
"code": null,
"e": 3428,
"s": 3343,
"text": "We can use the ‘upper()’ method to capitalize the text in the strings in our series:"
},
{
"code": null,
"e": 3467,
"s": 3428,
"text": "s_upper = s1.str.upper()print(s_upper)"
},
{
"code": null,
"e": 3501,
"s": 3467,
"text": "We also use the ‘lower()’ method:"
},
{
"code": null,
"e": 3545,
"s": 3501,
"text": "s_lower = s_upper.str.lower()print(s_lower)"
},
{
"code": null,
"e": 3602,
"s": 3545,
"text": "We can also get the length of each string using ‘len()’:"
},
{
"code": null,
"e": 3622,
"s": 3602,
"text": "print(s1.str.len())"
},
{
"code": null,
"e": 3822,
"s": 3622,
"text": "Let’s consider a few more interesting methods. We can use the ‘strip()’ method to remove whitespace. For this, let’s define and print a new example series containing strings with unwanted whitespace:"
},
{
"code": null,
"e": 3888,
"s": 3822,
"text": "s3 = pd.Series([' python', 'java', 'ruby ', 'fortran '])print(s3)"
},
{
"code": null,
"e": 4036,
"s": 3888,
"text": "As you can see, there is whitespace to the left of ‘python’ and to the right of ‘ruby’ and ‘fortran’. We can remove this with the ‘strip()’ method:"
},
{
"code": null,
"e": 4058,
"s": 4036,
"text": "print(s3.str.strip())"
},
{
"code": null,
"e": 4115,
"s": 4058,
"text": "We can also remove whitespace on the left with ‘lstrip’:"
},
{
"code": null,
"e": 4138,
"s": 4115,
"text": "print(s3.str.lstrip())"
},
{
"code": null,
"e": 4170,
"s": 4138,
"text": "and on the right with ‘rstrip’:"
},
{
"code": null,
"e": 4193,
"s": 4170,
"text": "print(s3.str.rstrip())"
},
{
"code": null,
"e": 4354,
"s": 4193,
"text": "In the previous two examples I was working with ‘dtype=object’ but, again, try your best to remember to specify ‘dtype=strings’ if you are working with strings."
},
{
"code": null,
"e": 4593,
"s": 4354,
"text": "You can also use the strip methods to remove unwanted characters in your text. Often times, in real text data you have the presence of ‘\\n’ which indicates a new line. Let’s modify our series and demonstrate the use of strip in this case:"
},
{
"code": null,
"e": 4667,
"s": 4593,
"text": "s3 = pd.Series([' python\\n', 'java\\n', 'ruby \\n', 'fortran \\n'])print(s3)"
},
{
"code": null,
"e": 4719,
"s": 4667,
"text": "An we can remove the ‘\\n’ character with ‘strip()’:"
},
{
"code": null,
"e": 4746,
"s": 4719,
"text": "print(s3.str.strip(' \\n'))"
},
{
"code": null,
"e": 4917,
"s": 4746,
"text": "In this specific example, I’d like to point out a difference in behavior between ‘dtype=object’ and ‘dtype= strings’. If we specify ‘dtype= strings’ and print the series:"
},
{
"code": null,
"e": 5007,
"s": 4917,
"text": "s4 = pd.Series([' python\\n', 'java\\n', 'ruby \\n', 'fortran \\n'], dtype='string')print(s4)"
},
{
"code": null,
"e": 5117,
"s": 5007,
"text": "We see that ‘\\n’ has been interpreted. Nonetheless using ‘strip()’ on the newly specified series still works:"
},
{
"code": null,
"e": 5144,
"s": 5117,
"text": "print(s4.str.strip(‘ \\n’))"
},
{
"code": null,
"e": 5270,
"s": 5144,
"text": "The last method we will look at is the ‘replace()’ method. Suppose we have a new series with poorly formatted dollar amounts:"
},
{
"code": null,
"e": 5360,
"s": 5270,
"text": "s5 = pd.Series(['$#1200', 'dollar1,000', 'dollar10000', '$500'], dtype=\"string\")print(s5)"
},
{
"code": null,
"e": 5447,
"s": 5360,
"text": "We can use the ‘replace()’ method to get rid of the unwanted ‘#’ in the first element:"
},
{
"code": null,
"e": 5478,
"s": 5447,
"text": "print(s5.str.replace('#', ''))"
},
{
"code": null,
"e": 5541,
"s": 5478,
"text": "We can also replace the text ‘dollar’ with an actual ‘$’ sign:"
},
{
"code": null,
"e": 5585,
"s": 5541,
"text": "s5 = s5.str.replace('dollar', '$')print(s5)"
},
{
"code": null,
"e": 5638,
"s": 5585,
"text": "Finally, we can remove the ‘,’ from the 2nd element:"
},
{
"code": null,
"e": 5676,
"s": 5638,
"text": "s5 = s5.str.replace(',', '')print(s5)"
},
{
"code": null,
"e": 5943,
"s": 5676,
"text": "I will stop here but feel free to play around with the methods a bit more. You can try applying some of the Pandas methods to freely available data sets like Yelp or Amazon reviews which can be found on Kaggle or to your own work if it involves processing text data."
},
{
"code": null,
"e": 6257,
"s": 5943,
"text": "To summarize, we discussed some basic Pandas methods for string manipulation. We went over generating boolean series based on the presence of specific strings, checking for the presence of digits in strings, removing unwanted whitespace or characters, and replacing unwanted characters with a character of choice."
}
] |
How to Map a Function Over NumPy Array? - GeeksforGeeks
|
28 Nov, 2021
In this article, we are going to see how to map a function over a NumPy array in Python.
The numpy.vectorize() function maps functions on data structures that contain a sequence of objects like NumPy arrays. The nested sequence of objects or NumPy arrays as inputs and returns a single NumPy array or a tuple of NumPy arrays.
Python3
import numpy as np arr = np.array([1, 2, 3, 4, 5]) def addTwo(i): return i+2 applyall = np.vectorize(addTwo)res = applyall(arr)print(res)
Output:
[3 4 5 6 7]
Explanation: The function is passed to the vectorized method and again the array is passed to it and the function will return the array on which the array is applied.
The lambda is an anonymous function, it takes any number of arguments but evaluates one expression.
Python3
import numpy as np arr = np.array([1, 2, 3, 4, 5]) def applyall(i): return i + 2 res = applyall(arr)print(res)
Output:
[3 4 5 6 7]
We can map a function over a NumPy array just by passing the array to the function.
Python3
import numpy as np arr = np.array([1, 2, 3, 4, 5]) def applyall(a): return a+2 res = applyall(arr)print(res)
Output:
[3 4 5 6 7]
Explanation: The array is passed to the applyall() method and it will map the function to the entire array and the resultant array is returned.
Picked
Python numpy-arrayManipulation
Python-numpy
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": "\n28 Nov, 2021"
},
{
"code": null,
"e": 23990,
"s": 23901,
"text": "In this article, we are going to see how to map a function over a NumPy array in Python."
},
{
"code": null,
"e": 24227,
"s": 23990,
"text": "The numpy.vectorize() function maps functions on data structures that contain a sequence of objects like NumPy arrays. The nested sequence of objects or NumPy arrays as inputs and returns a single NumPy array or a tuple of NumPy arrays."
},
{
"code": null,
"e": 24235,
"s": 24227,
"text": "Python3"
},
{
"code": "import numpy as np arr = np.array([1, 2, 3, 4, 5]) def addTwo(i): return i+2 applyall = np.vectorize(addTwo)res = applyall(arr)print(res)",
"e": 24381,
"s": 24235,
"text": null
},
{
"code": null,
"e": 24389,
"s": 24381,
"text": "Output:"
},
{
"code": null,
"e": 24401,
"s": 24389,
"text": "[3 4 5 6 7]"
},
{
"code": null,
"e": 24568,
"s": 24401,
"text": "Explanation: The function is passed to the vectorized method and again the array is passed to it and the function will return the array on which the array is applied."
},
{
"code": null,
"e": 24668,
"s": 24568,
"text": "The lambda is an anonymous function, it takes any number of arguments but evaluates one expression."
},
{
"code": null,
"e": 24676,
"s": 24668,
"text": "Python3"
},
{
"code": "import numpy as np arr = np.array([1, 2, 3, 4, 5]) def applyall(i): return i + 2 res = applyall(arr)print(res)",
"e": 24792,
"s": 24676,
"text": null
},
{
"code": null,
"e": 24800,
"s": 24792,
"text": "Output:"
},
{
"code": null,
"e": 24812,
"s": 24800,
"text": "[3 4 5 6 7]"
},
{
"code": null,
"e": 24896,
"s": 24812,
"text": "We can map a function over a NumPy array just by passing the array to the function."
},
{
"code": null,
"e": 24904,
"s": 24896,
"text": "Python3"
},
{
"code": "import numpy as np arr = np.array([1, 2, 3, 4, 5]) def applyall(a): return a+2 res = applyall(arr)print(res)",
"e": 25019,
"s": 24904,
"text": null
},
{
"code": null,
"e": 25027,
"s": 25019,
"text": "Output:"
},
{
"code": null,
"e": 25039,
"s": 25027,
"text": "[3 4 5 6 7]"
},
{
"code": null,
"e": 25183,
"s": 25039,
"text": "Explanation: The array is passed to the applyall() method and it will map the function to the entire array and the resultant array is returned."
},
{
"code": null,
"e": 25190,
"s": 25183,
"text": "Picked"
},
{
"code": null,
"e": 25221,
"s": 25190,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 25234,
"s": 25221,
"text": "Python-numpy"
},
{
"code": null,
"e": 25241,
"s": 25234,
"text": "Python"
},
{
"code": null,
"e": 25339,
"s": 25241,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25348,
"s": 25339,
"text": "Comments"
},
{
"code": null,
"e": 25361,
"s": 25348,
"text": "Old Comments"
},
{
"code": null,
"e": 25393,
"s": 25361,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25449,
"s": 25393,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25491,
"s": 25449,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25533,
"s": 25491,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25569,
"s": 25533,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 25591,
"s": 25569,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25630,
"s": 25591,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25657,
"s": 25630,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 25688,
"s": 25657,
"text": "Python | os.path.join() method"
}
] |
Construction of Combinational Circuits - GeeksforGeeks
|
23 Jul, 2019
A Combinational Circuit consist of logic gates whose outputs at any instant of time are determined directly from the present combination of inputs without regard to previous input. Examples of combinational circuits: Adder, Subtractor, Converter, and Encoder/Decoder.
Here we are going to learn how to construct and analyze any type of combinational circuit using four general steps. I am going to explain this trick with the help of the one combinational circuit and you can apply the same for implementing other combinational circuits.
Following are the four steps to construct and analyze any combinational circuit.
Step-1: Identify the number of inputs and outputs of the circuit.First of all, we have to think about the inputs and outputs of the circuit by considering which type of logical operation we want to perform with the circuit.For example, we have to create a circuit that can add two bits. For this, we require two inputs (one for the first bit (A) another for the second bit (B)) and two outputs one for sum (S) of two bits and another for carry (C).In total, we require 2 inputs and 2 outputs. So here our first step is completed.
In total, we require 2 inputs and 2 outputs. So here our first step is completed.
Step-2: Creating the Truth Table.In this step we have to create truth table for our circuit so for this first we will create input columns and list all the possible combinations of inputs. In our case 2 bits can have maximum 4 combinations (00 01 10 11).Now in output, we have two columns (Sum and Carry) as discussed earlier. Now we have to fill output columns in such a way that for which logical operation we are constructing circuit.In our circuit, we want addition so we will add those input bits and write the sum of those bits in (Sum) column and if carry is generated we will write 1 else write.0 in (Carry) column.
In our circuit, we want addition so we will add those input bits and write the sum of those bits in (Sum) column and if carry is generated we will write 1 else write.
0 in (Carry) column.
Step-3: Simplify the Boolean function for each output.In this step, we have to just create a simplified Boolean function according to inputs and outputs of the truth table obtained in the previous step.For Sum,Sum = A'B + AB' = A XOR B For Carry,Carry = AB = A AND B
Sum = A'B + AB' = A XOR B
For Carry,
Carry = AB = A AND B
Step-4: Constructing circuit using Boolean function obtained from third step.For sum, we have obtained (A XOR B) so we will connect A and B to the inputs of XOR gate and take its output as a sum. For carry, we have obtained (A AND B) so we will connect A and B to the inputs of AND gate and take its output as a carry.Now in this circuit, if you provide input at A and B ends. You will get the output on sum and carry ends according to truth table we have created above. So here we have completed our four steps for creating the combinational circuit.
Now in this circuit, if you provide input at A and B ends. You will get the output on sum and carry ends according to truth table we have created above. So here we have completed our four steps for creating the combinational circuit.
So, we have created a combinational circuit called Half Adder. You can apply the same steps to create any other combinational circuit.
Amanjhurani
Digital Electronics & Logic Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design 101 sequence detector (Mealy machine)
Carry Look-Ahead Adder
BCD to 7 Segment Decoder
Encoder in Digital Logic
Flip-flop types, their Conversion and Applications
Layers of OSI Model
ACID Properties in DBMS
Types of Operating Systems
Normal Forms in DBMS
Page Replacement Algorithms in Operating Systems
|
[
{
"code": null,
"e": 24702,
"s": 24674,
"text": "\n23 Jul, 2019"
},
{
"code": null,
"e": 24970,
"s": 24702,
"text": "A Combinational Circuit consist of logic gates whose outputs at any instant of time are determined directly from the present combination of inputs without regard to previous input. Examples of combinational circuits: Adder, Subtractor, Converter, and Encoder/Decoder."
},
{
"code": null,
"e": 25240,
"s": 24970,
"text": "Here we are going to learn how to construct and analyze any type of combinational circuit using four general steps. I am going to explain this trick with the help of the one combinational circuit and you can apply the same for implementing other combinational circuits."
},
{
"code": null,
"e": 25321,
"s": 25240,
"text": "Following are the four steps to construct and analyze any combinational circuit."
},
{
"code": null,
"e": 25851,
"s": 25321,
"text": "Step-1: Identify the number of inputs and outputs of the circuit.First of all, we have to think about the inputs and outputs of the circuit by considering which type of logical operation we want to perform with the circuit.For example, we have to create a circuit that can add two bits. For this, we require two inputs (one for the first bit (A) another for the second bit (B)) and two outputs one for sum (S) of two bits and another for carry (C).In total, we require 2 inputs and 2 outputs. So here our first step is completed."
},
{
"code": null,
"e": 25933,
"s": 25851,
"text": "In total, we require 2 inputs and 2 outputs. So here our first step is completed."
},
{
"code": null,
"e": 26557,
"s": 25933,
"text": "Step-2: Creating the Truth Table.In this step we have to create truth table for our circuit so for this first we will create input columns and list all the possible combinations of inputs. In our case 2 bits can have maximum 4 combinations (00 01 10 11).Now in output, we have two columns (Sum and Carry) as discussed earlier. Now we have to fill output columns in such a way that for which logical operation we are constructing circuit.In our circuit, we want addition so we will add those input bits and write the sum of those bits in (Sum) column and if carry is generated we will write 1 else write.0 in (Carry) column."
},
{
"code": null,
"e": 26724,
"s": 26557,
"text": "In our circuit, we want addition so we will add those input bits and write the sum of those bits in (Sum) column and if carry is generated we will write 1 else write."
},
{
"code": null,
"e": 26745,
"s": 26724,
"text": "0 in (Carry) column."
},
{
"code": null,
"e": 27013,
"s": 26745,
"text": "Step-3: Simplify the Boolean function for each output.In this step, we have to just create a simplified Boolean function according to inputs and outputs of the truth table obtained in the previous step.For Sum,Sum = A'B + AB' = A XOR B For Carry,Carry = AB = A AND B "
},
{
"code": null,
"e": 27040,
"s": 27013,
"text": "Sum = A'B + AB' = A XOR B "
},
{
"code": null,
"e": 27051,
"s": 27040,
"text": "For Carry,"
},
{
"code": null,
"e": 27073,
"s": 27051,
"text": "Carry = AB = A AND B "
},
{
"code": null,
"e": 27625,
"s": 27073,
"text": "Step-4: Constructing circuit using Boolean function obtained from third step.For sum, we have obtained (A XOR B) so we will connect A and B to the inputs of XOR gate and take its output as a sum. For carry, we have obtained (A AND B) so we will connect A and B to the inputs of AND gate and take its output as a carry.Now in this circuit, if you provide input at A and B ends. You will get the output on sum and carry ends according to truth table we have created above. So here we have completed our four steps for creating the combinational circuit."
},
{
"code": null,
"e": 27859,
"s": 27625,
"text": "Now in this circuit, if you provide input at A and B ends. You will get the output on sum and carry ends according to truth table we have created above. So here we have completed our four steps for creating the combinational circuit."
},
{
"code": null,
"e": 27994,
"s": 27859,
"text": "So, we have created a combinational circuit called Half Adder. You can apply the same steps to create any other combinational circuit."
},
{
"code": null,
"e": 28006,
"s": 27994,
"text": "Amanjhurani"
},
{
"code": null,
"e": 28041,
"s": 28006,
"text": "Digital Electronics & Logic Design"
},
{
"code": null,
"e": 28049,
"s": 28041,
"text": "GATE CS"
},
{
"code": null,
"e": 28147,
"s": 28049,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28156,
"s": 28147,
"text": "Comments"
},
{
"code": null,
"e": 28169,
"s": 28156,
"text": "Old Comments"
},
{
"code": null,
"e": 28214,
"s": 28169,
"text": "Design 101 sequence detector (Mealy machine)"
},
{
"code": null,
"e": 28237,
"s": 28214,
"text": "Carry Look-Ahead Adder"
},
{
"code": null,
"e": 28262,
"s": 28237,
"text": "BCD to 7 Segment Decoder"
},
{
"code": null,
"e": 28287,
"s": 28262,
"text": "Encoder in Digital Logic"
},
{
"code": null,
"e": 28338,
"s": 28287,
"text": "Flip-flop types, their Conversion and Applications"
},
{
"code": null,
"e": 28358,
"s": 28338,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 28382,
"s": 28358,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 28409,
"s": 28382,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 28430,
"s": 28409,
"text": "Normal Forms in DBMS"
}
] |
Return Pointer from Functions in C++
|
As we have seen in last chapter how C++ allows to return an array from a function, similar way C++ allows you to return a pointer from a function. To do so, you would have to declare a function returning a pointer as in the following example −
int * myFunction() {
.
.
.
}
Second point to remember is that, it is not good idea to return the address of a local variable to outside of the function, so you would have to define the local variable as static variable.
Now, consider the following function, which will generate 10 random numbers and return them using an array name which represents a pointer i.e., address of first array element.
#include <iostream>
#include <ctime>
using namespace std;
// function to generate and retrun random numbers.
int * getRandom( ) {
static int r[10];
// set the seed
srand( (unsigned)time( NULL ) );
for (int i = 0; i < 10; ++i) {
r[i] = rand();
cout << r[i] << endl;
}
return r;
}
// main function to call above defined function.
int main () {
// a pointer to an int.
int *p;
p = getRandom();
for ( int i = 0; i < 10; i++ ) {
cout << "*(p + " << i << ") : ";
cout << *(p + i) << endl;
}
return 0;
}
When the above code is compiled together and executed, it produces result something as follows −
624723190
1468735695
807113585
976495677
613357504
1377296355
1530315259
1778906708
1820354158
667126415
*(p + 0) : 624723190
*(p + 1) : 1468735695
*(p + 2) : 807113585
*(p + 3) : 976495677
*(p + 4) : 613357504
*(p + 5) : 1377296355
*(p + 6) : 1530315259
*(p + 7) : 1778906708
*(p + 8) : 1820354158
*(p + 9) : 667126415
154 Lectures
11.5 hours
Arnab Chakraborty
14 Lectures
57 mins
Kaushik Roy Chowdhury
30 Lectures
12.5 hours
Frahaan Hussain
54 Lectures
3.5 hours
Frahaan Hussain
77 Lectures
5.5 hours
Frahaan Hussain
12 Lectures
3.5 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2562,
"s": 2318,
"text": "As we have seen in last chapter how C++ allows to return an array from a function, similar way C++ allows you to return a pointer from a function. To do so, you would have to declare a function returning a pointer as in the following example −"
},
{
"code": null,
"e": 2601,
"s": 2562,
"text": "int * myFunction() {\n .\n .\n .\n}\n"
},
{
"code": null,
"e": 2792,
"s": 2601,
"text": "Second point to remember is that, it is not good idea to return the address of a local variable to outside of the function, so you would have to define the local variable as static variable."
},
{
"code": null,
"e": 2969,
"s": 2792,
"text": "Now, consider the following function, which will generate 10 random numbers and return them using an array name which represents a pointer i.e., address of first array element."
},
{
"code": null,
"e": 3545,
"s": 2969,
"text": "#include <iostream>\n#include <ctime>\n \nusing namespace std;\n \n// function to generate and retrun random numbers.\nint * getRandom( ) {\n static int r[10];\n \n // set the seed\n srand( (unsigned)time( NULL ) );\n \n for (int i = 0; i < 10; ++i) {\n r[i] = rand();\n cout << r[i] << endl;\n }\n \n return r;\n}\n \n// main function to call above defined function.\nint main () {\n // a pointer to an int.\n int *p;\n \n p = getRandom();\n for ( int i = 0; i < 10; i++ ) {\n cout << \"*(p + \" << i << \") : \";\n cout << *(p + i) << endl;\n }\n \n return 0;\n}"
},
{
"code": null,
"e": 3642,
"s": 3545,
"text": "When the above code is compiled together and executed, it produces result something as follows −"
},
{
"code": null,
"e": 3963,
"s": 3642,
"text": "624723190\n1468735695\n807113585\n976495677\n613357504\n1377296355\n1530315259\n1778906708\n1820354158\n667126415\n*(p + 0) : 624723190\n*(p + 1) : 1468735695\n*(p + 2) : 807113585\n*(p + 3) : 976495677\n*(p + 4) : 613357504\n*(p + 5) : 1377296355\n*(p + 6) : 1530315259\n*(p + 7) : 1778906708\n*(p + 8) : 1820354158\n*(p + 9) : 667126415\n"
},
{
"code": null,
"e": 4000,
"s": 3963,
"text": "\n 154 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 4019,
"s": 4000,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4051,
"s": 4019,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 4074,
"s": 4051,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 4110,
"s": 4074,
"text": "\n 30 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 4127,
"s": 4110,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4162,
"s": 4127,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4179,
"s": 4162,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4214,
"s": 4179,
"text": "\n 77 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4231,
"s": 4214,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4266,
"s": 4231,
"text": "\n 12 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4283,
"s": 4266,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4290,
"s": 4283,
"text": " Print"
},
{
"code": null,
"e": 4301,
"s": 4290,
"text": " Add Notes"
}
] |
R - Array - GeeksforGeeks
|
10 May, 2020
Arrays are essential data storage structures defined by a fixed number of dimensions. Arrays are used for the allocation of space at contiguous memory locations. Uni-dimensional arrays are called vectors with the length being their only dimension. Two-dimensional arrays are called matrices, consisting of fixed numbers of rows and columns. Arrays consist of all elements of the same data type. Vectors are supplied as input to the function and then create an array based on the number of dimensions.
An array in R can be created with the use of array() function. List of elements is passed to the array() functions along with the dimensions as required.
Syntax:
array(data, dim = (nrow, ncol, nmat), dimnames=names)
where,
nrow : Number of rowsncol : Number of columnsnmat : Number of matrices of dimensions nrow * ncoldimnames : Default value = NULL.
Otherwise, a list has to be specified which has a name for each component of the dimension. Each component is either a null or a vector of length equal to the dim value of that corresponding dimension.
A vector is a uni-dimensional array, which is specified by a single dimension, length. A Vector can be created using ‘c()‘ function. A list of values is passed to the c() function to create a vector.
Example:
vec1 <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)print (vec1) # cat is used to concatenate# strings and print it.cat ("Length of vector : ", length(vec1))
Output:
[1] 1 2 3 4 5 6 7 8 9
Length of vector : 9
A two-dimensional matrix is an array specified by a fixed number of rows and columns, each containing the same data type. A matrix is created by using array() function to which the values and the dimensions are passed.
Example:
# arranges data from 2 to 13 # in two matrices of dimensions 2x3arr = array(2:13, dim = c(2, 3, 2))print(arr)
Output:
, , 1
[,1] [,2] [,3]
[1,] 2 4 6
[2,] 3 5 7
, , 2
[,1] [,2] [,3]
[1,] 8 10 12
[2,] 9 11 13
Vectors of different lengths can also be fed as input into the array() function. However, the total number of elements in all the vectors combined should be equal to the number of elements in the matrices. The elements are arranged in the order in which they are specified in the function.Example:
vec1 <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)vec2 <- c(10, 11, 12) # elements are combined into a single vector, # vec1 elements followed by vec2 elements.arr = array(c(vec1, vec2), dim = c(2, 3, 2))print (arr)
Output:
,, 1
[, 1] [, 2] [, 3]
[1, ] 1 3 5
[2, ] 2 4 6
,, 2
[, 1] [, 2] [, 3]
[1, ] 7 9 11
[2, ] 8 10 12
The row names, column names and matrices names are specified as a vector of the number of rows, number of columns and number of matrices respectively. By default, the rows, columns and matrices are named by their index values.
row_names <- c("row1", "row2")col_names <- c("col1", "col2", "col3")mat_names <- c("Mat1", "Mat2") # the naming of the various elements# is specified in a list and # fed to the functionarr = array(2:14, dim = c(2, 3, 2), dimnames = list(row_names, col_names, mat_names))print (arr)
Output:
,, Mat1
col1 col2 col3
row1 2 4 6
row2 3 5 7
,, Mat2
col1 col2 col3
row1 8 10 12
row2 9 11 13
The arrays can be accessed by using indices for different dimensions separated by commas. Different components can be specified by any combination of elements’ names or positions.
The elements can be accessed by using indexes of the corresponding elements.
vec <- c(1:10) # accessing entire vectorcat ("Vector is : ", vec) # accessing elementscat ("Third element of vector is : ", vec[3])
<
Output:
Vector is : 1 2 3 4 5 6 7 8 9 10
Third element of vector is : 3
vec1 <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)vec2 <- c(10, 11, 12)row_names <- c("row1", "row2")col_names <- c("col1", "col2", "col3")mat_names <- c("Mat1", "Mat2")arr = array(c(vec1, vec2), dim = c(2, 3, 2), dimnames = list(row_names, col_names, mat_names)) # accessing matrix 1 by index valueprint ("Matrix 1")print (arr[,,1]) # accessing matrix 2 by its nameprint ("Matrix 2")print(arr[,,"Mat2"])
Output:
[1] "Matrix 1"
col1 col2 col3
row1 1 3 5
row2 2 4 6
[1] "Matrix 2"
col1 col2 col3
row1 7 9 11
row2 8 10 12
Rows and columns can also be accessed by both names as well as indices.
vec1 <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)vec2 <- c(10, 11, 12)row_names <- c("row1", "row2")col_names <- c("col1", "col2", "col3")mat_names <- c("Mat1", "Mat2")arr = array(c(vec1, vec2), dim = c(2, 3, 2), dimnames = list(row_names, col_names, mat_names)) # accessing matrix 1 by index valueprint ("1st column of matrix 1")print (arr[, 1, 1]) # accessing matrix 2 by its nameprint ("2nd row of matrix 2")print(arr["row2",,"Mat2"])
Output:
[1] "1st column of matrix 1"
row1 row2
1 2
[1] "2nd row of matrix 2"
col1 col2 col3
8 10 12
Elements can be accessed by using both the row and column numbers or names.
vec1 <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)vec2 <- c(10, 11, 12)row_names <- c("row1", "row2")col_names <- c("col1", "col2", "col3")mat_names <- c("Mat1", "Mat2")arr = array(c(vec1, vec2), dim = c(2, 3, 2), dimnames = list(row_names, col_names, mat_names)) # accessing matrix 1 by index valueprint ("2nd row 3rd column matrix 1 element")print (arr[2, "col3", 1]) # accessing matrix 2 by its nameprint ("2nd row 1st column element of matrix 2")print(arr["row2", "col1", "Mat2"])
Output:
[1] "2nd row 3rd column matrix 1 element"
[1] 6
[1] "2nd row 1st column element of matrix 2"
[1] 8
A smaller subset of the array elements can be accessed by defining a range of row or column limits.
row_names <- c("row1", "row2")col_names <- c("col1", "col2", "col3", "col4")mat_names <- c("Mat1", "Mat2")arr = array(1:15, dim = c(2, 4, 2), dimnames = list(row_names, col_names, mat_names)) # print elements of both the rows and columns 2 and 3 of matrix 1print (arr[, c(2, 3), 1])
Output:
col2 col3
row1 3 5
row2 4 6
Elements can be appended at the different positions in the array. The sequence of elements is retained in order of their addition to the array. The time complexity required to add new elements is O(n) where n is the length of the array. The length of the array increases by the number of element additions. There are various in-built functions available in R to add new values:
c(vector, values): c() function allows us to append values to the end of the array. Multiple values can also be added together.
append(vector, values): This method allows the values to be appended at any position in the vector. By default, this function adds the element at end.append(vector, values, after=length(vector)) adds new values after specified length of the array specified in the last argument of the function.
append(vector, values, after=length(vector)) adds new values after specified length of the array specified in the last argument of the function.
Using the length function of the array:Elements can be added at length+x indices where x>0.# creating a uni-dimensional arrayx <- c(1, 2, 3, 4, 5) # addition of element using c() functionx <- c(x, 6)print ("Array after 1st modification ")print (x) # addition of element using append functionx <- append(x, 7)print ("Array after 2nd modification ")print (x) # adding elements after computing the lengthlen <- length(x)x[len + 1] <- 8print ("Array after 3rd modification ")print (x) # adding on length + 3 indexx[len + 3]<-9print ("Array after 4th modification ")print (x) # append a vector of values to the array after length + 3 of arrayprint ("Array after 5th modification")x <- append(x, c(10, 11, 12), after = length(x)+3)print (x) # adds new elements after 3rd indexprint ("Array after 6th modification")x <- append(x, c(-1, -1), after = 3)print (x)Output:[1] "Array after 1st modification "
[1] 1 2 3 4 5 6
[1] "Array after 2nd modification "
[1] 1 2 3 4 5 6 7
[1] "Array after 3rd modification "
[1] 1 2 3 4 5 6 7 8
[1] "Array after 4th modification "
[1] 1 2 3 4 5 6 7 8 NA 9
[1] "Array after 5th modification"
[1] 1 2 3 4 5 6 7 8 NA 9 10 11 12
[1] "Array after 6th modification"
[1] 1 2 3 -1 -1 4 5 6 7 8 NA 9 10 11 12The original length of the array was 7, and after third modification elements are present till the 8th index value. Now, at the fourth modification, when we add element 9 at the tenth index value, the R’s inbuilt function automatically adds NA at the missing value positions.At 5th modification, the array of elements [10, 11, 12] are added beginning from the 11th index.At 6th modification, array [-1, -1] is appended after the third position in the array.
# creating a uni-dimensional arrayx <- c(1, 2, 3, 4, 5) # addition of element using c() functionx <- c(x, 6)print ("Array after 1st modification ")print (x) # addition of element using append functionx <- append(x, 7)print ("Array after 2nd modification ")print (x) # adding elements after computing the lengthlen <- length(x)x[len + 1] <- 8print ("Array after 3rd modification ")print (x) # adding on length + 3 indexx[len + 3]<-9print ("Array after 4th modification ")print (x) # append a vector of values to the array after length + 3 of arrayprint ("Array after 5th modification")x <- append(x, c(10, 11, 12), after = length(x)+3)print (x) # adds new elements after 3rd indexprint ("Array after 6th modification")x <- append(x, c(-1, -1), after = 3)print (x)
Output:
[1] "Array after 1st modification "
[1] 1 2 3 4 5 6
[1] "Array after 2nd modification "
[1] 1 2 3 4 5 6 7
[1] "Array after 3rd modification "
[1] 1 2 3 4 5 6 7 8
[1] "Array after 4th modification "
[1] 1 2 3 4 5 6 7 8 NA 9
[1] "Array after 5th modification"
[1] 1 2 3 4 5 6 7 8 NA 9 10 11 12
[1] "Array after 6th modification"
[1] 1 2 3 -1 -1 4 5 6 7 8 NA 9 10 11 12
The original length of the array was 7, and after third modification elements are present till the 8th index value. Now, at the fourth modification, when we add element 9 at the tenth index value, the R’s inbuilt function automatically adds NA at the missing value positions.At 5th modification, the array of elements [10, 11, 12] are added beginning from the 11th index.At 6th modification, array [-1, -1] is appended after the third position in the array.
Elements can be removed from arrays in R, either one at a time or multiple together. These elements are specified as indexes to the array, wherein the array values satisfying the conditions are retained and rest removed. The comparison for removal is based on array values. Multiple conditions can also be combined together to remove a range of elements. Another way to remove elements is by using %in% operator wherein the set of element values belonging to the TRUE values of the operator are displayed as result and the rest are removed.
# creating an array of length 9m <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)print ("Original Array")print (m) # remove a single value element:3 from arraym <- m[m != 3]print ("After 1st modification")print (m) # removing elements based on condition# where either element should be # greater than 2 and less than equal to 8m <- m[m>2 & m<= 8]print ("After 2nd modification")print (m) # remove sequence of elements using another arrayremove <- c(4, 6, 8) # check which element satisfies the remove propertyprint (m % in % remove)print ("After 3rd modification")print (m [! m % in % remove])
Output:
[1] "Original Array"
[1] 1 2 3 4 5 6 7 8 9
[1] "After 1st modification"
[1] 1 2 4 5 6 7 8 9
[1] "After 2nd modification"
[1] 4 5 6 7 8
[1] TRUE FALSE TRUE FALSE TRUE
[1] "After 3rd modification"
[1] 5 7
At 1st modification, all the element values that are not equal to 3 are retained. At 2nd modification, the range of elements that are between 2 and 8 are retained, rest are removed. At 3rd modification, the elements satisfying the FALSE value are printed, since the condition involves the NOT operator.
The elements of the array can be updated with new values by assignment of the desired index of the array with the modified value. The changes are retained in the original array. If the index value to be updated is within the length of the array, then the value is changed, otherwise, the new element is added at the specified index. Multiple elements can also be updated at once, either with the same element value or multiple values in case the new values are specified as a vector.
# creating an array of length 9m <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)print ("Original Array")print (m) # updating single elementm[1] <- 0print ("After 1st modification")print (m) # updating sequence of elementsm[7:9] <- -1print ("After 2nd modification")print (m) # updating two indices with two different valuesm[c(2, 5)] <- c(-1, -2)print ("After 3rd modification")print (m) # this add new element to the arraym[10] <- 10print ("After 4th modification")print (m)
Output:
[1] "Original Array"
[1] 1 2 3 4 5 6 7 8 9
[1] "After 1st modification"
[1] 0 2 3 4 5 6 7 8 9
[1] "After 2nd modification"
[1] 0 2 3 4 5 6 -1 -1 -1
[1] "After 3rd modification"
[1] 0 -1 3 4 -2 6 -1 -1 -1
[1] "After 4th modification"
[1] 0 -1 3 4 -2 6 -1 -1 -1 10
At 2nd modification, the elements at indexes 7 to 9 are updated with -1 each. At 3rd modification, the second element is replaced by -1 and fifth element by -2 respectively. At 4th modification, a new element is added since 10th index is greater than the length of the array.
Picked
R-Arrays
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change column name of a given DataFrame in R
How to Replace specific values in column in R DataFrame ?
Adding elements in a vector in R programming - append() method
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
Logistic Regression in R Programming
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to change Row Names of DataFrame in R ?
K-Means Clustering in R Programming
|
[
{
"code": null,
"e": 28964,
"s": 28936,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 29465,
"s": 28964,
"text": "Arrays are essential data storage structures defined by a fixed number of dimensions. Arrays are used for the allocation of space at contiguous memory locations. Uni-dimensional arrays are called vectors with the length being their only dimension. Two-dimensional arrays are called matrices, consisting of fixed numbers of rows and columns. Arrays consist of all elements of the same data type. Vectors are supplied as input to the function and then create an array based on the number of dimensions."
},
{
"code": null,
"e": 29619,
"s": 29465,
"text": "An array in R can be created with the use of array() function. List of elements is passed to the array() functions along with the dimensions as required."
},
{
"code": null,
"e": 29627,
"s": 29619,
"text": "Syntax:"
},
{
"code": null,
"e": 29681,
"s": 29627,
"text": "array(data, dim = (nrow, ncol, nmat), dimnames=names)"
},
{
"code": null,
"e": 29688,
"s": 29681,
"text": "where,"
},
{
"code": null,
"e": 29817,
"s": 29688,
"text": "nrow : Number of rowsncol : Number of columnsnmat : Number of matrices of dimensions nrow * ncoldimnames : Default value = NULL."
},
{
"code": null,
"e": 30019,
"s": 29817,
"text": "Otherwise, a list has to be specified which has a name for each component of the dimension. Each component is either a null or a vector of length equal to the dim value of that corresponding dimension."
},
{
"code": null,
"e": 30219,
"s": 30019,
"text": "A vector is a uni-dimensional array, which is specified by a single dimension, length. A Vector can be created using ‘c()‘ function. A list of values is passed to the c() function to create a vector."
},
{
"code": null,
"e": 30228,
"s": 30219,
"text": "Example:"
},
{
"code": "vec1 <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)print (vec1) # cat is used to concatenate# strings and print it.cat (\"Length of vector : \", length(vec1))",
"e": 30371,
"s": 30228,
"text": null
},
{
"code": null,
"e": 30379,
"s": 30371,
"text": "Output:"
},
{
"code": null,
"e": 30423,
"s": 30379,
"text": "[1] 1 2 3 4 5 6 7 8 9\nLength of vector : 9"
},
{
"code": null,
"e": 30642,
"s": 30423,
"text": "A two-dimensional matrix is an array specified by a fixed number of rows and columns, each containing the same data type. A matrix is created by using array() function to which the values and the dimensions are passed."
},
{
"code": null,
"e": 30651,
"s": 30642,
"text": "Example:"
},
{
"code": "# arranges data from 2 to 13 # in two matrices of dimensions 2x3arr = array(2:13, dim = c(2, 3, 2))print(arr)",
"e": 30761,
"s": 30651,
"text": null
},
{
"code": null,
"e": 30769,
"s": 30761,
"text": "Output:"
},
{
"code": null,
"e": 30904,
"s": 30769,
"text": ", , 1\n\n [,1] [,2] [,3]\n[1,] 2 4 6\n[2,] 3 5 7\n\n, , 2\n\n [,1] [,2] [,3]\n[1,] 8 10 12\n[2,] 9 11 13"
},
{
"code": null,
"e": 31202,
"s": 30904,
"text": "Vectors of different lengths can also be fed as input into the array() function. However, the total number of elements in all the vectors combined should be equal to the number of elements in the matrices. The elements are arranged in the order in which they are specified in the function.Example:"
},
{
"code": "vec1 <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)vec2 <- c(10, 11, 12) # elements are combined into a single vector, # vec1 elements followed by vec2 elements.arr = array(c(vec1, vec2), dim = c(2, 3, 2))print (arr)",
"e": 31405,
"s": 31202,
"text": null
},
{
"code": null,
"e": 31413,
"s": 31405,
"text": "Output:"
},
{
"code": null,
"e": 31553,
"s": 31413,
"text": ",, 1\n [, 1] [, 2] [, 3]\n[1, ] 1 3 5\n[2, ] 2 4 6\n,, 2\n [, 1] [, 2] [, 3]\n[1, ] 7 9 11\n[2, ] 8 10 12"
},
{
"code": null,
"e": 31780,
"s": 31553,
"text": "The row names, column names and matrices names are specified as a vector of the number of rows, number of columns and number of matrices respectively. By default, the rows, columns and matrices are named by their index values."
},
{
"code": "row_names <- c(\"row1\", \"row2\")col_names <- c(\"col1\", \"col2\", \"col3\")mat_names <- c(\"Mat1\", \"Mat2\") # the naming of the various elements# is specified in a list and # fed to the functionarr = array(2:14, dim = c(2, 3, 2), dimnames = list(row_names, col_names, mat_names))print (arr)",
"e": 32103,
"s": 31780,
"text": null
},
{
"code": null,
"e": 32111,
"s": 32103,
"text": "Output:"
},
{
"code": null,
"e": 32247,
"s": 32111,
"text": ",, Mat1\n col1 col2 col3\nrow1 2 4 6\nrow2 3 5 7\n,, Mat2\n col1 col2 col3\nrow1 8 10 12\nrow2 9 11 13"
},
{
"code": null,
"e": 32427,
"s": 32247,
"text": "The arrays can be accessed by using indices for different dimensions separated by commas. Different components can be specified by any combination of elements’ names or positions."
},
{
"code": null,
"e": 32504,
"s": 32427,
"text": "The elements can be accessed by using indexes of the corresponding elements."
},
{
"code": "vec <- c(1:10) # accessing entire vectorcat (\"Vector is : \", vec) # accessing elementscat (\"Third element of vector is : \", vec[3])",
"e": 32638,
"s": 32504,
"text": null
},
{
"code": null,
"e": 32648,
"s": 32638,
"text": "<\nOutput:"
},
{
"code": null,
"e": 32713,
"s": 32648,
"text": "Vector is : 1 2 3 4 5 6 7 8 9 10\nThird element of vector is : 3"
},
{
"code": "vec1 <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)vec2 <- c(10, 11, 12)row_names <- c(\"row1\", \"row2\")col_names <- c(\"col1\", \"col2\", \"col3\")mat_names <- c(\"Mat1\", \"Mat2\")arr = array(c(vec1, vec2), dim = c(2, 3, 2), dimnames = list(row_names, col_names, mat_names)) # accessing matrix 1 by index valueprint (\"Matrix 1\")print (arr[,,1]) # accessing matrix 2 by its nameprint (\"Matrix 2\")print(arr[,,\"Mat2\"])",
"e": 33150,
"s": 32713,
"text": null
},
{
"code": null,
"e": 33158,
"s": 33150,
"text": "Output:"
},
{
"code": null,
"e": 33308,
"s": 33158,
"text": "[1] \"Matrix 1\"\n col1 col2 col3\nrow1 1 3 5\nrow2 2 4 6\n[1] \"Matrix 2\"\n col1 col2 col3\nrow1 7 9 11\nrow2 8 10 12"
},
{
"code": null,
"e": 33380,
"s": 33308,
"text": "Rows and columns can also be accessed by both names as well as indices."
},
{
"code": "vec1 <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)vec2 <- c(10, 11, 12)row_names <- c(\"row1\", \"row2\")col_names <- c(\"col1\", \"col2\", \"col3\")mat_names <- c(\"Mat1\", \"Mat2\")arr = array(c(vec1, vec2), dim = c(2, 3, 2), dimnames = list(row_names, col_names, mat_names)) # accessing matrix 1 by index valueprint (\"1st column of matrix 1\")print (arr[, 1, 1]) # accessing matrix 2 by its nameprint (\"2nd row of matrix 2\")print(arr[\"row2\",,\"Mat2\"])",
"e": 33846,
"s": 33380,
"text": null
},
{
"code": null,
"e": 33854,
"s": 33846,
"text": "Output:"
},
{
"code": null,
"e": 33963,
"s": 33854,
"text": "[1] \"1st column of matrix 1\"\nrow1 row2 \n 1 2 \n[1] \"2nd row of matrix 2\"\ncol1 col2 col3 \n 8 10 12 "
},
{
"code": null,
"e": 34039,
"s": 33963,
"text": "Elements can be accessed by using both the row and column numbers or names."
},
{
"code": "vec1 <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)vec2 <- c(10, 11, 12)row_names <- c(\"row1\", \"row2\")col_names <- c(\"col1\", \"col2\", \"col3\")mat_names <- c(\"Mat1\", \"Mat2\")arr = array(c(vec1, vec2), dim = c(2, 3, 2), dimnames = list(row_names, col_names, mat_names)) # accessing matrix 1 by index valueprint (\"2nd row 3rd column matrix 1 element\")print (arr[2, \"col3\", 1]) # accessing matrix 2 by its nameprint (\"2nd row 1st column element of matrix 2\")print(arr[\"row2\", \"col1\", \"Mat2\"])",
"e": 34518,
"s": 34039,
"text": null
},
{
"code": null,
"e": 34526,
"s": 34518,
"text": "Output:"
},
{
"code": null,
"e": 34625,
"s": 34526,
"text": "[1] \"2nd row 3rd column matrix 1 element\"\n[1] 6\n[1] \"2nd row 1st column element of matrix 2\"\n[1] 8"
},
{
"code": null,
"e": 34725,
"s": 34625,
"text": "A smaller subset of the array elements can be accessed by defining a range of row or column limits."
},
{
"code": "row_names <- c(\"row1\", \"row2\")col_names <- c(\"col1\", \"col2\", \"col3\", \"col4\")mat_names <- c(\"Mat1\", \"Mat2\")arr = array(1:15, dim = c(2, 4, 2), dimnames = list(row_names, col_names, mat_names)) # print elements of both the rows and columns 2 and 3 of matrix 1print (arr[, c(2, 3), 1])",
"e": 35015,
"s": 34725,
"text": null
},
{
"code": null,
"e": 35023,
"s": 35015,
"text": "Output:"
},
{
"code": null,
"e": 35069,
"s": 35023,
"text": " col2 col3\nrow1 3 5\nrow2 4 6\n"
},
{
"code": null,
"e": 35447,
"s": 35069,
"text": "Elements can be appended at the different positions in the array. The sequence of elements is retained in order of their addition to the array. The time complexity required to add new elements is O(n) where n is the length of the array. The length of the array increases by the number of element additions. There are various in-built functions available in R to add new values:"
},
{
"code": null,
"e": 35575,
"s": 35447,
"text": "c(vector, values): c() function allows us to append values to the end of the array. Multiple values can also be added together."
},
{
"code": null,
"e": 35870,
"s": 35575,
"text": "append(vector, values): This method allows the values to be appended at any position in the vector. By default, this function adds the element at end.append(vector, values, after=length(vector)) adds new values after specified length of the array specified in the last argument of the function."
},
{
"code": null,
"e": 36015,
"s": 35870,
"text": "append(vector, values, after=length(vector)) adds new values after specified length of the array specified in the last argument of the function."
},
{
"code": null,
"e": 37733,
"s": 36015,
"text": "Using the length function of the array:Elements can be added at length+x indices where x>0.# creating a uni-dimensional arrayx <- c(1, 2, 3, 4, 5) # addition of element using c() functionx <- c(x, 6)print (\"Array after 1st modification \")print (x) # addition of element using append functionx <- append(x, 7)print (\"Array after 2nd modification \")print (x) # adding elements after computing the lengthlen <- length(x)x[len + 1] <- 8print (\"Array after 3rd modification \")print (x) # adding on length + 3 indexx[len + 3]<-9print (\"Array after 4th modification \")print (x) # append a vector of values to the array after length + 3 of arrayprint (\"Array after 5th modification\")x <- append(x, c(10, 11, 12), after = length(x)+3)print (x) # adds new elements after 3rd indexprint (\"Array after 6th modification\")x <- append(x, c(-1, -1), after = 3)print (x)Output:[1] \"Array after 1st modification \"\n[1] 1 2 3 4 5 6\n[1] \"Array after 2nd modification \"\n[1] 1 2 3 4 5 6 7\n[1] \"Array after 3rd modification \"\n[1] 1 2 3 4 5 6 7 8\n[1] \"Array after 4th modification \"\n[1] 1 2 3 4 5 6 7 8 NA 9\n[1] \"Array after 5th modification\"\n[1] 1 2 3 4 5 6 7 8 NA 9 10 11 12\n[1] \"Array after 6th modification\"\n[1] 1 2 3 -1 -1 4 5 6 7 8 NA 9 10 11 12The original length of the array was 7, and after third modification elements are present till the 8th index value. Now, at the fourth modification, when we add element 9 at the tenth index value, the R’s inbuilt function automatically adds NA at the missing value positions.At 5th modification, the array of elements [10, 11, 12] are added beginning from the 11th index.At 6th modification, array [-1, -1] is appended after the third position in the array."
},
{
"code": "# creating a uni-dimensional arrayx <- c(1, 2, 3, 4, 5) # addition of element using c() functionx <- c(x, 6)print (\"Array after 1st modification \")print (x) # addition of element using append functionx <- append(x, 7)print (\"Array after 2nd modification \")print (x) # adding elements after computing the lengthlen <- length(x)x[len + 1] <- 8print (\"Array after 3rd modification \")print (x) # adding on length + 3 indexx[len + 3]<-9print (\"Array after 4th modification \")print (x) # append a vector of values to the array after length + 3 of arrayprint (\"Array after 5th modification\")x <- append(x, c(10, 11, 12), after = length(x)+3)print (x) # adds new elements after 3rd indexprint (\"Array after 6th modification\")x <- append(x, c(-1, -1), after = 3)print (x)",
"e": 38503,
"s": 37733,
"text": null
},
{
"code": null,
"e": 38511,
"s": 38503,
"text": "Output:"
},
{
"code": null,
"e": 38905,
"s": 38511,
"text": "[1] \"Array after 1st modification \"\n[1] 1 2 3 4 5 6\n[1] \"Array after 2nd modification \"\n[1] 1 2 3 4 5 6 7\n[1] \"Array after 3rd modification \"\n[1] 1 2 3 4 5 6 7 8\n[1] \"Array after 4th modification \"\n[1] 1 2 3 4 5 6 7 8 NA 9\n[1] \"Array after 5th modification\"\n[1] 1 2 3 4 5 6 7 8 NA 9 10 11 12\n[1] \"Array after 6th modification\"\n[1] 1 2 3 -1 -1 4 5 6 7 8 NA 9 10 11 12"
},
{
"code": null,
"e": 39363,
"s": 38905,
"text": "The original length of the array was 7, and after third modification elements are present till the 8th index value. Now, at the fourth modification, when we add element 9 at the tenth index value, the R’s inbuilt function automatically adds NA at the missing value positions.At 5th modification, the array of elements [10, 11, 12] are added beginning from the 11th index.At 6th modification, array [-1, -1] is appended after the third position in the array."
},
{
"code": null,
"e": 39904,
"s": 39363,
"text": "Elements can be removed from arrays in R, either one at a time or multiple together. These elements are specified as indexes to the array, wherein the array values satisfying the conditions are retained and rest removed. The comparison for removal is based on array values. Multiple conditions can also be combined together to remove a range of elements. Another way to remove elements is by using %in% operator wherein the set of element values belonging to the TRUE values of the operator are displayed as result and the rest are removed."
},
{
"code": "# creating an array of length 9m <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)print (\"Original Array\")print (m) # remove a single value element:3 from arraym <- m[m != 3]print (\"After 1st modification\")print (m) # removing elements based on condition# where either element should be # greater than 2 and less than equal to 8m <- m[m>2 & m<= 8]print (\"After 2nd modification\")print (m) # remove sequence of elements using another arrayremove <- c(4, 6, 8) # check which element satisfies the remove propertyprint (m % in % remove)print (\"After 3rd modification\")print (m [! m % in % remove])",
"e": 40493,
"s": 39904,
"text": null
},
{
"code": null,
"e": 40501,
"s": 40493,
"text": "Output:"
},
{
"code": null,
"e": 40707,
"s": 40501,
"text": "[1] \"Original Array\"\n[1] 1 2 3 4 5 6 7 8 9\n[1] \"After 1st modification\"\n[1] 1 2 4 5 6 7 8 9\n[1] \"After 2nd modification\"\n[1] 4 5 6 7 8\n[1] TRUE FALSE TRUE FALSE TRUE\n[1] \"After 3rd modification\"\n[1] 5 7"
},
{
"code": null,
"e": 41010,
"s": 40707,
"text": "At 1st modification, all the element values that are not equal to 3 are retained. At 2nd modification, the range of elements that are between 2 and 8 are retained, rest are removed. At 3rd modification, the elements satisfying the FALSE value are printed, since the condition involves the NOT operator."
},
{
"code": null,
"e": 41494,
"s": 41010,
"text": "The elements of the array can be updated with new values by assignment of the desired index of the array with the modified value. The changes are retained in the original array. If the index value to be updated is within the length of the array, then the value is changed, otherwise, the new element is added at the specified index. Multiple elements can also be updated at once, either with the same element value or multiple values in case the new values are specified as a vector."
},
{
"code": "# creating an array of length 9m <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)print (\"Original Array\")print (m) # updating single elementm[1] <- 0print (\"After 1st modification\")print (m) # updating sequence of elementsm[7:9] <- -1print (\"After 2nd modification\")print (m) # updating two indices with two different valuesm[c(2, 5)] <- c(-1, -2)print (\"After 3rd modification\")print (m) # this add new element to the arraym[10] <- 10print (\"After 4th modification\")print (m)",
"e": 41962,
"s": 41494,
"text": null
},
{
"code": null,
"e": 41970,
"s": 41962,
"text": "Output:"
},
{
"code": null,
"e": 42248,
"s": 41970,
"text": "[1] \"Original Array\"\n[1] 1 2 3 4 5 6 7 8 9\n[1] \"After 1st modification\"\n[1] 0 2 3 4 5 6 7 8 9\n[1] \"After 2nd modification\"\n[1] 0 2 3 4 5 6 -1 -1 -1\n[1] \"After 3rd modification\"\n[1] 0 -1 3 4 -2 6 -1 -1 -1\n[1] \"After 4th modification\"\n [1] 0 -1 3 4 -2 6 -1 -1 -1 10"
},
{
"code": null,
"e": 42524,
"s": 42248,
"text": "At 2nd modification, the elements at indexes 7 to 9 are updated with -1 each. At 3rd modification, the second element is replaced by -1 and fifth element by -2 respectively. At 4th modification, a new element is added since 10th index is greater than the length of the array."
},
{
"code": null,
"e": 42531,
"s": 42524,
"text": "Picked"
},
{
"code": null,
"e": 42540,
"s": 42531,
"text": "R-Arrays"
},
{
"code": null,
"e": 42551,
"s": 42540,
"text": "R Language"
},
{
"code": null,
"e": 42649,
"s": 42551,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42658,
"s": 42649,
"text": "Comments"
},
{
"code": null,
"e": 42671,
"s": 42658,
"text": "Old Comments"
},
{
"code": null,
"e": 42716,
"s": 42671,
"text": "Change column name of a given DataFrame in R"
},
{
"code": null,
"e": 42774,
"s": 42716,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 42837,
"s": 42774,
"text": "Adding elements in a vector in R programming - append() method"
},
{
"code": null,
"e": 42869,
"s": 42837,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 42921,
"s": 42869,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 42958,
"s": 42921,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 42993,
"s": 42958,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 43031,
"s": 42993,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 43075,
"s": 43031,
"text": "How to change Row Names of DataFrame in R ?"
}
] |
How to update data in a MySQL database with Java?
|
To update data into a MySQL database table, use UPDATE command. The syntax is as follows −
update yourTableName set yourColumnName1 = value1,....N where condition;
First, we need to create a table. The query is as follows −
mysql> create table UpdateDemo
-> (
-> id int,
-> Name varchar(200)
-> );
Query OK, 0 rows affected (0.67 sec)
Let us insert records into the table. The following is the query −
mysql> insert into UpdateDemo values(101,'John');
Query OK, 1 row affected (0.19 sec)
mysql> truncate table UpdateDemo;
Query OK, 0 rows affected (0.86 sec)
mysql> insert into UpdateDemo values(1,'John');
Query OK, 1 row affected (0.13 sec)
mysql> insert into UpdateDemo values(2,'Carol');
Query OK, 1 row affected (0.13 sec)
mysql> insert into UpdateDemo values(3,'Smith');
Query OK, 1 row affected (0.18 sec)
mysql> insert into UpdateDemo values(4,'David');
Query OK, 1 row affected (0.15 sec)
Now, display all records from the table with the help of select statement. The query is as follows −
mysql> select *from UpdateDemo;
Here is the output −
+------+-------+
| id | Name |
+------+-------+
| 1 | John |
| 2 | Carol |
| 3 | Smith |
| 4 | David |
+------+-------+
4 rows in set (0.00 sec)
Here is the JAVA code to update records from a MySQL database. We will establish a Java Connection to our MySQL database −
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
public class JavaUpdateDemo {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
System.out.println(e);
}
conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/business", "Manish", "123456");
System.out.println("Connection is created successfully:");
stmt = (Statement) conn.createStatement();
String query1 = "update UpdateDemo set Name='Johnson' " + "where id in(1,4)";
stmt.executeUpdate(query1);
System.out.println("Record has been updated in the table successfully..................");
} catch (SQLException excep) {
excep.printStackTrace();
} catch (Exception excep) {
excep.printStackTrace();
} finally {
try {
if (stmt != null)
conn.close();
} catch (SQLException se) {}
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Please check it in the MySQL Table. Record is now updated.......");
}
}
Here is the output −
We have updated data with id 1 and 4. The Name column with “Johnson” have been updated. The following is the query to check whether the table data has been updated or not with the help of select statement.
mysql> select *from UpdateDemo;
The following is the output −
+------+---------+
| id | Name |
+------+---------+
| 1 | Johnson |
| 2 | Carol |
| 3 | Smith |
| 4 | Johnson |
+------+---------+
4 rows in set (0.00 sec)
Look at the above output, the id 1 and 4 is updated.
|
[
{
"code": null,
"e": 1153,
"s": 1062,
"text": "To update data into a MySQL database table, use UPDATE command. The syntax is as follows −"
},
{
"code": null,
"e": 1226,
"s": 1153,
"text": "update yourTableName set yourColumnName1 = value1,....N where condition;"
},
{
"code": null,
"e": 1286,
"s": 1226,
"text": "First, we need to create a table. The query is as follows −"
},
{
"code": null,
"e": 1409,
"s": 1286,
"text": "mysql> create table UpdateDemo\n -> (\n -> id int,\n -> Name varchar(200)\n -> );\nQuery OK, 0 rows affected (0.67 sec)"
},
{
"code": null,
"e": 1476,
"s": 1409,
"text": "Let us insert records into the table. The following is the query −"
},
{
"code": null,
"e": 1972,
"s": 1476,
"text": "mysql> insert into UpdateDemo values(101,'John');\nQuery OK, 1 row affected (0.19 sec)\nmysql> truncate table UpdateDemo;\nQuery OK, 0 rows affected (0.86 sec)\nmysql> insert into UpdateDemo values(1,'John');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into UpdateDemo values(2,'Carol');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into UpdateDemo values(3,'Smith');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into UpdateDemo values(4,'David');\nQuery OK, 1 row affected (0.15 sec)"
},
{
"code": null,
"e": 2073,
"s": 1972,
"text": "Now, display all records from the table with the help of select statement. The query is as follows −"
},
{
"code": null,
"e": 2105,
"s": 2073,
"text": "mysql> select *from UpdateDemo;"
},
{
"code": null,
"e": 2126,
"s": 2105,
"text": "Here is the output −"
},
{
"code": null,
"e": 2287,
"s": 2126,
"text": "+------+-------+\n| id | Name |\n+------+-------+\n| 1 | John |\n| 2 | Carol |\n| 3 | Smith |\n| 4 | David |\n+------+-------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2410,
"s": 2287,
"text": "Here is the JAVA code to update records from a MySQL database. We will establish a Java Connection to our MySQL database −"
},
{
"code": null,
"e": 3882,
"s": 2410,
"text": "import java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport com.mysql.jdbc.Connection;\nimport com.mysql.jdbc.PreparedStatement;\nimport com.mysql.jdbc.Statement;\npublic class JavaUpdateDemo {\n public static void main(String[] args) {\n Connection conn = null;\n Statement stmt = null;\n try {\n try {\n Class.forName(\"com.mysql.jdbc.Driver\");\n } catch (Exception e) {\n System.out.println(e);\n }\n conn = (Connection) DriverManager.getConnection(\"jdbc:mysql://localhost/business\", \"Manish\", \"123456\");\n System.out.println(\"Connection is created successfully:\");\n stmt = (Statement) conn.createStatement();\n String query1 = \"update UpdateDemo set Name='Johnson' \" + \"where id in(1,4)\";\n stmt.executeUpdate(query1);\n System.out.println(\"Record has been updated in the table successfully..................\");\n } catch (SQLException excep) {\n excep.printStackTrace();\n } catch (Exception excep) {\n excep.printStackTrace();\n } finally {\n try {\n if (stmt != null)\n conn.close();\n } catch (SQLException se) {}\n try {\n if (conn != null)\n conn.close();\n } catch (SQLException se) {\n se.printStackTrace();\n }\n }\n System.out.println(\"Please check it in the MySQL Table. Record is now updated.......\");\n }\n}"
},
{
"code": null,
"e": 3903,
"s": 3882,
"text": "Here is the output −"
},
{
"code": null,
"e": 4109,
"s": 3903,
"text": "We have updated data with id 1 and 4. The Name column with “Johnson” have been updated. The following is the query to check whether the table data has been updated or not with the help of select statement."
},
{
"code": null,
"e": 4141,
"s": 4109,
"text": "mysql> select *from UpdateDemo;"
},
{
"code": null,
"e": 4171,
"s": 4141,
"text": "The following is the output −"
},
{
"code": null,
"e": 4348,
"s": 4171,
"text": "+------+---------+\n| id | Name |\n+------+---------+\n| 1 | Johnson |\n| 2 | Carol |\n| 3 | Smith |\n| 4 | Johnson |\n+------+---------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 4401,
"s": 4348,
"text": "Look at the above output, the id 1 and 4 is updated."
}
] |
How to call a JavaScript function from an onsubmit event?
|
The onsubmit event occurs when you try to submit a form. You can put your form validation against this event type. The following example shows how to use onsubmit. Here, we are calling a validate() function before submitting a form data to the webserver. If validate() function returns true, the form will be submitted, otherwise it will not submit the data.
<script>
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
<form method="POST" action="new.cgi" onsubmit="return validate()">
.......
<input type="submit" value="Submit" />
</form>
|
[
{
"code": null,
"e": 1421,
"s": 1062,
"text": "The onsubmit event occurs when you try to submit a form. You can put your form validation against this event type. The following example shows how to use onsubmit. Here, we are calling a validate() function before submitting a form data to the webserver. If validate() function returns true, the form will be submitted, otherwise it will not submit the data."
},
{
"code": null,
"e": 1585,
"s": 1421,
"text": "<script>\n <!--\n function validation() {\n all validation goes here\n .........\n return either true or false\n }\n //-->\n</script>"
},
{
"code": null,
"e": 1713,
"s": 1585,
"text": "<form method=\"POST\" action=\"new.cgi\" onsubmit=\"return validate()\">\n .......\n <input type=\"submit\" value=\"Submit\" />\n</form>"
}
] |
Gulp - Optimizing CSS and JavaScript
|
In this chapter, you will learn how to optimize CSS and JavaScript. Optimizing is required to remove unnecessary data (for e.g. spaces and unused characters) from the source files. It reduces the size of the files and allows them to load faster
Go to “work” directory from your command line and install “gulp-uglify”, “gulp-minify-css” and “gulp-concat” plugins by using the following command −
npm install gulp-uglify gulp-minify-css gulp-concat
In your configuration file gulpfile.js, first declare the dependencies as shown in the following code.
var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var minify = require('gulp-minify-css');
Next, you need to create tasks for optimizing CSS and JavaScript as shown in the following code.
gulp.task('js', function(){
gulp.src('src/scripts/*.js')
.pipe(concat('script.js'))
.pipe(uglify())
.pipe(gulp.dest('build/scripts/'));
});
gulp.task('css', function(){
gulp.src('src/styles/*.css')
.pipe(concat('styles.css'))
.pipe(minify())
.pipe(gulp.dest('build/styles/'));
});
gulp.task('default',['js','css'],function(){
});
The js task will accepts .js files from src/scripts/ folder. It concatenates and uglifies the js files, then produces build/scripts/script.js file.
The CSS task will accept .css files from src/styles/ folder. It concatenates and minifies CSS files, then produces build/styles/styles.css file.
The configuration file is set up and ready to execute. Use the following command to run the task.
gulp
On running the task using the above command, you will receive the following result in the command prompt.
C:\work>gulp
[13:16:34] Using gulpfile C:\work\gulpfile.js
[13:16:34] Starting 'js'...
[13:16:34] Finished 'js' after 24 ms
[13:16:34] Starting 'css'...
[13:16:34] Finished 'css' after 6.05 ms
[13:16:34] Starting 'default'...
[13:16:34] Finished 'default' after 5.04 μs
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2061,
"s": 1816,
"text": "In this chapter, you will learn how to optimize CSS and JavaScript. Optimizing is required to remove unnecessary data (for e.g. spaces and unused characters) from the source files. It reduces the size of the files and allows them to load faster"
},
{
"code": null,
"e": 2211,
"s": 2061,
"text": "Go to “work” directory from your command line and install “gulp-uglify”, “gulp-minify-css” and “gulp-concat” plugins by using the following command −"
},
{
"code": null,
"e": 2264,
"s": 2211,
"text": "npm install gulp-uglify gulp-minify-css gulp-concat\n"
},
{
"code": null,
"e": 2367,
"s": 2264,
"text": "In your configuration file gulpfile.js, first declare the dependencies as shown in the following code."
},
{
"code": null,
"e": 2511,
"s": 2367,
"text": "var gulp = require('gulp');\nvar concat = require('gulp-concat');\nvar uglify = require('gulp-uglify');\nvar minify = require('gulp-minify-css');\n"
},
{
"code": null,
"e": 2608,
"s": 2511,
"text": "Next, you need to create tasks for optimizing CSS and JavaScript as shown in the following code."
},
{
"code": null,
"e": 2964,
"s": 2608,
"text": "gulp.task('js', function(){\n gulp.src('src/scripts/*.js')\n .pipe(concat('script.js'))\n .pipe(uglify())\n .pipe(gulp.dest('build/scripts/'));\n});\n\ngulp.task('css', function(){\n gulp.src('src/styles/*.css')\n .pipe(concat('styles.css'))\n .pipe(minify())\n .pipe(gulp.dest('build/styles/'));\n});\n\ngulp.task('default',['js','css'],function(){\n});"
},
{
"code": null,
"e": 3112,
"s": 2964,
"text": "The js task will accepts .js files from src/scripts/ folder. It concatenates and uglifies the js files, then produces build/scripts/script.js file."
},
{
"code": null,
"e": 3257,
"s": 3112,
"text": "The CSS task will accept .css files from src/styles/ folder. It concatenates and minifies CSS files, then produces build/styles/styles.css file."
},
{
"code": null,
"e": 3355,
"s": 3257,
"text": "The configuration file is set up and ready to execute. Use the following command to run the task."
},
{
"code": null,
"e": 3361,
"s": 3355,
"text": "gulp\n"
},
{
"code": null,
"e": 3467,
"s": 3361,
"text": "On running the task using the above command, you will receive the following result in the command prompt."
},
{
"code": null,
"e": 3738,
"s": 3467,
"text": "C:\\work>gulp\n[13:16:34] Using gulpfile C:\\work\\gulpfile.js\n[13:16:34] Starting 'js'...\n[13:16:34] Finished 'js' after 24 ms\n[13:16:34] Starting 'css'...\n[13:16:34] Finished 'css' after 6.05 ms\n[13:16:34] Starting 'default'...\n[13:16:34] Finished 'default' after 5.04 μs\n"
},
{
"code": null,
"e": 3745,
"s": 3738,
"text": " Print"
},
{
"code": null,
"e": 3756,
"s": 3745,
"text": " Add Notes"
}
] |
Count of distinct substrings | Practice | GeeksforGeeks
|
Given a string of length N of lowercase alphabet characters. The task is to complete the function countDistinctSubstring(), which returns the count of total number of distinct substrings of this string.
Input:
The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. Each test case contains a string str.
Output:
For each test case in a new line, output will be an integer denoting count of total number of distinct substrings of this string.
User Task:
Since this is a functional problem you don't have to worry about input, you just have to complete the function countDistinctSubstring().
Constraints:
1 ≤ T ≤ 10
1 ≤ N ≤ 1000
Example(To be used only for expected output):
Input:
2
ab
ababa
Output:
4
10
Exaplanation:
Testcase 1: For the given string "ab" the total distinct substrings are: "", "a", "b", "ab".
0
theanmolmalik2 months ago
C++ Solution using Trie
class Node
{
public:
bool isWord;
Node* child[26];
Node()
{
isWord=0;
for(int i=0;i<26;i++)
{
child[i]=0;
}
}
};
int countDistinctSubstring(string s)
{
Node* head=new Node();
int count=1;
for(int i=0;i<s.size();i++)
{
Node* temp=head;
for(int j=i;j<s.size();j++)
{
if(temp->child[s[j]-'a']==NULL)
{
temp->child[s[j]-'a']=new Node();
temp->isWord=1;
count++;
}
temp=temp->child[s[j]-'a'];
}
}
return count;
}
+1
ashiqhussainkumar1432 months ago
struct Node { Node *ref[26]; bool flag=false; void setEnd(){ flag=true; } bool containsKey(char c){ return ref[c-'a']!=NULL; } Node *get(char c){ return ref[c-'a']; } void put(char c ){ Node *node=new Node(); ref[c-'a']=node; }};
int countDistinctSubstring(string s){ //Your code here int count=0; struct Node *root=new Node(); for(int i=0;i<s.length();i++){ struct Node *node=root; for(int j=i;j<s.length();j++){ if(!node->containsKey(s[j])){ node->put(s[j]); count++; } node=node->get(s[j]); } node->setEnd(); } return count+1;}
0
piyushsharma9129126 months ago
@geeksforgeeks please provide exact constrain, time complexity and space complexity of this problem.
0
shivam__996 months ago
//simple trie solution
class Node {
public:
char data;
unordered_map<char,Node*> m;
bool isTerminal;
Node(char ch)
{
data=ch;
isTerminal=false;
}
};
class Trie{
public:
Node * root;
Trie()
{
root=new Node('\0');
}
};
int countDistinctSubstring(string s)
{
int cnt=1; //included count of substr " "
Trie t;
for(int i=0;i<s.size();i++)
{
Node* temp=t.root;
for(int j=i;j<s.size();j++)
{
if(temp->m.count(s[j])==0)
{
Node* n=new Node(s[j]);
temp->m[s[j]]=n;
cnt++;
}
temp=temp->m[s[j]];
if(!temp->isTerminal)
temp->isTerminal=true;
}
}
return cnt;
}
0
wallflower9 months ago
wallflower
Java trie solution. Just insert all suffixes in trie.https://ide.geeksforgeeks.o...
+1
Suryan Jain10 months ago
Suryan Jain
Python 1.18
def countDistinctSubstring(s): #code here ans=set() n=len(s) for window in range(n): i=0 for j in range(window,n): ans.add(s[i:j+1]) i+=1 return len(ans)+1
0
Shivam Jha10 months ago
Shivam Jha
Why am i getting SIGABRT error in this?class Trie{ public: vector<trie*>child; bool isend; Trie(){ isend=false; child=vector<trie*>(26,NULL); }}; void insert(char key,Trie *root,string s){ Trie * curr= root; int index=key-'a'; curr->child[index]=new Trie(); curr->child[index]->isend=true; curr=curr->child[index]; for(int i=0;i<s.size();i++){ int="" index="s[i]-'a';" if(curr-="">child[index]==NULL){ curr->child[index]=new Trie(); } curr=curr->child[index]; curr->isend=true; } } bool search(Trie *root, string key){ Trie *curr=root; for(int i=0;i<key.size();i++){ int="" index="key[i]-'a';" if(curr-="">child[index]==NULL) return false; curr=curr->child[index]; } return (curr!= NULL and curr->isend); } int distinct(Trie *root){ int count = 0; for (int i = 0; i < 26; i++) { if (root->child[i] != NULL) { count += distinct(root->child[i]); } } return count + 1; }int countDistinctSubstring(string s){ // total no of non empty substring of any string of n length will be n*(n+1)/2 // if empty is included then total will be = n* (n+1)/2 +1; // unordered_set<string> st; // int n=s.size(); // for(int i=0;i<n;i++){ for(int="" j="1;j<=n-i;j++){" if(st.count(s.substr(i,j)))="" continue;="" st.insert(s.substr(i,j));="" }="" }="" return="" st.size()+1;="" trie="" *root="new" trie();="" int="" n="s.size();" string="" temp="" ;="" for(int="" i="0;i<n;i++){" if(search(root,temp+s[i]))="" continue;="" insert(s[i],root,s.substr(i));="" temp.pop_back();="" }="" return="" distinct(root);="" <="" code="">
0
Adarsh Gautam11 months ago
Adarsh Gautam
Execution Time:0.31 Using Trie Only
0
Mustafa Basit1 year ago
Mustafa Basit
using Trieclass GfG{ static class TrieNode { TrieNode childrens[]; boolean isEnd; TrieNode() { childrens = new TrieNode[26]; isEnd = false; } } static void insertString(TrieNode root, String S) { TrieNode node = root; for(int level = 0; level < S.length(); level++) { if (node.childrens[S.charAt(level) - 'a'] == null){ node.childrens[S.charAt(level) - 'a'] = new TrieNode(); } node = node.childrens[S.charAt(level) - 'a']; } node.isEnd = true; } static int countNodes(TrieNode root) { int count = 0; for (int i = 0; i < root.childrens.length; i++) { if (root.childrens[i] != null) { count += countNodes(root.childrens[i]); } } return count + 1; } public static int countDistinctSubstring(String S) { //your code here TrieNode root = new TrieNode(); for (int i = 0; i < S.length(); i++) { insertString(root, S.substring(i)); } return countNodes(root); }}
0
Vikas Thapliyal
This comment was deleted.
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": 429,
"s": 226,
"text": "Given a string of length N of lowercase alphabet characters. The task is to complete the function countDistinctSubstring(), which returns the count of total number of distinct substrings of this string."
},
{
"code": null,
"e": 582,
"s": 429,
"text": "Input:\nThe first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. Each test case contains a string str."
},
{
"code": null,
"e": 720,
"s": 582,
"text": "Output:\nFor each test case in a new line, output will be an integer denoting count of total number of distinct substrings of this string."
},
{
"code": null,
"e": 868,
"s": 720,
"text": "User Task:\nSince this is a functional problem you don't have to worry about input, you just have to complete the function countDistinctSubstring()."
},
{
"code": null,
"e": 905,
"s": 868,
"text": "Constraints:\n1 ≤ T ≤ 10\n1 ≤ N ≤ 1000"
},
{
"code": null,
"e": 969,
"s": 905,
"text": "Example(To be used only for expected output):\nInput:\n2\nab\nababa"
},
{
"code": null,
"e": 982,
"s": 969,
"text": "Output:\n4\n10"
},
{
"code": null,
"e": 1091,
"s": 982,
"text": "Exaplanation:\nTestcase 1: For the given string \"ab\" the total distinct substrings are: \"\", \"a\", \"b\", \"ab\".\n "
},
{
"code": null,
"e": 1093,
"s": 1091,
"text": "0"
},
{
"code": null,
"e": 1119,
"s": 1093,
"text": "theanmolmalik2 months ago"
},
{
"code": null,
"e": 1143,
"s": 1119,
"text": "C++ Solution using Trie"
},
{
"code": null,
"e": 1860,
"s": 1145,
"text": "class Node\n{\n public:\n bool isWord;\n Node* child[26];\n \n Node()\n {\n isWord=0;\n for(int i=0;i<26;i++)\n {\n child[i]=0;\n }\n }\n};\n\nint countDistinctSubstring(string s)\n{\n Node* head=new Node();\n \n int count=1;\n \n for(int i=0;i<s.size();i++)\n {\n Node* temp=head;\n \n for(int j=i;j<s.size();j++)\n {\n if(temp->child[s[j]-'a']==NULL)\n {\n temp->child[s[j]-'a']=new Node();\n temp->isWord=1;\n count++;\n }\n \n temp=temp->child[s[j]-'a'];\n }\n }\n \n return count;\n}"
},
{
"code": null,
"e": 1863,
"s": 1860,
"text": "+1"
},
{
"code": null,
"e": 1896,
"s": 1863,
"text": "ashiqhussainkumar1432 months ago"
},
{
"code": null,
"e": 2179,
"s": 1896,
"text": "struct Node { Node *ref[26]; bool flag=false; void setEnd(){ flag=true; } bool containsKey(char c){ return ref[c-'a']!=NULL; } Node *get(char c){ return ref[c-'a']; } void put(char c ){ Node *node=new Node(); ref[c-'a']=node; }};"
},
{
"code": null,
"e": 2580,
"s": 2181,
"text": "int countDistinctSubstring(string s){ //Your code here int count=0; struct Node *root=new Node(); for(int i=0;i<s.length();i++){ struct Node *node=root; for(int j=i;j<s.length();j++){ if(!node->containsKey(s[j])){ node->put(s[j]); count++; } node=node->get(s[j]); } node->setEnd(); } return count+1;}"
},
{
"code": null,
"e": 2582,
"s": 2580,
"text": "0"
},
{
"code": null,
"e": 2613,
"s": 2582,
"text": "piyushsharma9129126 months ago"
},
{
"code": null,
"e": 2715,
"s": 2613,
"text": "@geeksforgeeks please provide exact constrain, time complexity and space complexity of this problem. "
},
{
"code": null,
"e": 2717,
"s": 2715,
"text": "0"
},
{
"code": null,
"e": 2740,
"s": 2717,
"text": "shivam__996 months ago"
},
{
"code": null,
"e": 3535,
"s": 2740,
"text": "//simple trie solution\nclass Node {\n public:\n char data;\n unordered_map<char,Node*> m;\n bool isTerminal;\n Node(char ch)\n {\n data=ch;\n isTerminal=false;\n }\n};\n\nclass Trie{\n \n public:\n Node * root;\n Trie()\n {\n root=new Node('\\0');\n }\n};\n\nint countDistinctSubstring(string s)\n{\n int cnt=1; //included count of substr \" \"\n Trie t;\n \n for(int i=0;i<s.size();i++)\n {\n Node* temp=t.root;\n for(int j=i;j<s.size();j++)\n {\n if(temp->m.count(s[j])==0)\n {\n Node* n=new Node(s[j]);\n temp->m[s[j]]=n;\n cnt++;\n }\n temp=temp->m[s[j]];\n if(!temp->isTerminal)\n temp->isTerminal=true;\n \n }\n }\n return cnt;\n \n}"
},
{
"code": null,
"e": 3537,
"s": 3535,
"text": "0"
},
{
"code": null,
"e": 3560,
"s": 3537,
"text": "wallflower9 months ago"
},
{
"code": null,
"e": 3571,
"s": 3560,
"text": "wallflower"
},
{
"code": null,
"e": 3655,
"s": 3571,
"text": "Java trie solution. Just insert all suffixes in trie.https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 3658,
"s": 3655,
"text": "+1"
},
{
"code": null,
"e": 3683,
"s": 3658,
"text": "Suryan Jain10 months ago"
},
{
"code": null,
"e": 3695,
"s": 3683,
"text": "Suryan Jain"
},
{
"code": null,
"e": 3707,
"s": 3695,
"text": "Python 1.18"
},
{
"code": null,
"e": 3926,
"s": 3707,
"text": "def countDistinctSubstring(s): #code here ans=set() n=len(s) for window in range(n): i=0 for j in range(window,n): ans.add(s[i:j+1]) i+=1 return len(ans)+1"
},
{
"code": null,
"e": 3928,
"s": 3926,
"text": "0"
},
{
"code": null,
"e": 3952,
"s": 3928,
"text": "Shivam Jha10 months ago"
},
{
"code": null,
"e": 3963,
"s": 3952,
"text": "Shivam Jha"
},
{
"code": null,
"e": 5728,
"s": 3963,
"text": "Why am i getting SIGABRT error in this?class Trie{ public: vector<trie*>child; bool isend; Trie(){ isend=false; child=vector<trie*>(26,NULL); }}; void insert(char key,Trie *root,string s){ Trie * curr= root; int index=key-'a'; curr->child[index]=new Trie(); curr->child[index]->isend=true; curr=curr->child[index]; for(int i=0;i<s.size();i++){ int=\"\" index=\"s[i]-'a';\" if(curr-=\"\">child[index]==NULL){ curr->child[index]=new Trie(); } curr=curr->child[index]; curr->isend=true; } } bool search(Trie *root, string key){ Trie *curr=root; for(int i=0;i<key.size();i++){ int=\"\" index=\"key[i]-'a';\" if(curr-=\"\">child[index]==NULL) return false; curr=curr->child[index]; } return (curr!= NULL and curr->isend); } int distinct(Trie *root){ int count = 0; for (int i = 0; i < 26; i++) { if (root->child[i] != NULL) { count += distinct(root->child[i]); } } return count + 1; }int countDistinctSubstring(string s){ // total no of non empty substring of any string of n length will be n*(n+1)/2 // if empty is included then total will be = n* (n+1)/2 +1; // unordered_set<string> st; // int n=s.size(); // for(int i=0;i<n;i++){ for(int=\"\" j=\"1;j<=n-i;j++){\" if(st.count(s.substr(i,j)))=\"\" continue;=\"\" st.insert(s.substr(i,j));=\"\" }=\"\" }=\"\" return=\"\" st.size()+1;=\"\" trie=\"\" *root=\"new\" trie();=\"\" int=\"\" n=\"s.size();\" string=\"\" temp=\"\" ;=\"\" for(int=\"\" i=\"0;i<n;i++){\" if(search(root,temp+s[i]))=\"\" continue;=\"\" insert(s[i],root,s.substr(i));=\"\" temp.pop_back();=\"\" }=\"\" return=\"\" distinct(root);=\"\" <=\"\" code=\"\">"
},
{
"code": null,
"e": 5730,
"s": 5728,
"text": "0"
},
{
"code": null,
"e": 5757,
"s": 5730,
"text": "Adarsh Gautam11 months ago"
},
{
"code": null,
"e": 5771,
"s": 5757,
"text": "Adarsh Gautam"
},
{
"code": null,
"e": 5807,
"s": 5771,
"text": "Execution Time:0.31 Using Trie Only"
},
{
"code": null,
"e": 5809,
"s": 5807,
"text": "0"
},
{
"code": null,
"e": 5833,
"s": 5809,
"text": "Mustafa Basit1 year ago"
},
{
"code": null,
"e": 5847,
"s": 5833,
"text": "Mustafa Basit"
},
{
"code": null,
"e": 6986,
"s": 5847,
"text": "using Trieclass GfG{ static class TrieNode { TrieNode childrens[]; boolean isEnd; TrieNode() { childrens = new TrieNode[26]; isEnd = false; } } static void insertString(TrieNode root, String S) { TrieNode node = root; for(int level = 0; level < S.length(); level++) { if (node.childrens[S.charAt(level) - 'a'] == null){ node.childrens[S.charAt(level) - 'a'] = new TrieNode(); } node = node.childrens[S.charAt(level) - 'a']; } node.isEnd = true; } static int countNodes(TrieNode root) { int count = 0; for (int i = 0; i < root.childrens.length; i++) { if (root.childrens[i] != null) { count += countNodes(root.childrens[i]); } } return count + 1; } public static int countDistinctSubstring(String S) { //your code here TrieNode root = new TrieNode(); for (int i = 0; i < S.length(); i++) { insertString(root, S.substring(i)); } return countNodes(root); }}"
},
{
"code": null,
"e": 6988,
"s": 6986,
"text": "0"
},
{
"code": null,
"e": 7004,
"s": 6988,
"text": "Vikas Thapliyal"
},
{
"code": null,
"e": 7030,
"s": 7004,
"text": "This comment was deleted."
},
{
"code": null,
"e": 7176,
"s": 7030,
"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": 7212,
"s": 7176,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7222,
"s": 7212,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7232,
"s": 7222,
"text": "\nContest\n"
},
{
"code": null,
"e": 7295,
"s": 7232,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7443,
"s": 7295,
"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": 7651,
"s": 7443,
"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": 7757,
"s": 7651,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.