title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Python | Create list of numbers with given range | 20 Nov, 2019
Given two numbers r1 and r2 (which defines the range), write a Python program to create a list with the given range (inclusive).
Examples:
Input : r1 = -1, r2 = 1
Output : [-1, 0, 1]
Input : r1 = 5, r2 = 9
Output : [5, 6, 7, 8, 9]
Let’s discuss a few approaches to do this task.
Approach #1 : Naive Approach
A naive method to create list within a given range is to first create an empty list and append successor of each integer in every iteration of for loop.
# Python3 Program to Create list # with integers within given range def createList(r1, r2): # Testing if range r1 and r2 # are equal if (r1 == r2): return r1 else: # Create empty list res = [] # loop to append successors to # list until r2 is reached. while(r1 < r2+1 ): res.append(r1) r1 += 1 return res # Driver Coder1, r2 = -1, 1print(createList(r1, r2))
[-1, 0, 1]
Approach #2 : List comprehension
We can also use list comprehension for the purpose. Just iterate ‘item’ in a for loop from r1 to r2 and return all ‘item’ as list. This will be a simple one liner code.
# Python3 Program to Create list # with integers within given range def createList(r1, r2): return [item for item in range(r1, r2+1)] # Driver Coder1, r2 = -1, 1print(createList(r1, r2))
[-1, 0, 1]
Approach #3 : using Python range()
Python comes with a direct function range() which creates a sequence of numbers from start to stop values and print each item in the sequence. We use range() with r1 and r2 and then convert the sequence into list.
# Python3 Program to Create list # with integers within given range def createList(r1, r2): return list(range(r1, r2+1)) # Driver Coder1, r2 = -1, 1print(createList(r1, r2))
[-1, 0, 1]
Approach #4 : Using numpy.arange()
Python numpy.arange() returns a list with evenly spaced elements as per the interval. Here we set the interval as 1 according to our need to get the desired output.
# Python3 Program to Create list # with integers within given range import numpy as npdef createList(r1, r2): return np.arange(r1, r2+1, 1) # Driver Coder1, r2 = -1, 1print(createList(r1, r2))
[-1 0 1]
ManasChhabra2
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Enumerate() in Python
Read a file line by line in Python
Different ways to create Pandas Dataframe
How to Install PIP on Windows ?
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n20 Nov, 2019"
},
{
"code": null,
"e": 182,
"s": 53,
"text": "Given two numbers r1 and r2 (which defines the range), write a Python program to create a list with the given range (inclusive)."
},
{
"code": null,
"e": 192,
"s": 182,
"text": "Examples:"
},
{
"code": null,
"e": 286,
"s": 192,
"text": "Input : r1 = -1, r2 = 1\nOutput : [-1, 0, 1]\n\nInput : r1 = 5, r2 = 9\nOutput : [5, 6, 7, 8, 9]\n"
},
{
"code": null,
"e": 334,
"s": 286,
"text": "Let’s discuss a few approaches to do this task."
},
{
"code": null,
"e": 363,
"s": 334,
"text": "Approach #1 : Naive Approach"
},
{
"code": null,
"e": 516,
"s": 363,
"text": "A naive method to create list within a given range is to first create an empty list and append successor of each integer in every iteration of for loop."
},
{
"code": "# Python3 Program to Create list # with integers within given range def createList(r1, r2): # Testing if range r1 and r2 # are equal if (r1 == r2): return r1 else: # Create empty list res = [] # loop to append successors to # list until r2 is reached. while(r1 < r2+1 ): res.append(r1) r1 += 1 return res # Driver Coder1, r2 = -1, 1print(createList(r1, r2))",
"e": 988,
"s": 516,
"text": null
},
{
"code": null,
"e": 1000,
"s": 988,
"text": "[-1, 0, 1]\n"
},
{
"code": null,
"e": 1034,
"s": 1000,
"text": " Approach #2 : List comprehension"
},
{
"code": null,
"e": 1203,
"s": 1034,
"text": "We can also use list comprehension for the purpose. Just iterate ‘item’ in a for loop from r1 to r2 and return all ‘item’ as list. This will be a simple one liner code."
},
{
"code": "# Python3 Program to Create list # with integers within given range def createList(r1, r2): return [item for item in range(r1, r2+1)] # Driver Coder1, r2 = -1, 1print(createList(r1, r2))",
"e": 1400,
"s": 1203,
"text": null
},
{
"code": null,
"e": 1412,
"s": 1400,
"text": "[-1, 0, 1]\n"
},
{
"code": null,
"e": 1448,
"s": 1412,
"text": " Approach #3 : using Python range()"
},
{
"code": null,
"e": 1662,
"s": 1448,
"text": "Python comes with a direct function range() which creates a sequence of numbers from start to stop values and print each item in the sequence. We use range() with r1 and r2 and then convert the sequence into list."
},
{
"code": "# Python3 Program to Create list # with integers within given range def createList(r1, r2): return list(range(r1, r2+1)) # Driver Coder1, r2 = -1, 1print(createList(r1, r2))",
"e": 1846,
"s": 1662,
"text": null
},
{
"code": null,
"e": 1858,
"s": 1846,
"text": "[-1, 0, 1]\n"
},
{
"code": null,
"e": 1894,
"s": 1858,
"text": " Approach #4 : Using numpy.arange()"
},
{
"code": null,
"e": 2059,
"s": 1894,
"text": "Python numpy.arange() returns a list with evenly spaced elements as per the interval. Here we set the interval as 1 according to our need to get the desired output."
},
{
"code": "# Python3 Program to Create list # with integers within given range import numpy as npdef createList(r1, r2): return np.arange(r1, r2+1, 1) # Driver Coder1, r2 = -1, 1print(createList(r1, r2))",
"e": 2260,
"s": 2059,
"text": null
},
{
"code": null,
"e": 2272,
"s": 2260,
"text": "[-1 0 1]\n"
},
{
"code": null,
"e": 2286,
"s": 2272,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 2307,
"s": 2286,
"text": "Python list-programs"
},
{
"code": null,
"e": 2319,
"s": 2307,
"text": "python-list"
},
{
"code": null,
"e": 2326,
"s": 2319,
"text": "Python"
},
{
"code": null,
"e": 2342,
"s": 2326,
"text": "Python Programs"
},
{
"code": null,
"e": 2354,
"s": 2342,
"text": "python-list"
},
{
"code": null,
"e": 2452,
"s": 2354,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2474,
"s": 2452,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2509,
"s": 2474,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2551,
"s": 2509,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2583,
"s": 2551,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2609,
"s": 2583,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2652,
"s": 2609,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2674,
"s": 2652,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2713,
"s": 2674,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2751,
"s": 2713,
"text": "Python | Convert a list to dictionary"
}
] |
How to Calculate MAPE in Python? | 28 Nov, 2021
In this article, we will see how to compute one of the methods to determine forecast accuracy called the Mean. Absolute Percentage Error (or simply MAPE) also known as Mean Absolute Percentage Deviation (MAPD) in python. The MAPE term determines how better accuracy does our forecast gives. The ‘M’ in MAPE stands for mean which takes in the average value over a series, ‘A’ stands for absolute that uses absolute values to keep the positive and negative errors from canceling one another out, ‘P’ is the percentage that makes this accuracy metric a relative metric, and the ‘E’ stands for error since this metric helps to determine the amount of error our forecast has.
Consider the following example, where we have the sales information of a store. The day column represents the day number which we are referring to, the actual sales column represents the actual sales value for the respective day whereas the forecast sales column represents the forecasted values for the sales figures (probably with an ML model). The APE column stands for Absolute percentage error (APE) which represents the percentage error between the actual and the forecasted value for the corresponding day. The formula for the percentage error is (actual value – forecast value) / actual value. The APE is the positive (absolute) value of this percentage error
Day No.
Actual Sales
Forecast Sales
Absolute Percentage Error (APE)
1
136
134
0.014
2
120
124
0.033
3
138
132
0.043
4
155
141
0.090
5
149
149
0.0
Now, the MAPE value can be found by taking the mean of the APE values. The formula can be represented as –
MAPE formula
Python
# Define the dataset as python listsactual = [136, 120, 138, 155, 149]forecast = [134, 124, 132, 141, 149] # Consider a list APE to store the# APE value for each of the records in datasetAPE = [] # Iterate over the list valuesfor day in range(5): # Calculate percentage error per_err = (actual[day] - forecast[day]) / actual[day] # Take absolute value of # the percentage error (APE) per_err = abs(per_err) # Append it to the APE list APE.append(per_err) # Calculate the MAPEMAPE = sum(APE)/len(APE) # Print the MAPE value and percentageprint(f'''MAPE : { round(MAPE, 2) }MAPE % : { round(MAPE*100, 2) } %''')
Output:
MAPE Output – 1
MAPE output is a non-negative floating-point. The best value for MAPE is 0.0 whereas a higher value determines that the predictions are not accurate enough. However, how much large a MAPE value should be to term it as an inefficient prediction depends upon the use case. In the above output, we can see that the forecast values are good enough because the MAPE suggests that there is a 3% error in the forecasted values for the sales made on each day.
If you are working on time series data in python, you might be probably working with pandas or NumPy. In such case, you can use the following code to get the MAPE output.
Python
import pandas as pdimport numpy as np # Define the function to return the MAPE valuesdef calculate_mape(actual, predicted) -> float: # Convert actual and predicted # to numpy array data type if not already if not all([isinstance(actual, np.ndarray), isinstance(predicted, np.ndarray)]): actual, predicted = np.array(actual), np.array(predicted) # Calculate the MAPE value and return return round(np.mean(np.abs(( actual - predicted) / actual)) * 100, 2) if __name__ == '__main__': # CALCULATE MAPE FROM PYTHON LIST actual = [136, 120, 138, 155, 149] predicted = [134, 124, 132, 141, 149] # Get MAPE for python list as parameters print("py list :", calculate_mape(actual, predicted), "%") # CALCULATE MAPE FROM NUMPY ARRAY actual = np.array([136, 120, 138, 155, 149]) predicted = np.array([134, 124, 132, 141, 149]) # Get MAPE for python list as parameters print("np array :", calculate_mape(actual, predicted), "%") # CALCULATE MAPE FROM PANDAS DATAFRAME # Define the pandas dataframe sales_df = pd.DataFrame({ "actual" : [136, 120, 138, 155, 149], "predicted" : [134, 124, 132, 141, 149] }) # Get MAPE for pandas series as parameters print("pandas df:", calculate_mape(sales_df.actual, sales_df.predicted), "%")
Output:
MAPE Output – 2
In the above program, we have depicted a single function `calculate_mape()` which does the MAPE calculation for a given python list, NumPy array, or pandas series. The output is the same as the same data is passed to all the 3 data type formats as parameters to the function.
Picked
Python-numpy
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 700,
"s": 28,
"text": "In this article, we will see how to compute one of the methods to determine forecast accuracy called the Mean. Absolute Percentage Error (or simply MAPE) also known as Mean Absolute Percentage Deviation (MAPD) in python. The MAPE term determines how better accuracy does our forecast gives. The ‘M’ in MAPE stands for mean which takes in the average value over a series, ‘A’ stands for absolute that uses absolute values to keep the positive and negative errors from canceling one another out, ‘P’ is the percentage that makes this accuracy metric a relative metric, and the ‘E’ stands for error since this metric helps to determine the amount of error our forecast has. "
},
{
"code": null,
"e": 1368,
"s": 700,
"text": "Consider the following example, where we have the sales information of a store. The day column represents the day number which we are referring to, the actual sales column represents the actual sales value for the respective day whereas the forecast sales column represents the forecasted values for the sales figures (probably with an ML model). The APE column stands for Absolute percentage error (APE) which represents the percentage error between the actual and the forecasted value for the corresponding day. The formula for the percentage error is (actual value – forecast value) / actual value. The APE is the positive (absolute) value of this percentage error"
},
{
"code": null,
"e": 1376,
"s": 1368,
"text": "Day No."
},
{
"code": null,
"e": 1389,
"s": 1376,
"text": "Actual Sales"
},
{
"code": null,
"e": 1404,
"s": 1389,
"text": "Forecast Sales"
},
{
"code": null,
"e": 1436,
"s": 1404,
"text": "Absolute Percentage Error (APE)"
},
{
"code": null,
"e": 1438,
"s": 1436,
"text": "1"
},
{
"code": null,
"e": 1442,
"s": 1438,
"text": "136"
},
{
"code": null,
"e": 1446,
"s": 1442,
"text": "134"
},
{
"code": null,
"e": 1452,
"s": 1446,
"text": "0.014"
},
{
"code": null,
"e": 1454,
"s": 1452,
"text": "2"
},
{
"code": null,
"e": 1458,
"s": 1454,
"text": "120"
},
{
"code": null,
"e": 1462,
"s": 1458,
"text": "124"
},
{
"code": null,
"e": 1468,
"s": 1462,
"text": "0.033"
},
{
"code": null,
"e": 1470,
"s": 1468,
"text": "3"
},
{
"code": null,
"e": 1474,
"s": 1470,
"text": "138"
},
{
"code": null,
"e": 1478,
"s": 1474,
"text": "132"
},
{
"code": null,
"e": 1484,
"s": 1478,
"text": "0.043"
},
{
"code": null,
"e": 1486,
"s": 1484,
"text": "4"
},
{
"code": null,
"e": 1490,
"s": 1486,
"text": "155"
},
{
"code": null,
"e": 1494,
"s": 1490,
"text": "141"
},
{
"code": null,
"e": 1500,
"s": 1494,
"text": "0.090"
},
{
"code": null,
"e": 1502,
"s": 1500,
"text": "5"
},
{
"code": null,
"e": 1506,
"s": 1502,
"text": "149"
},
{
"code": null,
"e": 1510,
"s": 1506,
"text": "149"
},
{
"code": null,
"e": 1514,
"s": 1510,
"text": "0.0"
},
{
"code": null,
"e": 1621,
"s": 1514,
"text": "Now, the MAPE value can be found by taking the mean of the APE values. The formula can be represented as –"
},
{
"code": null,
"e": 1634,
"s": 1621,
"text": "MAPE formula"
},
{
"code": null,
"e": 1641,
"s": 1634,
"text": "Python"
},
{
"code": "# Define the dataset as python listsactual = [136, 120, 138, 155, 149]forecast = [134, 124, 132, 141, 149] # Consider a list APE to store the# APE value for each of the records in datasetAPE = [] # Iterate over the list valuesfor day in range(5): # Calculate percentage error per_err = (actual[day] - forecast[day]) / actual[day] # Take absolute value of # the percentage error (APE) per_err = abs(per_err) # Append it to the APE list APE.append(per_err) # Calculate the MAPEMAPE = sum(APE)/len(APE) # Print the MAPE value and percentageprint(f'''MAPE : { round(MAPE, 2) }MAPE % : { round(MAPE*100, 2) } %''')",
"e": 2286,
"s": 1641,
"text": null
},
{
"code": null,
"e": 2294,
"s": 2286,
"text": "Output:"
},
{
"code": null,
"e": 2310,
"s": 2294,
"text": "MAPE Output – 1"
},
{
"code": null,
"e": 2762,
"s": 2310,
"text": "MAPE output is a non-negative floating-point. The best value for MAPE is 0.0 whereas a higher value determines that the predictions are not accurate enough. However, how much large a MAPE value should be to term it as an inefficient prediction depends upon the use case. In the above output, we can see that the forecast values are good enough because the MAPE suggests that there is a 3% error in the forecasted values for the sales made on each day."
},
{
"code": null,
"e": 2933,
"s": 2762,
"text": "If you are working on time series data in python, you might be probably working with pandas or NumPy. In such case, you can use the following code to get the MAPE output."
},
{
"code": null,
"e": 2940,
"s": 2933,
"text": "Python"
},
{
"code": "import pandas as pdimport numpy as np # Define the function to return the MAPE valuesdef calculate_mape(actual, predicted) -> float: # Convert actual and predicted # to numpy array data type if not already if not all([isinstance(actual, np.ndarray), isinstance(predicted, np.ndarray)]): actual, predicted = np.array(actual), np.array(predicted) # Calculate the MAPE value and return return round(np.mean(np.abs(( actual - predicted) / actual)) * 100, 2) if __name__ == '__main__': # CALCULATE MAPE FROM PYTHON LIST actual = [136, 120, 138, 155, 149] predicted = [134, 124, 132, 141, 149] # Get MAPE for python list as parameters print(\"py list :\", calculate_mape(actual, predicted), \"%\") # CALCULATE MAPE FROM NUMPY ARRAY actual = np.array([136, 120, 138, 155, 149]) predicted = np.array([134, 124, 132, 141, 149]) # Get MAPE for python list as parameters print(\"np array :\", calculate_mape(actual, predicted), \"%\") # CALCULATE MAPE FROM PANDAS DATAFRAME # Define the pandas dataframe sales_df = pd.DataFrame({ \"actual\" : [136, 120, 138, 155, 149], \"predicted\" : [134, 124, 132, 141, 149] }) # Get MAPE for pandas series as parameters print(\"pandas df:\", calculate_mape(sales_df.actual, sales_df.predicted), \"%\")",
"e": 4401,
"s": 2940,
"text": null
},
{
"code": null,
"e": 4409,
"s": 4401,
"text": "Output:"
},
{
"code": null,
"e": 4425,
"s": 4409,
"text": "MAPE Output – 2"
},
{
"code": null,
"e": 4701,
"s": 4425,
"text": "In the above program, we have depicted a single function `calculate_mape()` which does the MAPE calculation for a given python list, NumPy array, or pandas series. The output is the same as the same data is passed to all the 3 data type formats as parameters to the function."
},
{
"code": null,
"e": 4708,
"s": 4701,
"text": "Picked"
},
{
"code": null,
"e": 4721,
"s": 4708,
"text": "Python-numpy"
},
{
"code": null,
"e": 4735,
"s": 4721,
"text": "Python-pandas"
},
{
"code": null,
"e": 4742,
"s": 4735,
"text": "Python"
}
] |
How to Install Go on Windows? | 05 Oct, 2021
Before, we start with the process of Installing Golang on our System. We must have first-hand knowledge of What the Go Language is and what it actually does? Go is an open-source and statically typed programming language developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but launched in 2009. It is also known as the Golang and it supports the procedural programming language. It was initially developed to improve programming productivity of the large codebases, multicore, and networked machines.
Golang programs can be written on any plain text editor like notepad, notepad++ or anything of that sort. One can also use an online IDE for writing Golang codes or can even install one on their system to make it more feasible to write these codes. Using an IDE makes it easier to write Golang codes because IDEs provide a lot of features like intuitive code editor, debugger, compiler, etc.To begin with, writing Golang Codes and performing various intriguing and useful operations, one must have the Go language installed on their System. This can be done by following the step by step instructions provided below:
Before we begin with the installation of Go, it is good to check if it might be already installed on your System. To check if your device is preinstalled with Golang or not, just go to the Command line(For Windows, search for cmd in the Run dialog( + R).
Now run the following command:
go version
If Golang is already installed, it will generate a message with all the details of the Golang’s version available, otherwise, if Golang is not installed then an error will arise stating Bad command or file name
Before starting with the installation process, you need to download it. For that, all versions of Go for Windows are available on golang.org.
Download the Golang according to your system architecture and follow the further instructions for the installation of Golang.
Step 1: After downloading, unzip the downloaded archive file. After unzipping you will get a folder named go in the current directory.
Step 2: Now copy and paste the extracted folder wherever you want to install this. Here we are installing in C drive.
Step 3: Now set the environment variables. Right click on My PC and select Properties. Choose the Advanced System Settings from the left side and click on Environment Variables as shown in the below screenshots.
Step 4: Click on Path from the system variables and then click Edit. Then Click New and then add the Path with bin directory where you have pasted the Go folder. Here we are editing the path C:\go\bin and click Ok as shown in the below screenshots.
Step 5: Now create a new user variable which tells Go command where Golang libraries are present. For that click on New on User Variables as shown in the below screenshots.
Now fill the Variable name as GOROOT and Variable value is the path of your Golang folder. So here Variable Value is C:\go\. After Filling click OK.
After that Click Ok on Environment Variables and your setup is completed. Now Let’s check the Golang version by using the command go version on command prompt.
After completing the installation process, any IDE or text editor can be used to write Golang Codes and Run them on the IDE or the Command prompt with the use of command:
go run filename.go
Go-Basics
Golang
how-to-install
Go Language
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to concatenate two strings in Golang
time.Sleep() Function in Golang With Examples
strings.Replace() Function in Golang With Examples
strings.Contains Function in Golang with Examples
fmt.Sprintf() Function in Golang With Examples
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
How to filter object array based on attributes? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 577,
"s": 52,
"text": "Before, we start with the process of Installing Golang on our System. We must have first-hand knowledge of What the Go Language is and what it actually does? Go is an open-source and statically typed programming language developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but launched in 2009. It is also known as the Golang and it supports the procedural programming language. It was initially developed to improve programming productivity of the large codebases, multicore, and networked machines."
},
{
"code": null,
"e": 1194,
"s": 577,
"text": "Golang programs can be written on any plain text editor like notepad, notepad++ or anything of that sort. One can also use an online IDE for writing Golang codes or can even install one on their system to make it more feasible to write these codes. Using an IDE makes it easier to write Golang codes because IDEs provide a lot of features like intuitive code editor, debugger, compiler, etc.To begin with, writing Golang Codes and performing various intriguing and useful operations, one must have the Go language installed on their System. This can be done by following the step by step instructions provided below:"
},
{
"code": null,
"e": 1449,
"s": 1194,
"text": "Before we begin with the installation of Go, it is good to check if it might be already installed on your System. To check if your device is preinstalled with Golang or not, just go to the Command line(For Windows, search for cmd in the Run dialog( + R)."
},
{
"code": null,
"e": 1480,
"s": 1449,
"text": "Now run the following command:"
},
{
"code": null,
"e": 1491,
"s": 1480,
"text": "go version"
},
{
"code": null,
"e": 1702,
"s": 1491,
"text": "If Golang is already installed, it will generate a message with all the details of the Golang’s version available, otherwise, if Golang is not installed then an error will arise stating Bad command or file name"
},
{
"code": null,
"e": 1844,
"s": 1702,
"text": "Before starting with the installation process, you need to download it. For that, all versions of Go for Windows are available on golang.org."
},
{
"code": null,
"e": 1970,
"s": 1844,
"text": "Download the Golang according to your system architecture and follow the further instructions for the installation of Golang."
},
{
"code": null,
"e": 2105,
"s": 1970,
"text": "Step 1: After downloading, unzip the downloaded archive file. After unzipping you will get a folder named go in the current directory."
},
{
"code": null,
"e": 2223,
"s": 2105,
"text": "Step 2: Now copy and paste the extracted folder wherever you want to install this. Here we are installing in C drive."
},
{
"code": null,
"e": 2435,
"s": 2223,
"text": "Step 3: Now set the environment variables. Right click on My PC and select Properties. Choose the Advanced System Settings from the left side and click on Environment Variables as shown in the below screenshots."
},
{
"code": null,
"e": 2684,
"s": 2435,
"text": "Step 4: Click on Path from the system variables and then click Edit. Then Click New and then add the Path with bin directory where you have pasted the Go folder. Here we are editing the path C:\\go\\bin and click Ok as shown in the below screenshots."
},
{
"code": null,
"e": 2857,
"s": 2684,
"text": "Step 5: Now create a new user variable which tells Go command where Golang libraries are present. For that click on New on User Variables as shown in the below screenshots."
},
{
"code": null,
"e": 3006,
"s": 2857,
"text": "Now fill the Variable name as GOROOT and Variable value is the path of your Golang folder. So here Variable Value is C:\\go\\. After Filling click OK."
},
{
"code": null,
"e": 3166,
"s": 3006,
"text": "After that Click Ok on Environment Variables and your setup is completed. Now Let’s check the Golang version by using the command go version on command prompt."
},
{
"code": null,
"e": 3337,
"s": 3166,
"text": "After completing the installation process, any IDE or text editor can be used to write Golang Codes and Run them on the IDE or the Command prompt with the use of command:"
},
{
"code": null,
"e": 3356,
"s": 3337,
"text": "go run filename.go"
},
{
"code": null,
"e": 3366,
"s": 3356,
"text": "Go-Basics"
},
{
"code": null,
"e": 3373,
"s": 3366,
"text": "Golang"
},
{
"code": null,
"e": 3388,
"s": 3373,
"text": "how-to-install"
},
{
"code": null,
"e": 3400,
"s": 3388,
"text": "Go Language"
},
{
"code": null,
"e": 3407,
"s": 3400,
"text": "How To"
},
{
"code": null,
"e": 3426,
"s": 3407,
"text": "Installation Guide"
},
{
"code": null,
"e": 3524,
"s": 3426,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3576,
"s": 3524,
"text": "Different ways to concatenate two strings in Golang"
},
{
"code": null,
"e": 3622,
"s": 3576,
"text": "time.Sleep() Function in Golang With Examples"
},
{
"code": null,
"e": 3673,
"s": 3622,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 3723,
"s": 3673,
"text": "strings.Contains Function in Golang with Examples"
},
{
"code": null,
"e": 3770,
"s": 3723,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 3802,
"s": 3770,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3855,
"s": 3802,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 3899,
"s": 3855,
"text": "How to install Jupyter Notebook on Windows?"
}
] |
Ruby | String chars() Method | 17 Dec, 2019
chars is a String class method in Ruby which is used to return an array of characters in str.
Syntax: str.chars
Parameters: Here, str is the given string
Returns: An array of the characters.
Example 1:
# Ruby program to demonstrate # the chars method # Taking a string and # using the method puts "Ruby String".chars() puts "Methods".chars()
Output:
R
u
b
y
S
t
r
i
n
g
M
e
t
h
o
d
s
Example 2:
# Ruby program to demonstrate # the chars method # Taking a string and # using the method puts "GFG".chars() puts "G4G".chars()
Output:
G
F
G
G
4
G
Ruby String-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Dec, 2019"
},
{
"code": null,
"e": 122,
"s": 28,
"text": "chars is a String class method in Ruby which is used to return an array of characters in str."
},
{
"code": null,
"e": 140,
"s": 122,
"text": "Syntax: str.chars"
},
{
"code": null,
"e": 182,
"s": 140,
"text": "Parameters: Here, str is the given string"
},
{
"code": null,
"e": 219,
"s": 182,
"text": "Returns: An array of the characters."
},
{
"code": null,
"e": 230,
"s": 219,
"text": "Example 1:"
},
{
"code": "# Ruby program to demonstrate # the chars method # Taking a string and # using the method puts \"Ruby String\".chars() puts \"Methods\".chars() ",
"e": 378,
"s": 230,
"text": null
},
{
"code": null,
"e": 386,
"s": 378,
"text": "Output:"
},
{
"code": null,
"e": 423,
"s": 386,
"text": "R\nu\nb\ny\n \nS\nt\nr\ni\nn\ng\nM\ne\nt\nh\no\nd\ns\n"
},
{
"code": null,
"e": 434,
"s": 423,
"text": "Example 2:"
},
{
"code": "# Ruby program to demonstrate # the chars method # Taking a string and # using the method puts \"GFG\".chars() puts \"G4G\".chars() ",
"e": 570,
"s": 434,
"text": null
},
{
"code": null,
"e": 578,
"s": 570,
"text": "Output:"
},
{
"code": null,
"e": 591,
"s": 578,
"text": "G\nF\nG\nG\n4\nG\n"
},
{
"code": null,
"e": 609,
"s": 591,
"text": "Ruby String-class"
},
{
"code": null,
"e": 622,
"s": 609,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 627,
"s": 622,
"text": "Ruby"
}
] |
Input-output system calls in C | Create, Open, Close, Read, Write | 28 Oct, 2021
Important Terminology
What is the File Descriptor?File descriptor is integer that uniquely identifies an open file of the process.
File Descriptor table: File descriptor table is the collection of integer array indices that are file descriptors in which elements are pointers to file table entries. One unique file descriptors table is provided in operating system for each process.
File Table Entry: File table entries is a structure In-memory surrogate for an open file, which is created when process request to opens file and these entries maintains file position.
Standard File Descriptors: When any process starts, then that process file descriptors table’s fd(file descriptor) 0, 1, 2 open automatically, (By default) each of these 3 fd references file table entry for a file named /dev/tty
/dev/tty: In-memory surrogate for the terminalTerminal: Combination keyboard/video screen
Read from stdin => read from fd 0 : Whenever we write any character from keyboard, it read from stdin through fd 0 and save to file named /dev/tty.Write to stdout => write to fd 1 : Whenever we see any output to the video screen, it’s from the file named /dev/tty and written to stdout in screen through fd 1.Write to stderr => write to fd 2 : We see any error to the video screen, it is also from that file write to stderr in screen through fd 2.
I/O System calls
Basically there are total 5 types of I/O system calls:
1. Create: Used to Create a new empty file.
Syntax in C language:
int create(char *filename, mode_t mode)
Parameter:
filename : name of the file which you want to create
mode : indicates permissions of new file.
Returns:
return first unused file descriptor (generally 3 when first create use in process because 0, 1, 2 fd are reserved)
return -1 when error
How it work in OS
Create new empty file on disk
Create file table entry
Set first unused file descriptor to point to file table entry
Return file descriptor used, -1 upon failure
2. open: Used to Open the file for reading, writing or both.
Syntax in C language
#include<sys/types.h>
#include<sys/stat.h>
#include <fcntl.h>
int open (const char* Path, int flags [, int mode ]);
Parameters
Path: path to file which you want to use use absolute path begin with “/”, when you are not work in same directory of file.Use relative path which is only file name with extension, when you are work in same directory of file.
use absolute path begin with “/”, when you are not work in same directory of file.
Use relative path which is only file name with extension, when you are work in same directory of file.
flags : How you like to useO_RDONLY: read only, O_WRONLY: write only, O_RDWR: read and write, O_CREAT: create file if it doesn’t exist, O_EXCL: prevent creation if it already exists
O_RDONLY: read only, O_WRONLY: write only, O_RDWR: read and write, O_CREAT: create file if it doesn’t exist, O_EXCL: prevent creation if it already exists
How it works in OS
Find the existing file on disk
Create file table entry
Set first unused file descriptor to point to file table entry
Return file descriptor used, -1 upon failure
C
// C program to illustrate // open system call #include<stdio.h> #include<fcntl.h> #include<errno.h> extern int errno; int main() { // if file does not have in directory // then file foo.txt is created. int fd = open("foo.txt", O_RDONLY | O_CREAT); printf("fd = %d/n", fd); if (fd ==-1) { // print which type of error have in a code printf("Error Number % d\n", errno); // print program detail "Success or failure" perror("Program"); } return 0; }
Output:
fd = 3
3. close: Tells the operating system you are done with a file descriptor and Close the file which pointed by fd.
Syntax in C language
#include <fcntl.h>
int close(int fd);
Parameter:
fd :file descriptor
Return:
0 on success.
-1 on error.
How it works in the OS
Destroy file table entry referenced by element fd of file descriptor table– As long as no other process is pointing to it!
Set element fd of file descriptor table to NULL
C
// C program to illustrate close system Call #include<stdio.h> #include <fcntl.h> int main() { int fd1 = open("foo.txt", O_RDONLY); if (fd1 < 0) { perror("c1"); exit(1); } printf("opened the fd = % d\n", fd1); // Using close system Call if (close(fd1) < 0) { perror("c1"); exit(1); } printf("closed the fd.\n"); }
Output:
opened the fd = 3
closed the fd.
C
// C program to illustrate close system Call #include<stdio.h> #include<fcntl.h> int main() { // assume that foo.txt is already created int fd1 = open("foo.txt", O_RDONLY, 0); close(fd1); // assume that baz.tzt is already created int fd2 = open("baz.txt", O_RDONLY, 0); printf("fd2 = % d\n", fd2); exit(0); }
Output:
fd2 = 3
Here, In this code first open() returns 3 because when main process created, then fd 0, 1, 2 are already taken by stdin, stdout and stderr. So first unused file descriptor is 3 in file descriptor table. After that in close() system call is free it this 3 file descriptor and then after set 3 file descriptor as null. So when we called second open(), then first unused fd is also 3. So, output of this program is 3.
4. read: From the file indicated by the file descriptor fd, the read() function reads cnt bytes of input into the memory area indicated by buf. A successful read() updates the access time for the file.
Syntax in C language
size_t read (int fd, void* buf, size_t cnt);
Parameters:
fd: file descriptor
buf: buffer to read data from
cnt: length of buffer
Returns: How many bytes were actually read
return Number of bytes read on success
return 0 on reaching end of file
return -1 on error
return -1 on signal interrupt
Important points
buf needs to point to a valid memory location with length not smaller than the specified size because of overflow.
fd should be a valid file descriptor returned from open() to perform read operation because if fd is NULL then read should generate error.
cnt is the requested number of bytes read, while the return value is the actual number of bytes read. Also, some times read system call should read less bytes than cnt.
C
// C program to illustrate // read system Call #include<stdio.h> #include <fcntl.h> int main() { int fd, sz; char *c = (char *) calloc(100, sizeof(char)); fd = open("foo.txt", O_RDONLY); if (fd < 0) { perror("r1"); exit(1); } sz = read(fd, c, 10); printf("called read(% d, c, 10). returned that" " %d bytes were read.\n", fd, sz); c[sz] = '\0'; printf("Those bytes are as follows: % s\n", c); }
Output:
called read(3, c, 10). returned that 10 bytes were read.
Those bytes are as follows: 0 0 0 foo.
Suppose that foobar.txt consists of the 6 ASCII characters “foobar”. Then what is the output of the following program?
C
// C program to illustrate // read system Call #include<stdio.h> #include<unistd.h> #include<fcntl.h> #include<stdlib.h> int main() { char c; int fd1 = open("sample.txt", O_RDONLY, 0); int fd2 = open("sample.txt", O_RDONLY, 0); read(fd1, &c, 1); read(fd2, &c, 1); printf("c = %c\n", c); exit(0); }
Output:
c = f
The descriptors fd1 and fd2 each have their own open file table entry, so each descriptor has its own file position for foobar.txt. Thus, the read from fd2 reads the first byte of foobar.txt, and the output is c = f, not c = o.
5. write: Writes cnt bytes from buf to the file or socket associated with fd. cnt should not be greater than INT_MAX (defined in the limits.h header file). If cnt is zero, write() simply returns 0 without attempting any other action.
#include <fcntl.h>
size_t write (int fd, void* buf, size_t cnt);
Parameters:
fd: file descriptor
buf: buffer to write data to
cnt: length of buffer
Returns: How many bytes were actually written
return Number of bytes written on success
return 0 on reaching end of file
return -1 on error
return -1 on signal interrupt
Important points
The file needs to be opened for write operations
buf needs to be at least as long as specified by cnt because if buf size less than the cnt then buf will lead to the overflow condition.
cnt is the requested number of bytes to write, while the return value is the actual number of bytes written. This happens when fd have a less number of bytes to write than cnt.
If write() is interrupted by a signal, the effect is one of the following:-If write() has not written any data yet, it returns -1 and sets errno to EINTR.-If write() has successfully written some data, it returns the number of bytes it wrote before it was interrupted.
C
// C program to illustrate // write system Call #include<stdio.h> #include <fcntl.h> main() { int sz; int fd = open("foo.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644); if (fd < 0) { perror("r1"); exit(1); } sz = write(fd, "hello geeks\n", strlen("hello geeks\n")); printf("called write(% d, \"hello geeks\\n\", %d)." " It returned %d\n", fd, strlen("hello geeks\n"), sz); close(fd); }
Output:
called write(3, "hello geeks\n", 12). it returned 11
Here, when you see in the file foo.txt after running the code, you get a “hello geeks“. If foo.txt file already have some content in it then write system call overwrite the content and all previous content are deleted and only “hello geeks” content will have in the file.
Print “hello world” from the program without use any printf or cout function.
C
// C program to illustrate // I/O system Calls #include<stdio.h> #include<string.h> #include<unistd.h> #include<fcntl.h> int main (void) { int fd[2]; char buf1[12] = "hello world"; char buf2[12]; // assume foobar.txt is already created fd[0] = open("foobar.txt", O_RDWR); fd[1] = open("foobar.txt", O_RDWR); write(fd[0], buf1, strlen(buf1)); write(1, buf2, read(fd[1], buf2, 12)); close(fd[0]); close(fd[1]); return 0; }
Output:
hello world
In this code, buf1 array’s string “hello world” is first write in to stdin fd[0] then after that this string write into stdin to buf2 array. After that write into buf2 array to the stdout and print output “hello world“.This article is contributed by Kadam Patel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ritwikshanker
srinam
gabaa406
anikaseth98
ruhelaa48
vivekjoshi556
avtarkumar719
system-programming
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
What is the purpose of a function prototype?
Enumeration (or enum) in C
C Language Introduction
Operators in C / C++
Power Function in C/C++ | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Oct, 2021"
},
{
"code": null,
"e": 76,
"s": 54,
"text": "Important Terminology"
},
{
"code": null,
"e": 185,
"s": 76,
"text": "What is the File Descriptor?File descriptor is integer that uniquely identifies an open file of the process."
},
{
"code": null,
"e": 437,
"s": 185,
"text": "File Descriptor table: File descriptor table is the collection of integer array indices that are file descriptors in which elements are pointers to file table entries. One unique file descriptors table is provided in operating system for each process."
},
{
"code": null,
"e": 622,
"s": 437,
"text": "File Table Entry: File table entries is a structure In-memory surrogate for an open file, which is created when process request to opens file and these entries maintains file position."
},
{
"code": null,
"e": 851,
"s": 622,
"text": "Standard File Descriptors: When any process starts, then that process file descriptors table’s fd(file descriptor) 0, 1, 2 open automatically, (By default) each of these 3 fd references file table entry for a file named /dev/tty"
},
{
"code": null,
"e": 942,
"s": 851,
"text": "/dev/tty: In-memory surrogate for the terminalTerminal: Combination keyboard/video screen "
},
{
"code": null,
"e": 1390,
"s": 942,
"text": "Read from stdin => read from fd 0 : Whenever we write any character from keyboard, it read from stdin through fd 0 and save to file named /dev/tty.Write to stdout => write to fd 1 : Whenever we see any output to the video screen, it’s from the file named /dev/tty and written to stdout in screen through fd 1.Write to stderr => write to fd 2 : We see any error to the video screen, it is also from that file write to stderr in screen through fd 2."
},
{
"code": null,
"e": 1407,
"s": 1390,
"text": "I/O System calls"
},
{
"code": null,
"e": 1462,
"s": 1407,
"text": "Basically there are total 5 types of I/O system calls:"
},
{
"code": null,
"e": 1506,
"s": 1462,
"text": "1. Create: Used to Create a new empty file."
},
{
"code": null,
"e": 1569,
"s": 1506,
"text": "Syntax in C language: \nint create(char *filename, mode_t mode)"
},
{
"code": null,
"e": 1580,
"s": 1569,
"text": "Parameter:"
},
{
"code": null,
"e": 1633,
"s": 1580,
"text": "filename : name of the file which you want to create"
},
{
"code": null,
"e": 1675,
"s": 1633,
"text": "mode : indicates permissions of new file."
},
{
"code": null,
"e": 1684,
"s": 1675,
"text": "Returns:"
},
{
"code": null,
"e": 1799,
"s": 1684,
"text": "return first unused file descriptor (generally 3 when first create use in process because 0, 1, 2 fd are reserved)"
},
{
"code": null,
"e": 1820,
"s": 1799,
"text": "return -1 when error"
},
{
"code": null,
"e": 1838,
"s": 1820,
"text": "How it work in OS"
},
{
"code": null,
"e": 1868,
"s": 1838,
"text": "Create new empty file on disk"
},
{
"code": null,
"e": 1892,
"s": 1868,
"text": "Create file table entry"
},
{
"code": null,
"e": 1954,
"s": 1892,
"text": "Set first unused file descriptor to point to file table entry"
},
{
"code": null,
"e": 1999,
"s": 1954,
"text": "Return file descriptor used, -1 upon failure"
},
{
"code": null,
"e": 2060,
"s": 1999,
"text": "2. open: Used to Open the file for reading, writing or both."
},
{
"code": null,
"e": 2201,
"s": 2060,
"text": "Syntax in C language \n#include<sys/types.h>\n#include<sys/stat.h>\n#include <fcntl.h> \nint open (const char* Path, int flags [, int mode ]); "
},
{
"code": null,
"e": 2212,
"s": 2201,
"text": "Parameters"
},
{
"code": null,
"e": 2438,
"s": 2212,
"text": "Path: path to file which you want to use use absolute path begin with “/”, when you are not work in same directory of file.Use relative path which is only file name with extension, when you are work in same directory of file."
},
{
"code": null,
"e": 2521,
"s": 2438,
"text": "use absolute path begin with “/”, when you are not work in same directory of file."
},
{
"code": null,
"e": 2624,
"s": 2521,
"text": "Use relative path which is only file name with extension, when you are work in same directory of file."
},
{
"code": null,
"e": 2806,
"s": 2624,
"text": "flags : How you like to useO_RDONLY: read only, O_WRONLY: write only, O_RDWR: read and write, O_CREAT: create file if it doesn’t exist, O_EXCL: prevent creation if it already exists"
},
{
"code": null,
"e": 2961,
"s": 2806,
"text": "O_RDONLY: read only, O_WRONLY: write only, O_RDWR: read and write, O_CREAT: create file if it doesn’t exist, O_EXCL: prevent creation if it already exists"
},
{
"code": null,
"e": 2980,
"s": 2961,
"text": "How it works in OS"
},
{
"code": null,
"e": 3011,
"s": 2980,
"text": "Find the existing file on disk"
},
{
"code": null,
"e": 3035,
"s": 3011,
"text": "Create file table entry"
},
{
"code": null,
"e": 3097,
"s": 3035,
"text": "Set first unused file descriptor to point to file table entry"
},
{
"code": null,
"e": 3142,
"s": 3097,
"text": "Return file descriptor used, -1 upon failure"
},
{
"code": null,
"e": 3144,
"s": 3142,
"text": "C"
},
{
"code": "// C program to illustrate // open system call #include<stdio.h> #include<fcntl.h> #include<errno.h> extern int errno; int main() { // if file does not have in directory // then file foo.txt is created. int fd = open(\"foo.txt\", O_RDONLY | O_CREAT); printf(\"fd = %d/n\", fd); if (fd ==-1) { // print which type of error have in a code printf(\"Error Number % d\\n\", errno); // print program detail \"Success or failure\" perror(\"Program\"); } return 0; } ",
"e": 3699,
"s": 3144,
"text": null
},
{
"code": null,
"e": 3707,
"s": 3699,
"text": "Output:"
},
{
"code": null,
"e": 3714,
"s": 3707,
"text": "fd = 3"
},
{
"code": null,
"e": 3828,
"s": 3714,
"text": "3. close: Tells the operating system you are done with a file descriptor and Close the file which pointed by fd. "
},
{
"code": null,
"e": 3888,
"s": 3828,
"text": "Syntax in C language\n#include <fcntl.h>\nint close(int fd); "
},
{
"code": null,
"e": 3899,
"s": 3888,
"text": "Parameter:"
},
{
"code": null,
"e": 3919,
"s": 3899,
"text": "fd :file descriptor"
},
{
"code": null,
"e": 3927,
"s": 3919,
"text": "Return:"
},
{
"code": null,
"e": 3941,
"s": 3927,
"text": "0 on success."
},
{
"code": null,
"e": 3954,
"s": 3941,
"text": "-1 on error."
},
{
"code": null,
"e": 3977,
"s": 3954,
"text": "How it works in the OS"
},
{
"code": null,
"e": 4100,
"s": 3977,
"text": "Destroy file table entry referenced by element fd of file descriptor table– As long as no other process is pointing to it!"
},
{
"code": null,
"e": 4148,
"s": 4100,
"text": "Set element fd of file descriptor table to NULL"
},
{
"code": null,
"e": 4150,
"s": 4148,
"text": "C"
},
{
"code": "// C program to illustrate close system Call #include<stdio.h> #include <fcntl.h> int main() { int fd1 = open(\"foo.txt\", O_RDONLY); if (fd1 < 0) { perror(\"c1\"); exit(1); } printf(\"opened the fd = % d\\n\", fd1); // Using close system Call if (close(fd1) < 0) { perror(\"c1\"); exit(1); } printf(\"closed the fd.\\n\"); } ",
"e": 4543,
"s": 4150,
"text": null
},
{
"code": null,
"e": 4551,
"s": 4543,
"text": "Output:"
},
{
"code": null,
"e": 4584,
"s": 4551,
"text": "opened the fd = 3\nclosed the fd."
},
{
"code": null,
"e": 4586,
"s": 4584,
"text": "C"
},
{
"code": "// C program to illustrate close system Call #include<stdio.h> #include<fcntl.h> int main() { // assume that foo.txt is already created int fd1 = open(\"foo.txt\", O_RDONLY, 0); close(fd1); // assume that baz.tzt is already created int fd2 = open(\"baz.txt\", O_RDONLY, 0); printf(\"fd2 = % d\\n\", fd2); exit(0); } ",
"e": 4936,
"s": 4586,
"text": null
},
{
"code": null,
"e": 4944,
"s": 4936,
"text": "Output:"
},
{
"code": null,
"e": 4952,
"s": 4944,
"text": "fd2 = 3"
},
{
"code": null,
"e": 5367,
"s": 4952,
"text": "Here, In this code first open() returns 3 because when main process created, then fd 0, 1, 2 are already taken by stdin, stdout and stderr. So first unused file descriptor is 3 in file descriptor table. After that in close() system call is free it this 3 file descriptor and then after set 3 file descriptor as null. So when we called second open(), then first unused fd is also 3. So, output of this program is 3."
},
{
"code": null,
"e": 5569,
"s": 5367,
"text": "4. read: From the file indicated by the file descriptor fd, the read() function reads cnt bytes of input into the memory area indicated by buf. A successful read() updates the access time for the file."
},
{
"code": null,
"e": 5638,
"s": 5569,
"text": "Syntax in C language \nsize_t read (int fd, void* buf, size_t cnt); "
},
{
"code": null,
"e": 5650,
"s": 5638,
"text": "Parameters:"
},
{
"code": null,
"e": 5670,
"s": 5650,
"text": "fd: file descriptor"
},
{
"code": null,
"e": 5700,
"s": 5670,
"text": "buf: buffer to read data from"
},
{
"code": null,
"e": 5722,
"s": 5700,
"text": "cnt: length of buffer"
},
{
"code": null,
"e": 5765,
"s": 5722,
"text": "Returns: How many bytes were actually read"
},
{
"code": null,
"e": 5804,
"s": 5765,
"text": "return Number of bytes read on success"
},
{
"code": null,
"e": 5837,
"s": 5804,
"text": "return 0 on reaching end of file"
},
{
"code": null,
"e": 5856,
"s": 5837,
"text": "return -1 on error"
},
{
"code": null,
"e": 5886,
"s": 5856,
"text": "return -1 on signal interrupt"
},
{
"code": null,
"e": 5903,
"s": 5886,
"text": "Important points"
},
{
"code": null,
"e": 6018,
"s": 5903,
"text": "buf needs to point to a valid memory location with length not smaller than the specified size because of overflow."
},
{
"code": null,
"e": 6157,
"s": 6018,
"text": "fd should be a valid file descriptor returned from open() to perform read operation because if fd is NULL then read should generate error."
},
{
"code": null,
"e": 6326,
"s": 6157,
"text": "cnt is the requested number of bytes read, while the return value is the actual number of bytes read. Also, some times read system call should read less bytes than cnt."
},
{
"code": null,
"e": 6328,
"s": 6326,
"text": "C"
},
{
"code": "// C program to illustrate // read system Call #include<stdio.h> #include <fcntl.h> int main() { int fd, sz; char *c = (char *) calloc(100, sizeof(char)); fd = open(\"foo.txt\", O_RDONLY); if (fd < 0) { perror(\"r1\"); exit(1); } sz = read(fd, c, 10); printf(\"called read(% d, c, 10). returned that\" \" %d bytes were read.\\n\", fd, sz); c[sz] = '\\0'; printf(\"Those bytes are as follows: % s\\n\", c); } ",
"e": 6735,
"s": 6328,
"text": null
},
{
"code": null,
"e": 6743,
"s": 6735,
"text": "Output:"
},
{
"code": null,
"e": 6841,
"s": 6743,
"text": "called read(3, c, 10). returned that 10 bytes were read.\nThose bytes are as follows: 0 0 0 foo."
},
{
"code": null,
"e": 6960,
"s": 6841,
"text": "Suppose that foobar.txt consists of the 6 ASCII characters “foobar”. Then what is the output of the following program?"
},
{
"code": null,
"e": 6962,
"s": 6960,
"text": "C"
},
{
"code": "// C program to illustrate // read system Call #include<stdio.h> #include<unistd.h> #include<fcntl.h> #include<stdlib.h> int main() { char c; int fd1 = open(\"sample.txt\", O_RDONLY, 0); int fd2 = open(\"sample.txt\", O_RDONLY, 0); read(fd1, &c, 1); read(fd2, &c, 1); printf(\"c = %c\\n\", c); exit(0); } ",
"e": 7291,
"s": 6962,
"text": null
},
{
"code": null,
"e": 7299,
"s": 7291,
"text": "Output:"
},
{
"code": null,
"e": 7305,
"s": 7299,
"text": "c = f"
},
{
"code": null,
"e": 7533,
"s": 7305,
"text": "The descriptors fd1 and fd2 each have their own open file table entry, so each descriptor has its own file position for foobar.txt. Thus, the read from fd2 reads the first byte of foobar.txt, and the output is c = f, not c = o."
},
{
"code": null,
"e": 7767,
"s": 7533,
"text": "5. write: Writes cnt bytes from buf to the file or socket associated with fd. cnt should not be greater than INT_MAX (defined in the limits.h header file). If cnt is zero, write() simply returns 0 without attempting any other action."
},
{
"code": null,
"e": 7833,
"s": 7767,
"text": "#include <fcntl.h>\nsize_t write (int fd, void* buf, size_t cnt); "
},
{
"code": null,
"e": 7845,
"s": 7833,
"text": "Parameters:"
},
{
"code": null,
"e": 7865,
"s": 7845,
"text": "fd: file descriptor"
},
{
"code": null,
"e": 7894,
"s": 7865,
"text": "buf: buffer to write data to"
},
{
"code": null,
"e": 7916,
"s": 7894,
"text": "cnt: length of buffer"
},
{
"code": null,
"e": 7962,
"s": 7916,
"text": "Returns: How many bytes were actually written"
},
{
"code": null,
"e": 8004,
"s": 7962,
"text": "return Number of bytes written on success"
},
{
"code": null,
"e": 8037,
"s": 8004,
"text": "return 0 on reaching end of file"
},
{
"code": null,
"e": 8056,
"s": 8037,
"text": "return -1 on error"
},
{
"code": null,
"e": 8086,
"s": 8056,
"text": "return -1 on signal interrupt"
},
{
"code": null,
"e": 8103,
"s": 8086,
"text": "Important points"
},
{
"code": null,
"e": 8152,
"s": 8103,
"text": "The file needs to be opened for write operations"
},
{
"code": null,
"e": 8289,
"s": 8152,
"text": "buf needs to be at least as long as specified by cnt because if buf size less than the cnt then buf will lead to the overflow condition."
},
{
"code": null,
"e": 8466,
"s": 8289,
"text": "cnt is the requested number of bytes to write, while the return value is the actual number of bytes written. This happens when fd have a less number of bytes to write than cnt."
},
{
"code": null,
"e": 8735,
"s": 8466,
"text": "If write() is interrupted by a signal, the effect is one of the following:-If write() has not written any data yet, it returns -1 and sets errno to EINTR.-If write() has successfully written some data, it returns the number of bytes it wrote before it was interrupted."
},
{
"code": null,
"e": 8737,
"s": 8735,
"text": "C"
},
{
"code": "// C program to illustrate // write system Call #include<stdio.h> #include <fcntl.h> main() { int sz; int fd = open(\"foo.txt\", O_WRONLY | O_CREAT | O_TRUNC, 0644); if (fd < 0) { perror(\"r1\"); exit(1); } sz = write(fd, \"hello geeks\\n\", strlen(\"hello geeks\\n\")); printf(\"called write(% d, \\\"hello geeks\\\\n\\\", %d).\" \" It returned %d\\n\", fd, strlen(\"hello geeks\\n\"), sz); close(fd); } ",
"e": 9138,
"s": 8737,
"text": null
},
{
"code": null,
"e": 9146,
"s": 9138,
"text": "Output:"
},
{
"code": null,
"e": 9200,
"s": 9146,
"text": "called write(3, \"hello geeks\\n\", 12). it returned 11"
},
{
"code": null,
"e": 9472,
"s": 9200,
"text": "Here, when you see in the file foo.txt after running the code, you get a “hello geeks“. If foo.txt file already have some content in it then write system call overwrite the content and all previous content are deleted and only “hello geeks” content will have in the file."
},
{
"code": null,
"e": 9550,
"s": 9472,
"text": "Print “hello world” from the program without use any printf or cout function."
},
{
"code": null,
"e": 9552,
"s": 9550,
"text": "C"
},
{
"code": "// C program to illustrate // I/O system Calls #include<stdio.h> #include<string.h> #include<unistd.h> #include<fcntl.h> int main (void) { int fd[2]; char buf1[12] = \"hello world\"; char buf2[12]; // assume foobar.txt is already created fd[0] = open(\"foobar.txt\", O_RDWR); fd[1] = open(\"foobar.txt\", O_RDWR); write(fd[0], buf1, strlen(buf1)); write(1, buf2, read(fd[1], buf2, 12)); close(fd[0]); close(fd[1]); return 0; } ",
"e": 10048,
"s": 9552,
"text": null
},
{
"code": null,
"e": 10056,
"s": 10048,
"text": "Output:"
},
{
"code": null,
"e": 10068,
"s": 10056,
"text": "hello world"
},
{
"code": null,
"e": 10707,
"s": 10068,
"text": "In this code, buf1 array’s string “hello world” is first write in to stdin fd[0] then after that this string write into stdin to buf2 array. After that write into buf2 array to the stdout and print output “hello world“.This article is contributed by Kadam Patel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 10721,
"s": 10707,
"text": "ritwikshanker"
},
{
"code": null,
"e": 10728,
"s": 10721,
"text": "srinam"
},
{
"code": null,
"e": 10737,
"s": 10728,
"text": "gabaa406"
},
{
"code": null,
"e": 10749,
"s": 10737,
"text": "anikaseth98"
},
{
"code": null,
"e": 10759,
"s": 10749,
"text": "ruhelaa48"
},
{
"code": null,
"e": 10773,
"s": 10759,
"text": "vivekjoshi556"
},
{
"code": null,
"e": 10787,
"s": 10773,
"text": "avtarkumar719"
},
{
"code": null,
"e": 10806,
"s": 10787,
"text": "system-programming"
},
{
"code": null,
"e": 10817,
"s": 10806,
"text": "C Language"
},
{
"code": null,
"e": 10915,
"s": 10817,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10932,
"s": 10915,
"text": "Substring in C++"
},
{
"code": null,
"e": 10954,
"s": 10932,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 10999,
"s": 10954,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 11024,
"s": 10999,
"text": "std::string class in C++"
},
{
"code": null,
"e": 11072,
"s": 11024,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 11117,
"s": 11072,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 11144,
"s": 11117,
"text": "Enumeration (or enum) in C"
},
{
"code": null,
"e": 11168,
"s": 11144,
"text": "C Language Introduction"
},
{
"code": null,
"e": 11189,
"s": 11168,
"text": "Operators in C / C++"
}
] |
An Introduction to Time Series Analysis with ARIMA | by Taha Binhuraib | Towards Data Science | Time series forecasting focuses on analyzing data changes across equally spaced time intervals. Time series analysis is used in a wide variety of domains, ranging from econometrics to geology and earthquake prediction; it’s also used in almost all applied sciences and engineering. Examples of time series data include S&P 500 Index, disease rates, mortality rates, blood pressure tracking, global temperatures. This post will be looking at how the autoregressive integrated moving average(ARIMA) models work and are fitted to time series data. The first point to consider before moving forward is the difference between Multi and Univariate forecasting. The former uses only the previous values in time to forecast future values. The latter makes use of different predictors other than the series itself. Please refer to my GitHub repo for the Jupyter notebooks and relevant data.
White noise, by definition, is random data. A time series is white noise(random) if the variables are independent and identically distributed(i.i.d) with a mean of zero. In other words, the time series has a mean μ = 0 and a constant standard deviation σ = c. You can use the df.describe() function to check your mean:
Since our mean is well above zero, we can rest assured that our data is not white noise. Even though we do not need to do the following, let’s just divide our data into 2 parts and take a look at their respective standard deviations:
df_1 = df[:100]df_2 = df[100:]print(df_1.describe())print(df_2.describe())
Here we can clearly see that our σ1 ≠σ2. The next image will illustrate an example of white noise. As seen below, the signal oscillates around a mean of zero, and it is not that hard to notice that the standard deviation is constant across time.
White noisey = noise(t) = εt
Since the definition of white noise implies randomness, you cannot model it and make predictions. Once you see white noise, do not continue with any predictive model!
Arima is short for Auto-Regressive Integrated Moving Average, which is a forecasting algorithm based on the assumption that previous values carry inherent information and can be used to predict future values. We can develop a predictive model to predict xt given past values., formally denoted as the following:p(xt | xt−1, ... ,x1)
In order to understand ARIMA, we first have to separate it into its foundational constituents:
ARIMA
AR
I
MA
The ARIMA model takes in three parameters:
p is the order of the AR termq is the order of the MA termd is the number of differencing
p is the order of the AR term
q is the order of the MA term
d is the number of differencing
The AR model only depends on past values (lags) to estimate future values. Let’s take a look at the generalized form of the AR model:
The value “p” determines the number of past values p will be taken into account for the prediction. The higher the order of the model, the more past values will be taken into account. For the sake of simplicity, let’s look at an AR(1) model.
The AR model can simply be thought of as the linear combination of p past values.
The moving-average MA model, on the other hand, depends on past forecast errors to make predictions. Let’s look at the generalized form of the MA model:
The MA model can simply be thought of as the linear combination of q past forecast errors.
Now before going any further, we have to discuss the difference between stationary and non-stationary data.
Stationary data is data in which the time series does not depend on the time variable; this assumption is needed in order to develop a predictive model that only depends on past values only. Not having stationary data would render your predictions unsatisfactory as your model would take the time variable into account. Intuitively, parameters such as the mean and variance do not change over time. The two graphs below illustrate the difference between stationary and non-stationary data:
As seen above, the non-stationary data has a clear upwards trend.
Now let’s look at a concrete example of non-stationary data and use Pandas’ diff() function to achieve stationarity:
#Calculates the difference of a Dataframe element compared with another element in the Dataframe (default is element in previous row = 1).df_1.diff(1).plot()
As seen above, we have achieved stationarity by taking the difference between successive rows.
If d=0: yt = Yt
If d=1: yt = Yt — Yt−1
If d=2: yt = (Yt — Yt-1) -(Yt-1 — Yt-2)
Now let’s consider ARIMA(1,1,1) for the time series x. For the sake of brevity, constant terms have been omitted.
yt = yt — y_t−1
yt = φ1yt−1 + εt — θ1 εt−1
We can simply use Auto.Arima and cross-validate in order to find the best parameters for the model. First, let’s load the data and plot it.
df = pd.read_csv('passengers.csv', usecols=[1], engine='python')plt.plot(df)
As seen above, the data has a clear upwards trend with seasonality. Now we shall simply make use of Auto.Arima to fit the data and make predictions
y = df.valuestrain, test = train_test_split(y, train_size=100)# Fit modelmodel = pm.auto_arima(train, seasonal=True, m=12)forecasts = model.predict(test.shape[0])x = np.arange(y.shape[0])plt.plot(x, y, c='blue' , label = 'expected')plt.plot(x[100:], forecasts, c='green' , label = 'predicted')plt.legend()plt.show()
Great fit on the test data!
Arima is a great tool for time series analysis, and Auto Arima packages make the process of fine-tuning a lot easierAlways plot your data and perform Explanatory Data analysis EDA in order to get a better understanding of the data.Learning the technicalities behind different prediction models can help you choose the correct one.
Arima is a great tool for time series analysis, and Auto Arima packages make the process of fine-tuning a lot easier
Always plot your data and perform Explanatory Data analysis EDA in order to get a better understanding of the data.
Learning the technicalities behind different prediction models can help you choose the correct one. | [
{
"code": null,
"e": 1054,
"s": 172,
"text": "Time series forecasting focuses on analyzing data changes across equally spaced time intervals. Time series analysis is used in a wide variety of domains, ranging from econometrics to geology and earthquake prediction; it’s also used in almost all applied sciences and engineering. Examples of time series data include S&P 500 Index, disease rates, mortality rates, blood pressure tracking, global temperatures. This post will be looking at how the autoregressive integrated moving average(ARIMA) models work and are fitted to time series data. The first point to consider before moving forward is the difference between Multi and Univariate forecasting. The former uses only the previous values in time to forecast future values. The latter makes use of different predictors other than the series itself. Please refer to my GitHub repo for the Jupyter notebooks and relevant data."
},
{
"code": null,
"e": 1373,
"s": 1054,
"text": "White noise, by definition, is random data. A time series is white noise(random) if the variables are independent and identically distributed(i.i.d) with a mean of zero. In other words, the time series has a mean μ = 0 and a constant standard deviation σ = c. You can use the df.describe() function to check your mean:"
},
{
"code": null,
"e": 1607,
"s": 1373,
"text": "Since our mean is well above zero, we can rest assured that our data is not white noise. Even though we do not need to do the following, let’s just divide our data into 2 parts and take a look at their respective standard deviations:"
},
{
"code": null,
"e": 1682,
"s": 1607,
"text": "df_1 = df[:100]df_2 = df[100:]print(df_1.describe())print(df_2.describe())"
},
{
"code": null,
"e": 1929,
"s": 1682,
"text": "Here we can clearly see that our σ1 ≠σ2. The next image will illustrate an example of white noise. As seen below, the signal oscillates around a mean of zero, and it is not that hard to notice that the standard deviation is constant across time."
},
{
"code": null,
"e": 1958,
"s": 1929,
"text": "White noisey = noise(t) = εt"
},
{
"code": null,
"e": 2125,
"s": 1958,
"text": "Since the definition of white noise implies randomness, you cannot model it and make predictions. Once you see white noise, do not continue with any predictive model!"
},
{
"code": null,
"e": 2458,
"s": 2125,
"text": "Arima is short for Auto-Regressive Integrated Moving Average, which is a forecasting algorithm based on the assumption that previous values carry inherent information and can be used to predict future values. We can develop a predictive model to predict xt given past values., formally denoted as the following:p(xt | xt−1, ... ,x1)"
},
{
"code": null,
"e": 2553,
"s": 2458,
"text": "In order to understand ARIMA, we first have to separate it into its foundational constituents:"
},
{
"code": null,
"e": 2559,
"s": 2553,
"text": "ARIMA"
},
{
"code": null,
"e": 2562,
"s": 2559,
"text": "AR"
},
{
"code": null,
"e": 2564,
"s": 2562,
"text": "I"
},
{
"code": null,
"e": 2567,
"s": 2564,
"text": "MA"
},
{
"code": null,
"e": 2610,
"s": 2567,
"text": "The ARIMA model takes in three parameters:"
},
{
"code": null,
"e": 2700,
"s": 2610,
"text": "p is the order of the AR termq is the order of the MA termd is the number of differencing"
},
{
"code": null,
"e": 2730,
"s": 2700,
"text": "p is the order of the AR term"
},
{
"code": null,
"e": 2760,
"s": 2730,
"text": "q is the order of the MA term"
},
{
"code": null,
"e": 2792,
"s": 2760,
"text": "d is the number of differencing"
},
{
"code": null,
"e": 2926,
"s": 2792,
"text": "The AR model only depends on past values (lags) to estimate future values. Let’s take a look at the generalized form of the AR model:"
},
{
"code": null,
"e": 3168,
"s": 2926,
"text": "The value “p” determines the number of past values p will be taken into account for the prediction. The higher the order of the model, the more past values will be taken into account. For the sake of simplicity, let’s look at an AR(1) model."
},
{
"code": null,
"e": 3250,
"s": 3168,
"text": "The AR model can simply be thought of as the linear combination of p past values."
},
{
"code": null,
"e": 3403,
"s": 3250,
"text": "The moving-average MA model, on the other hand, depends on past forecast errors to make predictions. Let’s look at the generalized form of the MA model:"
},
{
"code": null,
"e": 3494,
"s": 3403,
"text": "The MA model can simply be thought of as the linear combination of q past forecast errors."
},
{
"code": null,
"e": 3602,
"s": 3494,
"text": "Now before going any further, we have to discuss the difference between stationary and non-stationary data."
},
{
"code": null,
"e": 4092,
"s": 3602,
"text": "Stationary data is data in which the time series does not depend on the time variable; this assumption is needed in order to develop a predictive model that only depends on past values only. Not having stationary data would render your predictions unsatisfactory as your model would take the time variable into account. Intuitively, parameters such as the mean and variance do not change over time. The two graphs below illustrate the difference between stationary and non-stationary data:"
},
{
"code": null,
"e": 4158,
"s": 4092,
"text": "As seen above, the non-stationary data has a clear upwards trend."
},
{
"code": null,
"e": 4275,
"s": 4158,
"text": "Now let’s look at a concrete example of non-stationary data and use Pandas’ diff() function to achieve stationarity:"
},
{
"code": null,
"e": 4433,
"s": 4275,
"text": "#Calculates the difference of a Dataframe element compared with another element in the Dataframe (default is element in previous row = 1).df_1.diff(1).plot()"
},
{
"code": null,
"e": 4528,
"s": 4433,
"text": "As seen above, we have achieved stationarity by taking the difference between successive rows."
},
{
"code": null,
"e": 4544,
"s": 4528,
"text": "If d=0: yt = Yt"
},
{
"code": null,
"e": 4567,
"s": 4544,
"text": "If d=1: yt = Yt — Yt−1"
},
{
"code": null,
"e": 4607,
"s": 4567,
"text": "If d=2: yt = (Yt — Yt-1) -(Yt-1 — Yt-2)"
},
{
"code": null,
"e": 4721,
"s": 4607,
"text": "Now let’s consider ARIMA(1,1,1) for the time series x. For the sake of brevity, constant terms have been omitted."
},
{
"code": null,
"e": 4737,
"s": 4721,
"text": "yt = yt — y_t−1"
},
{
"code": null,
"e": 4764,
"s": 4737,
"text": "yt = φ1yt−1 + εt — θ1 εt−1"
},
{
"code": null,
"e": 4904,
"s": 4764,
"text": "We can simply use Auto.Arima and cross-validate in order to find the best parameters for the model. First, let’s load the data and plot it."
},
{
"code": null,
"e": 4981,
"s": 4904,
"text": "df = pd.read_csv('passengers.csv', usecols=[1], engine='python')plt.plot(df)"
},
{
"code": null,
"e": 5129,
"s": 4981,
"text": "As seen above, the data has a clear upwards trend with seasonality. Now we shall simply make use of Auto.Arima to fit the data and make predictions"
},
{
"code": null,
"e": 5445,
"s": 5129,
"text": "y = df.valuestrain, test = train_test_split(y, train_size=100)# Fit modelmodel = pm.auto_arima(train, seasonal=True, m=12)forecasts = model.predict(test.shape[0])x = np.arange(y.shape[0])plt.plot(x, y, c='blue' , label = 'expected')plt.plot(x[100:], forecasts, c='green' , label = 'predicted')plt.legend()plt.show()"
},
{
"code": null,
"e": 5473,
"s": 5445,
"text": "Great fit on the test data!"
},
{
"code": null,
"e": 5804,
"s": 5473,
"text": "Arima is a great tool for time series analysis, and Auto Arima packages make the process of fine-tuning a lot easierAlways plot your data and perform Explanatory Data analysis EDA in order to get a better understanding of the data.Learning the technicalities behind different prediction models can help you choose the correct one."
},
{
"code": null,
"e": 5921,
"s": 5804,
"text": "Arima is a great tool for time series analysis, and Auto Arima packages make the process of fine-tuning a lot easier"
},
{
"code": null,
"e": 6037,
"s": 5921,
"text": "Always plot your data and perform Explanatory Data analysis EDA in order to get a better understanding of the data."
}
] |
Geoparsing with Python. Geoparsing refers to the process of... | by Michael Eby | Towards Data Science | Geoparsing refers to the process of extracting place-names from text and matching those names unambiguously with proper nouns and spatial coordinates. These coordinates can then be plotted on a map in order to visualize the spatial footprint of the text in question. Geoparsing is a specific kind of procedure known in geography as toponym resolution: however, while both geoparsing and toponym resolution address the identification of concrete geographical entities in text, toponym resolution typically concerns the simple derivation of geography from structured, unambiguous references; an example is the post office’s use geocoded state abbreviations for routing. Geoparsing, on the other hand, indicates that the input text contains unstructured ambiguity; for example, a text may reference Georgia, both a country and a state in the southern USA, and it is the task of the geoparsing researcher to resolve that ambiguity.
In information science, literary analysis, and the digital humanities, the Edinburgh Geoparser has been in use since 2015 as an open-source tool employed strictly for the task of geoparsing historical documents and classical works. Available free online, the Edinburgh Geoparser allows researchers to follow the peregrinations of John Steinbeck’s Travels with Charley or George Orwell’s The Road to Wigan Pier not solely on paper, but on a computer screen. The program takes an input text, pinpoints location names, cross-references those names with a gazetteer — an atlas-like geographical directory — and plots the output on Google Maps. In this way, scholars can see the travels of a letter sender or a novel’s protagonist with God’s-eye view, each discrete destination in interactive panorama.
With the aid of just a handful of readily accessible packages, we can easily build our own rudimentary Edinburgh Geoparser in Python. What follows is an attempt at doing so. For this example, I will be parsing Mark Twain’s The Innocents Abroad. This is an apt text for the task: published in 1859, the novel was one of Twain’s most famous in his lifetime, and it remains one of the best-selling travelogues ever. From the United States to France, Odessa to Jerusalem, Twain and 60 compatriots from 15 different states traverse the globe, toponyms abounding throughout.
For this geoparser, the below packages will be needed. I will make it clear what each is doing as it is called in the script below.
>import numpy as np>import matplotlib.pyplot as plt>%matplotlib inline>>import pandas as pd>import geopandas as gpd>>from urllib import request>from geotext import GeoText>>from geopy.geocoders import Nominatim>from geopy.exc import GeocoderTimedOut>>from shapely.geometry import Point, Polygon>import descartes
The first thing to do is to grab The Innocents. The full text is available free online through the Gutenberg Project. Python’s natural language processing library NLTK natively provides 18 Gutenberg texts for practice. Unfortunately, The Innocents is not one of them, so I will use the requests object from the urllib module, pass the url for the raw .txt, and decode it in utf-8.
>url = "http://www.gutenberg.org/files/3176/3176-0.txt">response = request.urlopen(url)>raw = response.read().decode('utf8')>print(f'{type(raw)}, \n{len(raw)}, \n{raw[:501]}')<class 'str'>, 1145397, Project Gutenberg's The Innocents Abroad, by Mark Twain (Samuel Clemens)This eBook is for the use of anyone anywhere at no cost and withalmost no restrictions whatsoever. You may copy it, give it away orre-use it under the terms of the Project Gutenberg License includedwith this eBook or online at www.gutenberg.netTitle: The Innocents AbroadAuthor: Mark Twain (Samuel Clemens)Release Date: August 18, 2006 [EBook #3176]Last Updated: February 23, 2018Language: English
Printed in my Jupyter Notebook console is the book’s title page; the entire text is just one large string of 1145397 characters. This string contains all the geographical references that I will attempt to mine. The automatic processing pipeline of the NLP package SpaCy includes name entity recognition, assigning countries, states, and cities the label “geopolitical entities.” However, I was unable to find a simple way in SpaCy to extract just cities—save for writing an iterative function that cross-references Wikipedia summaries—so I am instead using GeoText, which has an attribute for easily extracting city names.
>places = GeoText(raw)>cities = list(places.cities)>cities['Tangier', 'Paris', 'Temple', 'Como', 'Garibaldi', 'Rome', 'Roman', 'Naples', 'Naples', ...]
Like SpaCy, GeoText recognizes geographically named entities, but calling .cities in GeoText returns just the city names. Note that I am not removing duplicates entries of cities; I want to keep these so that when I plot them my map contains frequencies of reference.
Now, I need a gazetteer, in order concretely ground these city-names with unambiguous spatial coordinates. The Edinburgh Geoparser contains specialized gazetteers for historical place names, but I don’t have access to those. Instead, OpenStreetMap is a collaborative map inspired by the Wikipedia model: it is free and editable by anyone. OSM has a search tool called Nominatim, which, given a city or state name, reverse geocodes that name and returns its geographical coordinates. So I just need to give Nominatim the list of city names. There are many ways to do this, but one way is through the Python package GeoPy, which abstract’s Nominatim’s API and returns the coordinates contained in the first result of the input search.
>geolocator = Nominatim(timeout=2)>>lat_lon = []>for city in cities: > try:> location = geolocator.geocode(city)> if location:> print(location.latitude, location.longitude)> lat_lon.append(location)> except GeocoderTimedOut as e:> print("Error: geocode failed on input %s with message %s"%>> (city, e))>lat_lon35.7642313 -5.8186259978951148.8566101 2.351499231.098207 -97.342784745.9394759 9.14941014540895-29.2562253 -51.526916741.894802 12.485338449.67887 4.3141940.8359336 14.248782640.8359336 14.2487826
I set the API’s timeout to 2 seconds, and included an error-handling statement that skips the current search if the API times out. My hope is that if an individual search takes longer than 2 seconds, it’s not really a city name, and the script will thus weed out non-names from the final map. I put the city names and coordinates into a Pandas dataframe:
>df = pd.DataFrame(lat_lon, columns=['City Name', 'Coordinates'])>df.head(7)
The coordinates, which are currently formatted as tuples, need to be transformed into point objects, as each city will be represented by a point on the map. The Python package Shapely does just that. Below, I’m iterating over the dataframe series that contains the coordinate tuples, turning them each into Points, and switching the order of latitude and longitude, only because that’s the order the map object I downloaded uses.
>geometry = [Point(x[1], x[0]) for x in df['Coordinates']]>geometry[:7][<shapely.geometry.point.Point at 0x116fe3b10>, <shapely.geometry.point.Point at 0x116ff9190>, <shapely.geometry.point.Point at 0x116fe0c10>, <shapely.geometry.point.Point at 0x116fe0a10>, <shapely.geometry.point.Point at 0x116fe0250>, <shapely.geometry.point.Point at 0x116fe0850>, <shapely.geometry.point.Point at 0x116fe0210>]
Putting these point objects back into a dataframe will allow us to plot them easily. Now, instead of a pandas dataframe, I will use a geopandas dataframe, which can easily handle these types of objects.
>## coordinate system I'm using>crs = {'init': 'epsg:4326'}>>## convert df to geo df>geo_df = gpd.GeoDataFrame(df, crs=crs, geometry=geometry)>geo_df.head()
The final step is to plot the map with the locations. The fact that I did not remove duplicate location entries means that, if I set the transparency of the markers, more frequently referenced locations will appear more opaque than those referenced just once. That’s being done with the alpha parameter in the plot object. Opaque markers should roughly correspond to cities where the USS Quaker City actually travelled, transparent ones to cites merely mentioned.
>## world map .shp file I downloaded>countries_map =gpd.read_file('Countries_WGS84/> Countries_WGS84.shp')>>f, ax = plt.subplots(figsize=(16, 16))>countries_map.plot(ax=ax, alpha=0.4, color='grey')>geo_df['geometry'].plot(ax=ax, markersize = 30, > color = 'b', marker = '^', alpha=.2)
And that’s Mark Twain’s The Innocents Abroad, geoparsed. | [
{
"code": null,
"e": 1100,
"s": 172,
"text": "Geoparsing refers to the process of extracting place-names from text and matching those names unambiguously with proper nouns and spatial coordinates. These coordinates can then be plotted on a map in order to visualize the spatial footprint of the text in question. Geoparsing is a specific kind of procedure known in geography as toponym resolution: however, while both geoparsing and toponym resolution address the identification of concrete geographical entities in text, toponym resolution typically concerns the simple derivation of geography from structured, unambiguous references; an example is the post office’s use geocoded state abbreviations for routing. Geoparsing, on the other hand, indicates that the input text contains unstructured ambiguity; for example, a text may reference Georgia, both a country and a state in the southern USA, and it is the task of the geoparsing researcher to resolve that ambiguity."
},
{
"code": null,
"e": 1898,
"s": 1100,
"text": "In information science, literary analysis, and the digital humanities, the Edinburgh Geoparser has been in use since 2015 as an open-source tool employed strictly for the task of geoparsing historical documents and classical works. Available free online, the Edinburgh Geoparser allows researchers to follow the peregrinations of John Steinbeck’s Travels with Charley or George Orwell’s The Road to Wigan Pier not solely on paper, but on a computer screen. The program takes an input text, pinpoints location names, cross-references those names with a gazetteer — an atlas-like geographical directory — and plots the output on Google Maps. In this way, scholars can see the travels of a letter sender or a novel’s protagonist with God’s-eye view, each discrete destination in interactive panorama."
},
{
"code": null,
"e": 2467,
"s": 1898,
"text": "With the aid of just a handful of readily accessible packages, we can easily build our own rudimentary Edinburgh Geoparser in Python. What follows is an attempt at doing so. For this example, I will be parsing Mark Twain’s The Innocents Abroad. This is an apt text for the task: published in 1859, the novel was one of Twain’s most famous in his lifetime, and it remains one of the best-selling travelogues ever. From the United States to France, Odessa to Jerusalem, Twain and 60 compatriots from 15 different states traverse the globe, toponyms abounding throughout."
},
{
"code": null,
"e": 2599,
"s": 2467,
"text": "For this geoparser, the below packages will be needed. I will make it clear what each is doing as it is called in the script below."
},
{
"code": null,
"e": 2911,
"s": 2599,
"text": ">import numpy as np>import matplotlib.pyplot as plt>%matplotlib inline>>import pandas as pd>import geopandas as gpd>>from urllib import request>from geotext import GeoText>>from geopy.geocoders import Nominatim>from geopy.exc import GeocoderTimedOut>>from shapely.geometry import Point, Polygon>import descartes"
},
{
"code": null,
"e": 3292,
"s": 2911,
"text": "The first thing to do is to grab The Innocents. The full text is available free online through the Gutenberg Project. Python’s natural language processing library NLTK natively provides 18 Gutenberg texts for practice. Unfortunately, The Innocents is not one of them, so I will use the requests object from the urllib module, pass the url for the raw .txt, and decode it in utf-8."
},
{
"code": null,
"e": 3963,
"s": 3292,
"text": ">url = \"http://www.gutenberg.org/files/3176/3176-0.txt\">response = request.urlopen(url)>raw = response.read().decode('utf8')>print(f'{type(raw)}, \\n{len(raw)}, \\n{raw[:501]}')<class 'str'>, 1145397, Project Gutenberg's The Innocents Abroad, by Mark Twain (Samuel Clemens)This eBook is for the use of anyone anywhere at no cost and withalmost no restrictions whatsoever. You may copy it, give it away orre-use it under the terms of the Project Gutenberg License includedwith this eBook or online at www.gutenberg.netTitle: The Innocents AbroadAuthor: Mark Twain (Samuel Clemens)Release Date: August 18, 2006 [EBook #3176]Last Updated: February 23, 2018Language: English"
},
{
"code": null,
"e": 4586,
"s": 3963,
"text": "Printed in my Jupyter Notebook console is the book’s title page; the entire text is just one large string of 1145397 characters. This string contains all the geographical references that I will attempt to mine. The automatic processing pipeline of the NLP package SpaCy includes name entity recognition, assigning countries, states, and cities the label “geopolitical entities.” However, I was unable to find a simple way in SpaCy to extract just cities—save for writing an iterative function that cross-references Wikipedia summaries—so I am instead using GeoText, which has an attribute for easily extracting city names."
},
{
"code": null,
"e": 4738,
"s": 4586,
"text": ">places = GeoText(raw)>cities = list(places.cities)>cities['Tangier', 'Paris', 'Temple', 'Como', 'Garibaldi', 'Rome', 'Roman', 'Naples', 'Naples', ...]"
},
{
"code": null,
"e": 5006,
"s": 4738,
"text": "Like SpaCy, GeoText recognizes geographically named entities, but calling .cities in GeoText returns just the city names. Note that I am not removing duplicates entries of cities; I want to keep these so that when I plot them my map contains frequencies of reference."
},
{
"code": null,
"e": 5739,
"s": 5006,
"text": "Now, I need a gazetteer, in order concretely ground these city-names with unambiguous spatial coordinates. The Edinburgh Geoparser contains specialized gazetteers for historical place names, but I don’t have access to those. Instead, OpenStreetMap is a collaborative map inspired by the Wikipedia model: it is free and editable by anyone. OSM has a search tool called Nominatim, which, given a city or state name, reverse geocodes that name and returns its geographical coordinates. So I just need to give Nominatim the list of city names. There are many ways to do this, but one way is through the Python package GeoPy, which abstract’s Nominatim’s API and returns the coordinates contained in the first result of the input search."
},
{
"code": null,
"e": 6308,
"s": 5739,
"text": ">geolocator = Nominatim(timeout=2)>>lat_lon = []>for city in cities: > try:> location = geolocator.geocode(city)> if location:> print(location.latitude, location.longitude)> lat_lon.append(location)> except GeocoderTimedOut as e:> print(\"Error: geocode failed on input %s with message %s\"%>> (city, e))>lat_lon35.7642313 -5.8186259978951148.8566101 2.351499231.098207 -97.342784745.9394759 9.14941014540895-29.2562253 -51.526916741.894802 12.485338449.67887 4.3141940.8359336 14.248782640.8359336 14.2487826"
},
{
"code": null,
"e": 6663,
"s": 6308,
"text": "I set the API’s timeout to 2 seconds, and included an error-handling statement that skips the current search if the API times out. My hope is that if an individual search takes longer than 2 seconds, it’s not really a city name, and the script will thus weed out non-names from the final map. I put the city names and coordinates into a Pandas dataframe:"
},
{
"code": null,
"e": 6740,
"s": 6663,
"text": ">df = pd.DataFrame(lat_lon, columns=['City Name', 'Coordinates'])>df.head(7)"
},
{
"code": null,
"e": 7170,
"s": 6740,
"text": "The coordinates, which are currently formatted as tuples, need to be transformed into point objects, as each city will be represented by a point on the map. The Python package Shapely does just that. Below, I’m iterating over the dataframe series that contains the coordinate tuples, turning them each into Points, and switching the order of latitude and longitude, only because that’s the order the map object I downloaded uses."
},
{
"code": null,
"e": 7571,
"s": 7170,
"text": ">geometry = [Point(x[1], x[0]) for x in df['Coordinates']]>geometry[:7][<shapely.geometry.point.Point at 0x116fe3b10>, <shapely.geometry.point.Point at 0x116ff9190>, <shapely.geometry.point.Point at 0x116fe0c10>, <shapely.geometry.point.Point at 0x116fe0a10>, <shapely.geometry.point.Point at 0x116fe0250>, <shapely.geometry.point.Point at 0x116fe0850>, <shapely.geometry.point.Point at 0x116fe0210>]"
},
{
"code": null,
"e": 7774,
"s": 7571,
"text": "Putting these point objects back into a dataframe will allow us to plot them easily. Now, instead of a pandas dataframe, I will use a geopandas dataframe, which can easily handle these types of objects."
},
{
"code": null,
"e": 7931,
"s": 7774,
"text": ">## coordinate system I'm using>crs = {'init': 'epsg:4326'}>>## convert df to geo df>geo_df = gpd.GeoDataFrame(df, crs=crs, geometry=geometry)>geo_df.head()"
},
{
"code": null,
"e": 8395,
"s": 7931,
"text": "The final step is to plot the map with the locations. The fact that I did not remove duplicate location entries means that, if I set the transparency of the markers, more frequently referenced locations will appear more opaque than those referenced just once. That’s being done with the alpha parameter in the plot object. Opaque markers should roughly correspond to cities where the USS Quaker City actually travelled, transparent ones to cites merely mentioned."
},
{
"code": null,
"e": 8732,
"s": 8395,
"text": ">## world map .shp file I downloaded>countries_map =gpd.read_file('Countries_WGS84/> Countries_WGS84.shp')>>f, ax = plt.subplots(figsize=(16, 16))>countries_map.plot(ax=ax, alpha=0.4, color='grey')>geo_df['geometry'].plot(ax=ax, markersize = 30, > color = 'b', marker = '^', alpha=.2)"
}
] |
Can we sort a list with Lambda in Java? | Yes, we can sort a list with Lambda. Let us first create a String List:
List<String> list = Arrays.asList("LCD","Laptop", "Mobile", "Device", "LED", "Tablet");
Now, sort using Lambda, wherein we will be using compareTo():
Collections.sort(list, (String str1, String str2) -> str2.compareTo(str1));
The following is an example to sort a list with Lambda in Java:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Demo {
public static void main(String... args) {
List<String> list = Arrays.asList("LCD","Laptop", "Mobile", "Device", "LED", "Tablet");
System.out.println("List = "+list);
Collections.sort(list, (String str1, String str2) -> str2.compareTo(str1));
System.out.println("Sorted List = "+list);
}
}
List = [LCD, Laptop, Mobile, Device, LED, Tablet]
Sorted List = [Tablet, Mobile, Laptop, LED, LCD, Device] | [
{
"code": null,
"e": 1134,
"s": 1062,
"text": "Yes, we can sort a list with Lambda. Let us first create a String List:"
},
{
"code": null,
"e": 1222,
"s": 1134,
"text": "List<String> list = Arrays.asList(\"LCD\",\"Laptop\", \"Mobile\", \"Device\", \"LED\", \"Tablet\");"
},
{
"code": null,
"e": 1284,
"s": 1222,
"text": "Now, sort using Lambda, wherein we will be using compareTo():"
},
{
"code": null,
"e": 1360,
"s": 1284,
"text": "Collections.sort(list, (String str1, String str2) -> str2.compareTo(str1));"
},
{
"code": null,
"e": 1424,
"s": 1360,
"text": "The following is an example to sort a list with Lambda in Java:"
},
{
"code": null,
"e": 1843,
"s": 1424,
"text": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\npublic class Demo {\n public static void main(String... args) { \n List<String> list = Arrays.asList(\"LCD\",\"Laptop\", \"Mobile\", \"Device\", \"LED\", \"Tablet\");\n System.out.println(\"List = \"+list);\n Collections.sort(list, (String str1, String str2) -> str2.compareTo(str1));\n System.out.println(\"Sorted List = \"+list);\n }\n}"
},
{
"code": null,
"e": 1950,
"s": 1843,
"text": "List = [LCD, Laptop, Mobile, Device, LED, Tablet]\nSorted List = [Tablet, Mobile, Laptop, LED, LCD, Device]"
}
] |
How to add custom adapter for my listView on Android? | This example demonstrates how do I add custom adapter for my listView in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<MyData> arrayList = new ArrayList<>();
MyAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
arrayList.add(new MyData(1, " Mashu","987576443"));
arrayList.add(new MyData(2, " Azhar","8787576768"));
arrayList.add(new MyData(3, " Niyaz","65757657657"));
adapter = new MyAdapter(this, arrayList);
listView.setAdapter(adapter);
}
}
Step 4 − Create a java class(MyData.java) and add the following code
public class MyData {
private int serialNum;
private String name;
private String mobileNumber;
public MyData(int num, String name, String mobileNumber) {
this.serialNum = num;
this.name = name;
this.mobileNumber = mobileNumber;
}
public int getNum() {
return serialNum;
}
public void setNum(int num) {
this.serialNum = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
}
Step 5 − Create a java class(MyAdapter.java) and add the following code −
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class MyAdapter extends BaseAdapter {
private Context context;
private ArrayList<MyData> arrayList;
private TextView serialNum, name, contactNum;
public MyAdapter(Context context, ArrayList<MyData> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
@Override
public int getCount() {
return arrayList.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = LayoutInflater.from(context).inflate(R.layout.row, parent, false);
serialNum = convertView.findViewById(R.id.serailNumber);
name = convertView.findViewById(R.id.studentName);
contactNum = convertView.findViewById(R.id.mobileNum);
serialNum.setText(" " + arrayList.get(position).getNum());
name.setText(arrayList.get(position).getName());
contactNum.setText(arrayList.get(position).getMobileNumber());
return convertView;
}
}
Step 6 − Create a layout resource file(row.xml) and add the following code −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp">
<TextView
android:id="@+id/serailNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number"
android:textColor="@color/colorPrimary"
android:textSize="16sp" />
<TextView
android:id="@+id/studentName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textColor="#000000"
android:textSize="16sp" />
<TextView
android:id="@+id/mobileNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mobile Number"
android:textColor="@color/colorAccent"
android:textSize="16sp" />
</LinearLayout>
Step 7 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − | [
{
"code": null,
"e": 1144,
"s": 1062,
"text": "This example demonstrates how do I add custom adapter for my listView in android."
},
{
"code": null,
"e": 1273,
"s": 1144,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1338,
"s": 1273,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1716,
"s": 1338,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:orientation=\"vertical\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n <ListView\n android:id=\"@+id/listView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"/>\n</LinearLayout>"
},
{
"code": null,
"e": 1773,
"s": 1716,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2529,
"s": 1773,
"text": "import android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.ListView;\nimport java.util.ArrayList;\npublic class MainActivity extends AppCompatActivity {\n ListView listView;\n ArrayList<MyData> arrayList = new ArrayList<>();\n MyAdapter adapter;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n listView = findViewById(R.id.listView);\n arrayList.add(new MyData(1, \" Mashu\",\"987576443\"));\n arrayList.add(new MyData(2, \" Azhar\",\"8787576768\"));\n arrayList.add(new MyData(3, \" Niyaz\",\"65757657657\"));\n adapter = new MyAdapter(this, arrayList);\n listView.setAdapter(adapter);\n }\n}"
},
{
"code": null,
"e": 2598,
"s": 2529,
"text": "Step 4 − Create a java class(MyData.java) and add the following code"
},
{
"code": null,
"e": 3272,
"s": 2598,
"text": "public class MyData {\n private int serialNum;\n private String name;\n private String mobileNumber;\n public MyData(int num, String name, String mobileNumber) {\n this.serialNum = num;\n this.name = name;\n this.mobileNumber = mobileNumber;\n }\n public int getNum() {\n return serialNum;\n }\n public void setNum(int num) {\n this.serialNum = num;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getMobileNumber() {\n return mobileNumber;\n }\n public void setMobileNumber(String mobileNumber) {\n this.mobileNumber = mobileNumber;\n }\n}\n"
},
{
"code": null,
"e": 3346,
"s": 3272,
"text": "Step 5 − Create a java class(MyAdapter.java) and add the following code −"
},
{
"code": null,
"e": 4683,
"s": 3346,
"text": "import android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.BaseAdapter;\nimport android.widget.TextView;\nimport java.util.ArrayList;\npublic class MyAdapter extends BaseAdapter {\n private Context context;\n private ArrayList<MyData> arrayList;\n private TextView serialNum, name, contactNum;\n public MyAdapter(Context context, ArrayList<MyData> arrayList) {\n this.context = context;\n this.arrayList = arrayList;\n }\n @Override\n public int getCount() {\n return arrayList.size();\n }\n @Override\n public Object getItem(int position) {\n return position;\n }\n @Override\n public long getItemId(int position) {\n return position;\n }\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n convertView = LayoutInflater.from(context).inflate(R.layout.row, parent, false);\n serialNum = convertView.findViewById(R.id.serailNumber);\n name = convertView.findViewById(R.id.studentName);\n contactNum = convertView.findViewById(R.id.mobileNum);\n serialNum.setText(\" \" + arrayList.get(position).getNum());\n name.setText(arrayList.get(position).getName());\n contactNum.setText(arrayList.get(position).getMobileNumber());\n return convertView;\n }\n}"
},
{
"code": null,
"e": 4760,
"s": 4683,
"text": "Step 6 − Create a layout resource file(row.xml) and add the following code −"
},
{
"code": null,
"e": 5744,
"s": 4760,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:orientation=\"vertical\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"4dp\">\n <TextView\n android:id=\"@+id/serailNumber\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Number\"\n android:textColor=\"@color/colorPrimary\"\n android:textSize=\"16sp\" />\n <TextView\n android:id=\"@+id/studentName\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Name\"\n android:textColor=\"#000000\"\n android:textSize=\"16sp\" />\n <TextView\n android:id=\"@+id/mobileNum\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Mobile Number\"\n android:textColor=\"@color/colorAccent\"\n android:textSize=\"16sp\" />\n</LinearLayout>"
},
{
"code": null,
"e": 5799,
"s": 5744,
"text": "Step 7 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 6505,
"s": 5799,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action\n android:name=\"android.intent.action.MAIN\" />\n <category\n android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 6852,
"s": 6505,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
}
] |
Elasticsearch - Installation | In this chapter, we will understand the installation procedure of Elasticsearch in detail.
To install Elasticsearch on your local computer, you will have to follow the steps given below −
Step 1 − Check the version of java installed on your computer. It should be java 7 or higher. You can check by doing the following −
In Windows Operating System (OS) (using command prompt)−
> java -version
In UNIX OS (Using Terminal) −
$ echo $JAVA_HOME
Step 2 − Depending on your operating system, download Elasticsearch from www.elastic.co as mentioned below −
For windows OS, download ZIP file.
For windows OS, download ZIP file.
For UNIX OS, download TAR file.
For UNIX OS, download TAR file.
For Debian OS, download DEB file.
For Debian OS, download DEB file.
For Red Hat and other Linux distributions, download RPN file.
For Red Hat and other Linux distributions, download RPN file.
APT and Yum utilities can also be used to install Elasticsearch in many Linux distributions.
APT and Yum utilities can also be used to install Elasticsearch in many Linux distributions.
Step 3 − Installation process for Elasticsearch is simple and is described below for different OS −
Windows OS− Unzip the zip package and the Elasticsearch is installed.
Windows OS− Unzip the zip package and the Elasticsearch is installed.
UNIX OS− Extract tar file in any location and the Elasticsearch is installed.
UNIX OS− Extract tar file in any location and the Elasticsearch is installed.
$wget
https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch7.0.0-linux-x86_64.tar.gz
$tar -xzf elasticsearch-7.0.0-linux-x86_64.tar.gz
Using APT utility for Linux OS− Download and install the Public Signing Key
Using APT utility for Linux OS− Download and install the Public Signing Key
$ wget -qo - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo
apt-key add -
Save the repository definition as shown below −
$ echo "deb https://artifacts.elastic.co/packages/7.x/apt stable main" |
sudo tee -a /etc/apt/sources.list.d/elastic-7.x.list
Run update using the following command −
$ sudo apt-get update
Now you can install by using the following command −
$ sudo apt-get install elasticsearch
Download and install the Debian package manually using the command given here −
Download and install the Debian package manually using the command given here −
$wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch7.0.0-amd64.deb
$sudo dpkg -i elasticsearch-7.0.0-amd64.deb0
Using YUM utility for Debian Linux OS
Using YUM utility for Debian Linux OS
Download and install the Public Signing Key −
$ rpm --import https://artifacts.elastic.co/GPG-KEY-elasticsearch
ADD the following text in the file with .repo suffix in your “/etc/yum.repos.d/” directory. For example, elasticsearch.repo
ADD the following text in the file with .repo suffix in your “/etc/yum.repos.d/” directory. For example, elasticsearch.repo
elasticsearch-7.x]
name=Elasticsearch repository for 7.x packages
baseurl=https://artifacts.elastic.co/packages/7.x/yum
gpgcheck=1
gpgkey=https://artifacts.elastic.co/GPG-KEY-elasticsearch
enabled=1
autorefresh=1
type=rpm-md
You can now install Elasticsearch by using the following command
You can now install Elasticsearch by using the following command
sudo yum install elasticsearch
Step 4 − Go to the Elasticsearch home directory and inside the bin folder. Run the
elasticsearch.bat file in case of Windows or you can do the same using command prompt and through terminal in case of UNIX rum Elasticsearch file.
> cd elasticsearch-2.1.0/bin
> elasticsearch
$ cd elasticsearch-2.1.0/bin
$ ./elasticsearch
Note − In case of windows, you might get an error stating JAVA_HOME is not set, please
set it in environment variables to “C:\Program Files\Java\jre1.8.0_31” or the location where you installed java.
Step 5 − The default port for Elasticsearch web interface is 9200 or you can change it by
changing http.port inside the elasticsearch.yml file present in bin directory. You can check if the server is up and running by browsing http://localhost:9200. It will return a JSON object, which contains the information about the installed Elasticsearch in the following manner −
{
"name" : "Brain-Child",
"cluster_name" : "elasticsearch", "version" : {
"number" : "2.1.0",
"build_hash" : "72cd1f1a3eee09505e036106146dc1949dc5dc87",
"build_timestamp" : "2015-11-18T22:40:03Z",
"build_snapshot" : false,
"lucene_version" : "5.3.1"
},
"tagline" : "You Know, for Search"
}
Step 6 − In this step, let us install Kibana. Follow the respective code given below for
installing on Linux and Windows −
For Installation on Linux −
wget https://artifacts.elastic.co/downloads/kibana/kibana-7.0.0-linuxx86_64.tar.gz
tar -xzf kibana-7.0.0-linux-x86_64.tar.gz
cd kibana-7.0.0-linux-x86_64/
./bin/kibana
For Installation on Windows −
Download Kibana for Windows from https://www.elastic.co/products/kibana. Once you click the link, you will find the home page as shown below −
Unzip and go to the Kibana home directory and then run it.
CD c:\kibana-7.0.0-windows-x86_64
.\bin\kibana.bat
14 Lectures
5 hours
Manuj Aggarwal
20 Lectures
1 hours
Faizan Tayyab
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2672,
"s": 2581,
"text": "In this chapter, we will understand the installation procedure of Elasticsearch in detail."
},
{
"code": null,
"e": 2769,
"s": 2672,
"text": "To install Elasticsearch on your local computer, you will have to follow the steps given below −"
},
{
"code": null,
"e": 2902,
"s": 2769,
"text": "Step 1 − Check the version of java installed on your computer. It should be java 7 or higher. You can check by doing the following −"
},
{
"code": null,
"e": 2959,
"s": 2902,
"text": "In Windows Operating System (OS) (using command prompt)−"
},
{
"code": null,
"e": 2976,
"s": 2959,
"text": "> java -version\n"
},
{
"code": null,
"e": 3006,
"s": 2976,
"text": "In UNIX OS (Using Terminal) −"
},
{
"code": null,
"e": 3025,
"s": 3006,
"text": "$ echo $JAVA_HOME\n"
},
{
"code": null,
"e": 3134,
"s": 3025,
"text": "Step 2 − Depending on your operating system, download Elasticsearch from www.elastic.co as mentioned below −"
},
{
"code": null,
"e": 3169,
"s": 3134,
"text": "For windows OS, download ZIP file."
},
{
"code": null,
"e": 3204,
"s": 3169,
"text": "For windows OS, download ZIP file."
},
{
"code": null,
"e": 3236,
"s": 3204,
"text": "For UNIX OS, download TAR file."
},
{
"code": null,
"e": 3268,
"s": 3236,
"text": "For UNIX OS, download TAR file."
},
{
"code": null,
"e": 3302,
"s": 3268,
"text": "For Debian OS, download DEB file."
},
{
"code": null,
"e": 3336,
"s": 3302,
"text": "For Debian OS, download DEB file."
},
{
"code": null,
"e": 3398,
"s": 3336,
"text": "For Red Hat and other Linux distributions, download RPN file."
},
{
"code": null,
"e": 3460,
"s": 3398,
"text": "For Red Hat and other Linux distributions, download RPN file."
},
{
"code": null,
"e": 3553,
"s": 3460,
"text": "APT and Yum utilities can also be used to install Elasticsearch in many Linux distributions."
},
{
"code": null,
"e": 3646,
"s": 3553,
"text": "APT and Yum utilities can also be used to install Elasticsearch in many Linux distributions."
},
{
"code": null,
"e": 3746,
"s": 3646,
"text": "Step 3 − Installation process for Elasticsearch is simple and is described below for different OS −"
},
{
"code": null,
"e": 3816,
"s": 3746,
"text": "Windows OS− Unzip the zip package and the Elasticsearch is installed."
},
{
"code": null,
"e": 3886,
"s": 3816,
"text": "Windows OS− Unzip the zip package and the Elasticsearch is installed."
},
{
"code": null,
"e": 3964,
"s": 3886,
"text": "UNIX OS− Extract tar file in any location and the Elasticsearch is installed."
},
{
"code": null,
"e": 4042,
"s": 3964,
"text": "UNIX OS− Extract tar file in any location and the Elasticsearch is installed."
},
{
"code": null,
"e": 4192,
"s": 4042,
"text": "$wget\nhttps://artifacts.elastic.co/downloads/elasticsearch/elasticsearch7.0.0-linux-x86_64.tar.gz\n\n$tar -xzf elasticsearch-7.0.0-linux-x86_64.tar.gz\n"
},
{
"code": null,
"e": 4269,
"s": 4192,
"text": "Using APT utility for Linux OS− Download and install the Public Signing Key "
},
{
"code": null,
"e": 4346,
"s": 4269,
"text": "Using APT utility for Linux OS− Download and install the Public Signing Key "
},
{
"code": null,
"e": 4432,
"s": 4346,
"text": "$ wget -qo - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo\napt-key add -\n"
},
{
"code": null,
"e": 4480,
"s": 4432,
"text": "Save the repository definition as shown below −"
},
{
"code": null,
"e": 4607,
"s": 4480,
"text": "$ echo \"deb https://artifacts.elastic.co/packages/7.x/apt stable main\" |\nsudo tee -a /etc/apt/sources.list.d/elastic-7.x.list\n"
},
{
"code": null,
"e": 4648,
"s": 4607,
"text": "Run update using the following command −"
},
{
"code": null,
"e": 4671,
"s": 4648,
"text": "$ sudo apt-get update\n"
},
{
"code": null,
"e": 4724,
"s": 4671,
"text": "Now you can install by using the following command −"
},
{
"code": null,
"e": 4762,
"s": 4724,
"text": "$ sudo apt-get install elasticsearch\n"
},
{
"code": null,
"e": 4842,
"s": 4762,
"text": "Download and install the Debian package manually using the command given here −"
},
{
"code": null,
"e": 4922,
"s": 4842,
"text": "Download and install the Debian package manually using the command given here −"
},
{
"code": null,
"e": 5056,
"s": 4922,
"text": "$wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch7.0.0-amd64.deb\n$sudo dpkg -i elasticsearch-7.0.0-amd64.deb0\n"
},
{
"code": null,
"e": 5094,
"s": 5056,
"text": "Using YUM utility for Debian Linux OS"
},
{
"code": null,
"e": 5132,
"s": 5094,
"text": "Using YUM utility for Debian Linux OS"
},
{
"code": null,
"e": 5178,
"s": 5132,
"text": "Download and install the Public Signing Key −"
},
{
"code": null,
"e": 5245,
"s": 5178,
"text": "$ rpm --import https://artifacts.elastic.co/GPG-KEY-elasticsearch\n"
},
{
"code": null,
"e": 5369,
"s": 5245,
"text": "ADD the following text in the file with .repo suffix in your “/etc/yum.repos.d/” directory. For example, elasticsearch.repo"
},
{
"code": null,
"e": 5493,
"s": 5369,
"text": "ADD the following text in the file with .repo suffix in your “/etc/yum.repos.d/” directory. For example, elasticsearch.repo"
},
{
"code": null,
"e": 5719,
"s": 5493,
"text": "elasticsearch-7.x]\nname=Elasticsearch repository for 7.x packages\nbaseurl=https://artifacts.elastic.co/packages/7.x/yum\ngpgcheck=1\ngpgkey=https://artifacts.elastic.co/GPG-KEY-elasticsearch\nenabled=1\nautorefresh=1\ntype=rpm-md\n"
},
{
"code": null,
"e": 5784,
"s": 5719,
"text": "You can now install Elasticsearch by using the following command"
},
{
"code": null,
"e": 5849,
"s": 5784,
"text": "You can now install Elasticsearch by using the following command"
},
{
"code": null,
"e": 5881,
"s": 5849,
"text": "sudo yum install elasticsearch\n"
},
{
"code": null,
"e": 6111,
"s": 5881,
"text": "Step 4 − Go to the Elasticsearch home directory and inside the bin folder. Run the\nelasticsearch.bat file in case of Windows or you can do the same using command prompt and through terminal in case of UNIX rum Elasticsearch file."
},
{
"code": null,
"e": 6157,
"s": 6111,
"text": "> cd elasticsearch-2.1.0/bin\n> elasticsearch\n"
},
{
"code": null,
"e": 6205,
"s": 6157,
"text": "$ cd elasticsearch-2.1.0/bin\n$ ./elasticsearch\n"
},
{
"code": null,
"e": 6405,
"s": 6205,
"text": "Note − In case of windows, you might get an error stating JAVA_HOME is not set, please\nset it in environment variables to “C:\\Program Files\\Java\\jre1.8.0_31” or the location where you installed java."
},
{
"code": null,
"e": 6776,
"s": 6405,
"text": "Step 5 − The default port for Elasticsearch web interface is 9200 or you can change it by\nchanging http.port inside the elasticsearch.yml file present in bin directory. You can check if the server is up and running by browsing http://localhost:9200. It will return a JSON object, which contains the information about the installed Elasticsearch in the following manner −"
},
{
"code": null,
"e": 7108,
"s": 6776,
"text": "{\n \"name\" : \"Brain-Child\",\n \"cluster_name\" : \"elasticsearch\", \"version\" : {\n \"number\" : \"2.1.0\",\n \"build_hash\" : \"72cd1f1a3eee09505e036106146dc1949dc5dc87\",\n \"build_timestamp\" : \"2015-11-18T22:40:03Z\",\n \"build_snapshot\" : false,\n \"lucene_version\" : \"5.3.1\"\n },\n \"tagline\" : \"You Know, for Search\"\n}"
},
{
"code": null,
"e": 7231,
"s": 7108,
"text": "Step 6 − In this step, let us install Kibana. Follow the respective code given below for\ninstalling on Linux and Windows −"
},
{
"code": null,
"e": 7259,
"s": 7231,
"text": "For Installation on Linux −"
},
{
"code": null,
"e": 7431,
"s": 7259,
"text": "wget https://artifacts.elastic.co/downloads/kibana/kibana-7.0.0-linuxx86_64.tar.gz\n\ntar -xzf kibana-7.0.0-linux-x86_64.tar.gz\n\ncd kibana-7.0.0-linux-x86_64/\n\n./bin/kibana\n"
},
{
"code": null,
"e": 7461,
"s": 7431,
"text": "For Installation on Windows −"
},
{
"code": null,
"e": 7604,
"s": 7461,
"text": "Download Kibana for Windows from https://www.elastic.co/products/kibana. Once you click the link, you will find the home page as shown below −"
},
{
"code": null,
"e": 7663,
"s": 7604,
"text": "Unzip and go to the Kibana home directory and then run it."
},
{
"code": null,
"e": 7715,
"s": 7663,
"text": "CD c:\\kibana-7.0.0-windows-x86_64\n.\\bin\\kibana.bat\n"
},
{
"code": null,
"e": 7748,
"s": 7715,
"text": "\n 14 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7764,
"s": 7748,
"text": " Manuj Aggarwal"
},
{
"code": null,
"e": 7797,
"s": 7764,
"text": "\n 20 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7812,
"s": 7797,
"text": " Faizan Tayyab"
},
{
"code": null,
"e": 7819,
"s": 7812,
"text": " Print"
},
{
"code": null,
"e": 7830,
"s": 7819,
"text": " Add Notes"
}
] |
What are named parameters in C#? | Named parameters provides us the relaxation to remember or to look up the order of parameters in the parameter lists of called methods. The parameter for each argument can be specified by parameter name.
NamedParameterFunction(firstName: "Hello", lastName: "World")
Using named parameters in C#, we can put any parameter in any sequence as long as the name is there. The right parameter value based on their names will be mapped to the right variable. The parameters name must match with the method definition parameter names. Named arguments also improve the readability of our code by identifying what each argument represents.
Live Demo
using System;
namespace DemoApplication{
class Demo{
static void Main(string[] args){
NamedParameterFunction("James", "Bond");
NamedParameterFunction(firstName:"Mark", lastName:"Wood");
NamedParameterFunction(lastName: "Federer", firstName: "Roger");
Console.ReadLine();
}
public static void NamedParameterFunction(string firstName, string lastName){
Console.WriteLine($"FullName: {firstName} {lastName}");
}
}
}
The output of the above code is
FullName: James Bond
FullName: Mark Wood
FullName: Roger Federer
In the above code NamedParameterFunction(lastName: "Federer", firstName: "Roger") even though parameters are not passed in order since we are using named parameters, the parameters are mapped based on the name. So we are getting the output "Roger Federer" which is as expected. | [
{
"code": null,
"e": 1266,
"s": 1062,
"text": "Named parameters provides us the relaxation to remember or to look up the order of parameters in the parameter lists of called methods. The parameter for each argument can be specified by parameter name."
},
{
"code": null,
"e": 1328,
"s": 1266,
"text": "NamedParameterFunction(firstName: \"Hello\", lastName: \"World\")"
},
{
"code": null,
"e": 1692,
"s": 1328,
"text": "Using named parameters in C#, we can put any parameter in any sequence as long as the name is there. The right parameter value based on their names will be mapped to the right variable. The parameters name must match with the method definition parameter names. Named arguments also improve the readability of our code by identifying what each argument represents."
},
{
"code": null,
"e": 1703,
"s": 1692,
"text": " Live Demo"
},
{
"code": null,
"e": 2191,
"s": 1703,
"text": "using System;\nnamespace DemoApplication{\n class Demo{\n static void Main(string[] args){\n NamedParameterFunction(\"James\", \"Bond\");\n NamedParameterFunction(firstName:\"Mark\", lastName:\"Wood\");\n NamedParameterFunction(lastName: \"Federer\", firstName: \"Roger\");\n Console.ReadLine();\n }\n public static void NamedParameterFunction(string firstName, string lastName){\n Console.WriteLine($\"FullName: {firstName} {lastName}\");\n }\n }\n}"
},
{
"code": null,
"e": 2223,
"s": 2191,
"text": "The output of the above code is"
},
{
"code": null,
"e": 2288,
"s": 2223,
"text": "FullName: James Bond\nFullName: Mark Wood\nFullName: Roger Federer"
},
{
"code": null,
"e": 2566,
"s": 2288,
"text": "In the above code NamedParameterFunction(lastName: \"Federer\", firstName: \"Roger\") even though parameters are not passed in order since we are using named parameters, the parameters are mapped based on the name. So we are getting the output \"Roger Federer\" which is as expected."
}
] |
Augmentation Methods Using Albumentations And PyTorch | by Varun Dutt | Towards Data Science | Ever since the Deep Neural Net's rise to fame in the late 1990s, limited data has been a stumbling block. Lack of data results in overfitting, especially for architectures with a lot of parameters. Luckily, augmentation has turned out to be a revelation for machine learning tasks with limited data. It offers two major advantages.
First, you can increase the amount of data by creating several augmented copies of your original dataset which can also be used to balance a skewed dataset.
Second, it forces the model to be invariant to non-relevant features in the samples, for example, background in a face detection task. This helps the model generalize better.
In this post, we will explore the latest data augmentation methods and a novel implementation using the methods discussed. We’ll mainly be covering two methods, AutoAugment, and RandAugment. So, let’s start with a brief introduction to both the methods and then move on to the implementation.
AutoAugment introduced in “AutoAugment: Learning Augmentation Strategies from Data” attempts to automate choosing the type and magnitude of the transformations to apply to a sample. They propose a reinforcement learning method that finds an effective data augmentation policy by discretizing the search problem. The proposed method finds an augmentation policy S which has information on the transformations, the magnitudes of the transformations, and the probabilities of using those transformations.
Let us look at some of the details of the algorithm.
A policy S contains five sub-policies, each sub_policy has two transformations with each transformation having a magnitude and a probability parameter.
Note that the sub-policies here are sensitive to the sequence of the transformations and treated as a different sub-policy if the sequence of application is reversed.
There are 16 augmentation transformations that the controller can choose from (will be discussed in the implementation section). The range of the magnitude and the probability of application for each transformation has been discretized into 10 and 11 uniformly spaced values respectively.
The search algorithm has two components: a controller, which is a recurrent neural network(RNN), and the training algorithm, which is the Proximal Policy Optimization algorithm.
The controller (RNN) predicts an augmentation policy S from the search space, the predicted policy is then used to train a much smaller child model. The child model is trained on augmented data generated by applying the 5 predicted sub-policies on the training set. For each example in the mini-batch, one of the 5 sub-policies is chosen randomly to augment the image. The child model is then evaluated on a separate held-out validation set to measure the accuracy R, which is used as the reward signal to train the RNN controller.
You can read the entire paper here for all the details.
AutoAugment was one of the first papers to implement an automated approach to data augmentation effectively and showed substantially better results than previous automated approaches. However, the separate optimization procedure and the prohibitively large search space have a high computational cost. Moreover, the method makes a strong assumption that the result from a smaller network is transferable to a much larger network. This assumption, as it turns out, is not entirely true as pointed out in the RandAugment paper which proposes a much faster and in some situations better-performing method for data augmentation which we will discuss next.
Most learned augmentation algorithms like AutoAugment creates a proxy task that optimizes for the best augmentation policy on a smaller network, as discussed in the previous section this approach has some fundamental flaws which need to be addressed. RandAugment introduced in “RandAugment: Practical automated data augmentation with a reduced search space” attempts to circumvent this proxy task and also drastically reduce the search space to ease the computational load on the training procedure. The method reduces the number of parameters to two, N and M (which will be discussed in detail in the subsequent sub-section), and treats them as hyperparameters in the training procedure.
RandAugment instead of learning a policy picks a transformation randomly from a set of K transformations with a uniform probability of 1/K. The number of transformations to be picked is given by N which is a hyperparameter, this reduces the total policies in the search space to K pow N. The main benefit of the learned augmentation approach comes from increasing the diversity of the samples, uniform probability approach employed by RandAugment maintains the diversity of the samples but with significantly reduced search space.
Finally, the range of magnitude for each transformation similar to AutoAugment is discretized into 10 uniformly spaced values given by M, however, contrary to the learned approach all the transformations follow the same schedule for M which reduces the search space for magnitudes to just one. This is due to the fact that the optimal magnitude for augmentation depends on the size of the model and the training set, larger networks require larger data distortions(please refer to the image above) which intuitively makes sense. The paper also points out that larger datasets require larger data distortions which seems odd, one hypothesis that the authors put forward is that aggressive augmentation in small datasets might lead to a low signal-to-noise ratio. In any case, there is a clear pattern for optimal magnitude that all transformations follow based on the model size and training set size, this exposes a fundamental flaw in the learned augmentation approach which uses smaller networks to estimate transformation magnitude for all the tasks.
RandAugment uses a simple grid search to find optimal values for N and M, this is done by selecting a set of values for both the hyperparameters and testing all the permutations from those sets on a separate validation set. Finally, choosing the combination that gives the best improvement on the validation set. This procedure can be performed for every sample, every batch, or every epoch.
Now, that we have a fairly good understanding of the algorithms let us move towards the implementation. As discussed previously RandAugment is a much better algorithm, however, some key findings from the AutoAugment paper can be used in conjunction with RandAugment to reduce the computational cost even further.
You can download the notebook for this post from here, the notebook has all the necessary code to set up the augmentation algorithm and test it with Resnet50 on a small part of the Imagenet dataset provided by fastai. However, we will be only focusing on the part of the notebook relevant to augmentation in this post.
Let’s start by looking at the custom RandAugment function from the notebook and then break it down.
def randAugment(N, M, p, mode="all", cut_out = False): # Magnitude(M) search space shift_x = np.linspace(0,150,10) shift_y = np.linspace(0,150,10) rot = np.linspace(0,30,10) shear = np.linspace(0,10,10) sola = np.linspace(0,256,10) post = [4,4,5,5,6,6,7,7,8,8] cont = [np.linspace(-0.8,-0.1,10),np.linspace(0.1,2,10)] bright = np.linspace(0.1,0.7,10) shar = np.linspace(0.1,0.9,10) cut = np.linspace(0,60,10) # Transformation search space Aug =[#0 - geometrical A.ShiftScaleRotate(shift_limit_x=shift_x[M], rotate_limit=0, shift_limit_y=0, shift_limit=shift_x[M], p=p), A.ShiftScaleRotate(shift_limit_y=shift_y[M], rotate_limit=0, shift_limit_x=0, shift_limit=shift_y[M], p=p), A.IAAAffine(rotate=rot[M], p=p), A.IAAAffine(shear=shear[M], p=p), A.InvertImg(p=p), #5 - Color Based A.Equalize(p=p), A.Solarize(threshold=sola[M], p=p), A.Posterize(num_bits=post[M], p=p), A.RandomContrast(limit=[cont[0][M], cont[1][M]], p=p), A.RandomBrightness(limit=bright[M], p=p), A.IAASharpen(alpha=shar[M], lightness=shar[M], p=p)] # Sampling from the Transformation search space if mode == "geo": ops = np.random.choice(Aug[0:5], N) elif mode == "color": ops = np.random.choice(Aug[5:], N) else: ops = np.random.choice(Aug, N) if cut_out: ops.append(A.Cutout(num_holes=8, max_h_size=int(cut[M]), max_w_size=int(cut[M]), p=p)) transforms = A.Compose(ops) return transforms, ops
The function can roughly be divided into the following two sections.
This section discretizes the magnitude range into 10 uniformly spaced values.
“Aug” is the Transformation Search Space from which the algorithm can pick N transformations with uniform probability. Please take the time to see what these individual transformations do to get a better feel for creating this search space.
Note that the function has three modes “geo”, “color” and “all”. The “geo” mode is for tasks where color-based features define the object of interest in the image eg. fire detection. Similarly, the “color” mode is for tasks where the shape defines the object of interest eg. face detection, detecting a car, etc. Whereas, the “all” mode uses all the transformations.
The authors in the AutoAugment paper showed that different datasets were sensitive to different transformations in both positive and negative directions. Therefore, the “No Free Lunch” theorem applies in data augmentation as well and you will need to tweak the algorithm for every project.
Note that the magnitude ranges given in the table above are for functions from the PIL library, however, we are using Albumentaions in the randAugment() function, mainly because Albumentaions library uses open cv which is faster compared to PIL. You would have to experiment and figure out the magnitude range for each transformation for the library you like to use .
Let’s now look at the schedule for the magnitude of the transformations during training.
def train_model(model, criterion, optimizer, scheduler, aug_mode="all", cut_out=False, max_M=9, num_epochs=25): best_model_wts = copy.deepcopy(model.state_dict()) best_acc = 0.0 N=2;M=0;p=0.5 for epoch in range(num_epochs): print('Epoch {}/{}'.format(epoch, num_epochs - 1)) print('-' * 10) transforms, ops = randAugment(N=N, M=M, p=p, mode=aug_mode, cut_out=cut_out) dataloaders, dataset_sizes = create_dataloaders(root, train_df, valid_df, label_dict, bs=32, transforms=transforms) # Each epoch has a training and validation phase for phase in ['train', 'val']: if phase == 'train': model.train() # Set model to training mode else: model.eval() # Set model to evaluate mode running_loss = 0.0 running_corrects = 0 # Iterate over data. for inputs, labels in dataloaders[phase]: inputs = inputs.to(device) labels = labels.to(device) # zero the parameter gradients optimizer.zero_grad() # forward # track history if only in train with torch.set_grad_enabled(phase == 'train'): outputs = model(inputs) preds = torch.argmax(input = outputs, dim = 1) loss = criterion(outputs, labels) # backward + optimize only if in training phase if phase == 'train': loss.backward() optimizer.step() # statistics running_loss += loss.item() * inputs.size(0) running_corrects += torch.sum(preds == torch.argmax(input = labels, dim = 1)) if phase == 'train': scheduler.step() epoch_loss = running_loss / dataset_sizes[phase] epoch_acc = running_corrects.double() / dataset_sizes[phase] print('{} Loss: {:.4f} Acc: {:.4f}'.format( phase, epoch_loss, epoch_acc)) # deep copy the model if phase == 'val' and epoch_acc > best_acc: best_acc = epoch_acc best_model_wts = copy.deepcopy(model.state_dict()) elif phase == 'val' and epoch_acc < best_acc: stp = int((9-M)*((best_acc-epoch_acc)/best_acc)) M += max(1,stp) M = min(M, max_M) if M < max_M: print("Augmentaion Magnitude Changed To : {}\n".format(M)) print('Best val Acc: {:4f}'.format(best_acc)) # load best model weights model.load_state_dict(best_model_wts) return model
The lines of code relevant to the schedule have been boldened in the above code block.
I use a predetermined schedule for M in this example, M is incremented whenever the epoch accuracy is lower than the best accuracy on the validation set. The amount that M will be incremented by is calculated by the difference between the maximum possible value(9) and the current value of M scaled by the ratio of the difference between both the accuracies and the best accuracy.
Note that this schedule incurs no extra cost however is very rigid, RandAugment paper uses a grid search for both N and M after every batch to find their optimal values. However, even with the drastic reduction of computaional cost compared to AutoAugment, grid search is still infeasable for someone with a modest setup and a single gpu for most machine learning projects.
The schedule used in this implementation is not the only available schedule, you can experiment with the number of transformations N per sub-policy and also with probabilities for those transformations p. Augmentation is not an exact science, every lock has a different key, you need to find the matching key through experimentation and creative thinking.
AutoAugment Paper: https://arxiv.org/abs/1805.09501
RandAugment Paper: https://arxiv.org/abs/1909.13719 | [
{
"code": null,
"e": 503,
"s": 171,
"text": "Ever since the Deep Neural Net's rise to fame in the late 1990s, limited data has been a stumbling block. Lack of data results in overfitting, especially for architectures with a lot of parameters. Luckily, augmentation has turned out to be a revelation for machine learning tasks with limited data. It offers two major advantages."
},
{
"code": null,
"e": 660,
"s": 503,
"text": "First, you can increase the amount of data by creating several augmented copies of your original dataset which can also be used to balance a skewed dataset."
},
{
"code": null,
"e": 835,
"s": 660,
"text": "Second, it forces the model to be invariant to non-relevant features in the samples, for example, background in a face detection task. This helps the model generalize better."
},
{
"code": null,
"e": 1128,
"s": 835,
"text": "In this post, we will explore the latest data augmentation methods and a novel implementation using the methods discussed. We’ll mainly be covering two methods, AutoAugment, and RandAugment. So, let’s start with a brief introduction to both the methods and then move on to the implementation."
},
{
"code": null,
"e": 1630,
"s": 1128,
"text": "AutoAugment introduced in “AutoAugment: Learning Augmentation Strategies from Data” attempts to automate choosing the type and magnitude of the transformations to apply to a sample. They propose a reinforcement learning method that finds an effective data augmentation policy by discretizing the search problem. The proposed method finds an augmentation policy S which has information on the transformations, the magnitudes of the transformations, and the probabilities of using those transformations."
},
{
"code": null,
"e": 1683,
"s": 1630,
"text": "Let us look at some of the details of the algorithm."
},
{
"code": null,
"e": 1835,
"s": 1683,
"text": "A policy S contains five sub-policies, each sub_policy has two transformations with each transformation having a magnitude and a probability parameter."
},
{
"code": null,
"e": 2002,
"s": 1835,
"text": "Note that the sub-policies here are sensitive to the sequence of the transformations and treated as a different sub-policy if the sequence of application is reversed."
},
{
"code": null,
"e": 2291,
"s": 2002,
"text": "There are 16 augmentation transformations that the controller can choose from (will be discussed in the implementation section). The range of the magnitude and the probability of application for each transformation has been discretized into 10 and 11 uniformly spaced values respectively."
},
{
"code": null,
"e": 2469,
"s": 2291,
"text": "The search algorithm has two components: a controller, which is a recurrent neural network(RNN), and the training algorithm, which is the Proximal Policy Optimization algorithm."
},
{
"code": null,
"e": 3001,
"s": 2469,
"text": "The controller (RNN) predicts an augmentation policy S from the search space, the predicted policy is then used to train a much smaller child model. The child model is trained on augmented data generated by applying the 5 predicted sub-policies on the training set. For each example in the mini-batch, one of the 5 sub-policies is chosen randomly to augment the image. The child model is then evaluated on a separate held-out validation set to measure the accuracy R, which is used as the reward signal to train the RNN controller."
},
{
"code": null,
"e": 3057,
"s": 3001,
"text": "You can read the entire paper here for all the details."
},
{
"code": null,
"e": 3709,
"s": 3057,
"text": "AutoAugment was one of the first papers to implement an automated approach to data augmentation effectively and showed substantially better results than previous automated approaches. However, the separate optimization procedure and the prohibitively large search space have a high computational cost. Moreover, the method makes a strong assumption that the result from a smaller network is transferable to a much larger network. This assumption, as it turns out, is not entirely true as pointed out in the RandAugment paper which proposes a much faster and in some situations better-performing method for data augmentation which we will discuss next."
},
{
"code": null,
"e": 4398,
"s": 3709,
"text": "Most learned augmentation algorithms like AutoAugment creates a proxy task that optimizes for the best augmentation policy on a smaller network, as discussed in the previous section this approach has some fundamental flaws which need to be addressed. RandAugment introduced in “RandAugment: Practical automated data augmentation with a reduced search space” attempts to circumvent this proxy task and also drastically reduce the search space to ease the computational load on the training procedure. The method reduces the number of parameters to two, N and M (which will be discussed in detail in the subsequent sub-section), and treats them as hyperparameters in the training procedure."
},
{
"code": null,
"e": 4929,
"s": 4398,
"text": "RandAugment instead of learning a policy picks a transformation randomly from a set of K transformations with a uniform probability of 1/K. The number of transformations to be picked is given by N which is a hyperparameter, this reduces the total policies in the search space to K pow N. The main benefit of the learned augmentation approach comes from increasing the diversity of the samples, uniform probability approach employed by RandAugment maintains the diversity of the samples but with significantly reduced search space."
},
{
"code": null,
"e": 5983,
"s": 4929,
"text": "Finally, the range of magnitude for each transformation similar to AutoAugment is discretized into 10 uniformly spaced values given by M, however, contrary to the learned approach all the transformations follow the same schedule for M which reduces the search space for magnitudes to just one. This is due to the fact that the optimal magnitude for augmentation depends on the size of the model and the training set, larger networks require larger data distortions(please refer to the image above) which intuitively makes sense. The paper also points out that larger datasets require larger data distortions which seems odd, one hypothesis that the authors put forward is that aggressive augmentation in small datasets might lead to a low signal-to-noise ratio. In any case, there is a clear pattern for optimal magnitude that all transformations follow based on the model size and training set size, this exposes a fundamental flaw in the learned augmentation approach which uses smaller networks to estimate transformation magnitude for all the tasks."
},
{
"code": null,
"e": 6375,
"s": 5983,
"text": "RandAugment uses a simple grid search to find optimal values for N and M, this is done by selecting a set of values for both the hyperparameters and testing all the permutations from those sets on a separate validation set. Finally, choosing the combination that gives the best improvement on the validation set. This procedure can be performed for every sample, every batch, or every epoch."
},
{
"code": null,
"e": 6688,
"s": 6375,
"text": "Now, that we have a fairly good understanding of the algorithms let us move towards the implementation. As discussed previously RandAugment is a much better algorithm, however, some key findings from the AutoAugment paper can be used in conjunction with RandAugment to reduce the computational cost even further."
},
{
"code": null,
"e": 7007,
"s": 6688,
"text": "You can download the notebook for this post from here, the notebook has all the necessary code to set up the augmentation algorithm and test it with Resnet50 on a small part of the Imagenet dataset provided by fastai. However, we will be only focusing on the part of the notebook relevant to augmentation in this post."
},
{
"code": null,
"e": 7107,
"s": 7007,
"text": "Let’s start by looking at the custom RandAugment function from the notebook and then break it down."
},
{
"code": null,
"e": 8598,
"s": 7107,
"text": "def randAugment(N, M, p, mode=\"all\", cut_out = False): # Magnitude(M) search space shift_x = np.linspace(0,150,10) shift_y = np.linspace(0,150,10) rot = np.linspace(0,30,10) shear = np.linspace(0,10,10) sola = np.linspace(0,256,10) post = [4,4,5,5,6,6,7,7,8,8] cont = [np.linspace(-0.8,-0.1,10),np.linspace(0.1,2,10)] bright = np.linspace(0.1,0.7,10) shar = np.linspace(0.1,0.9,10) cut = np.linspace(0,60,10) # Transformation search space Aug =[#0 - geometrical A.ShiftScaleRotate(shift_limit_x=shift_x[M], rotate_limit=0, shift_limit_y=0, shift_limit=shift_x[M], p=p), A.ShiftScaleRotate(shift_limit_y=shift_y[M], rotate_limit=0, shift_limit_x=0, shift_limit=shift_y[M], p=p), A.IAAAffine(rotate=rot[M], p=p), A.IAAAffine(shear=shear[M], p=p), A.InvertImg(p=p), #5 - Color Based A.Equalize(p=p), A.Solarize(threshold=sola[M], p=p), A.Posterize(num_bits=post[M], p=p), A.RandomContrast(limit=[cont[0][M], cont[1][M]], p=p), A.RandomBrightness(limit=bright[M], p=p), A.IAASharpen(alpha=shar[M], lightness=shar[M], p=p)] # Sampling from the Transformation search space if mode == \"geo\": ops = np.random.choice(Aug[0:5], N) elif mode == \"color\": ops = np.random.choice(Aug[5:], N) else: ops = np.random.choice(Aug, N) if cut_out: ops.append(A.Cutout(num_holes=8, max_h_size=int(cut[M]), max_w_size=int(cut[M]), p=p)) transforms = A.Compose(ops) return transforms, ops"
},
{
"code": null,
"e": 8667,
"s": 8598,
"text": "The function can roughly be divided into the following two sections."
},
{
"code": null,
"e": 8745,
"s": 8667,
"text": "This section discretizes the magnitude range into 10 uniformly spaced values."
},
{
"code": null,
"e": 8986,
"s": 8745,
"text": "“Aug” is the Transformation Search Space from which the algorithm can pick N transformations with uniform probability. Please take the time to see what these individual transformations do to get a better feel for creating this search space."
},
{
"code": null,
"e": 9353,
"s": 8986,
"text": "Note that the function has three modes “geo”, “color” and “all”. The “geo” mode is for tasks where color-based features define the object of interest in the image eg. fire detection. Similarly, the “color” mode is for tasks where the shape defines the object of interest eg. face detection, detecting a car, etc. Whereas, the “all” mode uses all the transformations."
},
{
"code": null,
"e": 9643,
"s": 9353,
"text": "The authors in the AutoAugment paper showed that different datasets were sensitive to different transformations in both positive and negative directions. Therefore, the “No Free Lunch” theorem applies in data augmentation as well and you will need to tweak the algorithm for every project."
},
{
"code": null,
"e": 10011,
"s": 9643,
"text": "Note that the magnitude ranges given in the table above are for functions from the PIL library, however, we are using Albumentaions in the randAugment() function, mainly because Albumentaions library uses open cv which is faster compared to PIL. You would have to experiment and figure out the magnitude range for each transformation for the library you like to use ."
},
{
"code": null,
"e": 10100,
"s": 10011,
"text": "Let’s now look at the schedule for the magnitude of the transformations during training."
},
{
"code": null,
"e": 12785,
"s": 10100,
"text": "def train_model(model, criterion, optimizer, scheduler, aug_mode=\"all\", cut_out=False, max_M=9, num_epochs=25): best_model_wts = copy.deepcopy(model.state_dict()) best_acc = 0.0 N=2;M=0;p=0.5 for epoch in range(num_epochs): print('Epoch {}/{}'.format(epoch, num_epochs - 1)) print('-' * 10) transforms, ops = randAugment(N=N, M=M, p=p, mode=aug_mode, cut_out=cut_out) dataloaders, dataset_sizes = create_dataloaders(root, train_df, valid_df, label_dict, bs=32, transforms=transforms) # Each epoch has a training and validation phase for phase in ['train', 'val']: if phase == 'train': model.train() # Set model to training mode else: model.eval() # Set model to evaluate mode running_loss = 0.0 running_corrects = 0 # Iterate over data. for inputs, labels in dataloaders[phase]: inputs = inputs.to(device) labels = labels.to(device) # zero the parameter gradients optimizer.zero_grad() # forward # track history if only in train with torch.set_grad_enabled(phase == 'train'): outputs = model(inputs) preds = torch.argmax(input = outputs, dim = 1) loss = criterion(outputs, labels) # backward + optimize only if in training phase if phase == 'train': loss.backward() optimizer.step() # statistics running_loss += loss.item() * inputs.size(0) running_corrects += torch.sum(preds == torch.argmax(input = labels, dim = 1)) if phase == 'train': scheduler.step() epoch_loss = running_loss / dataset_sizes[phase] epoch_acc = running_corrects.double() / dataset_sizes[phase] print('{} Loss: {:.4f} Acc: {:.4f}'.format( phase, epoch_loss, epoch_acc)) # deep copy the model if phase == 'val' and epoch_acc > best_acc: best_acc = epoch_acc best_model_wts = copy.deepcopy(model.state_dict()) elif phase == 'val' and epoch_acc < best_acc: stp = int((9-M)*((best_acc-epoch_acc)/best_acc)) M += max(1,stp) M = min(M, max_M) if M < max_M: print(\"Augmentaion Magnitude Changed To : {}\\n\".format(M)) print('Best val Acc: {:4f}'.format(best_acc)) # load best model weights model.load_state_dict(best_model_wts) return model"
},
{
"code": null,
"e": 12872,
"s": 12785,
"text": "The lines of code relevant to the schedule have been boldened in the above code block."
},
{
"code": null,
"e": 13253,
"s": 12872,
"text": "I use a predetermined schedule for M in this example, M is incremented whenever the epoch accuracy is lower than the best accuracy on the validation set. The amount that M will be incremented by is calculated by the difference between the maximum possible value(9) and the current value of M scaled by the ratio of the difference between both the accuracies and the best accuracy."
},
{
"code": null,
"e": 13627,
"s": 13253,
"text": "Note that this schedule incurs no extra cost however is very rigid, RandAugment paper uses a grid search for both N and M after every batch to find their optimal values. However, even with the drastic reduction of computaional cost compared to AutoAugment, grid search is still infeasable for someone with a modest setup and a single gpu for most machine learning projects."
},
{
"code": null,
"e": 13983,
"s": 13627,
"text": "The schedule used in this implementation is not the only available schedule, you can experiment with the number of transformations N per sub-policy and also with probabilities for those transformations p. Augmentation is not an exact science, every lock has a different key, you need to find the matching key through experimentation and creative thinking."
},
{
"code": null,
"e": 14035,
"s": 13983,
"text": "AutoAugment Paper: https://arxiv.org/abs/1805.09501"
}
] |
Find all combinations that add upto given number using C++ | Suppose we have a positive number n. We have to find all combinations of positive numbers, that adds up to that number. Here we want only combinations, not the permutations. For the value n = 4, there will be [1, 1, 1, 1], [1, 1, 2], [2, 2], [1, 3], [4]
We will solve this using recursion. We have an array to store combinations, and we will fill that array using recursive approach. Each combination will be stored in increasing order of elements.
#include<iostream>
using namespace std;
void getCombination(int arr[], int index, int num, int decrement) {
if (decrement < 0)
return;
if (decrement == 0){
for (int i = 0; i < index; i++)
cout << arr[i] << " ";
cout << endl;
return;
}
int prev;
if(index == 0)
prev = 1;
else
prev = arr[index-1];
for (int k = prev; k <= num ; k++) {
arr[index] = k;
getCombination(arr, index + 1, num, decrement - k);
}
}
void findCombinations(int n) {
int arr[n];
getCombination(arr, 0, n, n);
}
int main() {
int n = 4;
findCombinations(n);
}
1 1 1 1
1 1 2
1 3
2 2
4 | [
{
"code": null,
"e": 1316,
"s": 1062,
"text": "Suppose we have a positive number n. We have to find all combinations of positive numbers, that adds up to that number. Here we want only combinations, not the permutations. For the value n = 4, there will be [1, 1, 1, 1], [1, 1, 2], [2, 2], [1, 3], [4]"
},
{
"code": null,
"e": 1511,
"s": 1316,
"text": "We will solve this using recursion. We have an array to store combinations, and we will fill that array using recursive approach. Each combination will be stored in increasing order of elements."
},
{
"code": null,
"e": 2134,
"s": 1511,
"text": "#include<iostream>\nusing namespace std;\nvoid getCombination(int arr[], int index, int num, int decrement) {\n if (decrement < 0)\n return;\n if (decrement == 0){\n for (int i = 0; i < index; i++)\n cout << arr[i] << \" \";\n cout << endl;\n return;\n }\n int prev;\n if(index == 0)\n prev = 1;\n else\n prev = arr[index-1];\n for (int k = prev; k <= num ; k++) {\n arr[index] = k;\n getCombination(arr, index + 1, num, decrement - k);\n }\n}\nvoid findCombinations(int n) {\n int arr[n];\n getCombination(arr, 0, n, n);\n}\nint main() {\n int n = 4;\n findCombinations(n);\n}"
},
{
"code": null,
"e": 2158,
"s": 2134,
"text": "1 1 1 1\n1 1 2\n1 3\n2 2\n4"
}
] |
Swift - Generics | Swift 4 language provides 'Generic' features to write flexible and reusable functions and types. Generics are used to avoid duplication and to provide abstraction. Swift 4 standard libraries are built with generics code. Swift 4s 'Arrays' and 'Dictionary' types belong to generic collections. With the help of arrays and dictionaries the arrays are defined to hold 'Int' values and 'String' values or any other types.
func exchange(a: inout Int, b: inout Int) {
let temp = a
a = b
b = temp
}
var numb1 = 100
var numb2 = 200
print("Before Swapping values are: \(numb1) and \(numb2)")
exchange(a: &numb1, b: &numb2)
print("After Swapping values are: \(numb1) and \(numb2)")
When we run the above program using playground, we get the following result −
Before Swapping values are: 100 and 200
After Swapping values are: 200 and 100
Generic functions can be used to access any data type like 'Int' or 'String'.
func exchange<T>(a: inout T, b: inout T) {
let temp = a
a = b
b = temp
}
var numb1 = 100
var numb2 = 200
print("Before Swapping Int values are: \(numb1) and \(numb2)")
exchange(a: &numb1, b: &numb2)
print("After Swapping Int values are: \(numb1) and \(numb2)")
var str1 = "Generics"
var str2 = "Functions"
print("Before Swapping String values are: \(str1) and \(str2)")
exchange(a: &str1, b: &str2)
print("After Swapping String values are: \(str1) and \(str2)")
When we run the above program using playground, we get the following result −
Before Swapping Int values are: 100 and 200
After Swapping Int values are: 200 and 100
Before Swapping String values are: Generics and Functions
After Swapping String values are: Functions and Generics
The function exchange() is used to swap values which is described in the above program and <T> is used as a type parameter. For the first time, function exchange() is called to return 'Int' values and second call to the function exchange() will return 'String' values. Multiple parameter types can be included inside the angle brackets separated by commas.
Type parameters are named as user defined to know the purpose of the type parameter that it holds. Swift 4 provides <T> as generic type parameter name. However type parameters like Arrays and Dictionaries can also be named as key, value to identify that they belong to type 'Dictionary'.
struct TOS<T> {
var items = [T]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
}
var tos = TOS<String>()
tos.push(item: "Swift 4")
print(tos.items)
tos.push(item: "Generics")
print(tos.items)
tos.push(item: "Type Parameters")
print(tos.items)
tos.push(item: "Naming Type Parameters")
print(tos.items)
let deletetos = tos.pop()
When we run the above program using playground, we get the following result −
[Swift 4]
[Swift 4, Generics]
[Swift 4, Generics, Type Parameters]
[Swift 4, Generics, Type Parameters, Naming Type Parameters]
Extending the stack property to know the top of the item is included with 'extension' keyword.
struct TOS<T> {
var items = [T]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
}
var tos = TOS<String>()
tos.push(item: "Swift 4")
print(tos.items)
tos.push(item: "Generics")
print(tos.items)
tos.push(item: "Type Parameters")
print(tos.items)
tos.push(item: "Naming Type Parameters")
print(tos.items)
extension TOS {
var first: T? {
return items.isEmpty ? nil : items[items.count - 1]
}
}
if let first = tos.first {
print("The top item on the stack is \(first).")
}
When we run the above program using playground, we get the following result −
["Swift 4"]
["Swift 4", "Generics"]
["Swift 4", "Generics", "Type Parameters"]
["Swift 4", "Generics", "Type Parameters", "Naming Type Parameters"]
The top item on the stack is Naming Type Parameters.
Swift 4 language allows 'type constraints' to specify whether the type parameter inherits from a specific class, or to ensure protocol conformance standard.
func exchange<T>(a: inout T, b: inout T) {
let temp = a
a = b
b = temp
}
var numb1 = 100
var numb2 = 200
print("Before Swapping Int values are: \(numb1) and \(numb2)")
exchange(a: &numb1, b: &numb2)
print("After Swapping Int values are: \(numb1) and \(numb2)")
var str1 = "Generics"
var str2 = "Functions"
print("Before Swapping String values are: \(str1) and \(str2)")
exchange(a: &str1, b: &str2)
print("After Swapping String values are: \(str1) and \(str2)")
When we run the above program using playground, we get the following result −
Before Swapping Int values are: 100 and 200
After Swapping Int values are: 200 and 100
Before Swapping String values are: Generics and Functions
After Swapping String values are: Functions and Generics
Swift 4 allows associated types to be declared inside the protocol definition by the keyword 'associatedtype'.
protocol Container {
associatedtype ItemType
mutating func append(item: ItemType)
var count: Int { get }
subscript(i: Int) -> ItemType { get }
}
struct TOS<T>: Container {
// original Stack<T> implementation
var items = [T]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
// conformance to the Container protocol
mutating func append(item: T) {
self.push(item: item)
}
var count: Int {
return items.count
}
subscript(i: Int) -> T {
return items[i]
}
}
var tos = TOS<String>()
tos.push(item: "Swift 4")
print(tos.items)
tos.push(item: "Generics")
print(tos.items)
tos.push(item: "Type Parameters")
print(tos.items)
tos.push(item: "Naming Type Parameters")
print(tos.items)
When we run the above program using playground, we get the following result −
[Swift 4]
[Swift 4, Generics]
[Swift 4, Generics, Type Parameters]
[Swift 4, Generics, Type Parameters, Naming Type Parameters]
Type constraints enable the user to define requirements on the type parameters associated with a generic function or type. For defining requirements for associated types 'where' clauses are declared as part of type parameter list. 'where' keyword is placed immediately after the list of type parameters followed by constraints of associated types, equality relationships between types and associated types.
protocol Container {
associatedtype ItemType
mutating func append(item: ItemType)
var count: Int { get }
subscript(i: Int) -> ItemType { get }
}
struct Stack<T>: Container {
// original Stack<T> implementation
var items = [T]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
// conformance to the Container protocol
mutating func append(item: T) {
self.push(item: item)
}
var count: Int {
return items.count
}
subscript(i: Int) -> T {
return items[i]
}
}
func allItemsMatch<
C1: Container, C2: Container
where C1.ItemType == C2.ItemType, C1.ItemType: Equatable>
(someContainer: C1, anotherContainer: C2) -> Bool {
// check that both containers contain the same number of items
if someContainer.count != anotherContainer.count {
return false
}
// check each pair of items to see if they are equivalent
for i in 0..<someContainer.count {
if someContainer[i] != anotherContainer[i] {
return false
}
}
// all items match, so return true
return true
}
var tos = Stack<String>()
tos.push(item: "Swift 4")
print(tos.items)
tos.push(item: "Generics")
print(tos.items)
tos.push(item: "Where Clause")
print(tos.items)
var eos = ["Swift 4", "Generics", "Where Clause"]
print(eos)
When we run the above program using playground, we get the following result −
[Swift 4]
[Swift 4, Generics]
[Swift 4, Generics, Where Clause]
[Swift 4, Generics, Where Clause]
38 Lectures
1 hours
Ashish Sharma
13 Lectures
2 hours
Three Millennials
7 Lectures
1 hours
Three Millennials
22 Lectures
1 hours
Frahaan Hussain
12 Lectures
39 mins
Devasena Rajendran
40 Lectures
2.5 hours
Grant Klimaytys
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2671,
"s": 2253,
"text": "Swift 4 language provides 'Generic' features to write flexible and reusable functions and types. Generics are used to avoid duplication and to provide abstraction. Swift 4 standard libraries are built with generics code. Swift 4s 'Arrays' and 'Dictionary' types belong to generic collections. With the help of arrays and dictionaries the arrays are defined to hold 'Int' values and 'String' values or any other types."
},
{
"code": null,
"e": 2936,
"s": 2671,
"text": "func exchange(a: inout Int, b: inout Int) {\n let temp = a\n a = b\n b = temp\n}\n\nvar numb1 = 100\nvar numb2 = 200\n\nprint(\"Before Swapping values are: \\(numb1) and \\(numb2)\")\nexchange(a: &numb1, b: &numb2)\nprint(\"After Swapping values are: \\(numb1) and \\(numb2)\")"
},
{
"code": null,
"e": 3014,
"s": 2936,
"text": "When we run the above program using playground, we get the following result −"
},
{
"code": null,
"e": 3094,
"s": 3014,
"text": "Before Swapping values are: 100 and 200\nAfter Swapping values are: 200 and 100\n"
},
{
"code": null,
"e": 3172,
"s": 3094,
"text": "Generic functions can be used to access any data type like 'Int' or 'String'."
},
{
"code": null,
"e": 3646,
"s": 3172,
"text": "func exchange<T>(a: inout T, b: inout T) {\n let temp = a\n a = b\n b = temp\n}\nvar numb1 = 100\nvar numb2 = 200\n\nprint(\"Before Swapping Int values are: \\(numb1) and \\(numb2)\")\nexchange(a: &numb1, b: &numb2)\nprint(\"After Swapping Int values are: \\(numb1) and \\(numb2)\")\n\nvar str1 = \"Generics\"\nvar str2 = \"Functions\"\n\nprint(\"Before Swapping String values are: \\(str1) and \\(str2)\")\nexchange(a: &str1, b: &str2)\nprint(\"After Swapping String values are: \\(str1) and \\(str2)\")"
},
{
"code": null,
"e": 3724,
"s": 3646,
"text": "When we run the above program using playground, we get the following result −"
},
{
"code": null,
"e": 3927,
"s": 3724,
"text": "Before Swapping Int values are: 100 and 200\nAfter Swapping Int values are: 200 and 100\nBefore Swapping String values are: Generics and Functions\nAfter Swapping String values are: Functions and Generics\n"
},
{
"code": null,
"e": 4284,
"s": 3927,
"text": "The function exchange() is used to swap values which is described in the above program and <T> is used as a type parameter. For the first time, function exchange() is called to return 'Int' values and second call to the function exchange() will return 'String' values. Multiple parameter types can be included inside the angle brackets separated by commas."
},
{
"code": null,
"e": 4572,
"s": 4284,
"text": "Type parameters are named as user defined to know the purpose of the type parameter that it holds. Swift 4 provides <T> as generic type parameter name. However type parameters like Arrays and Dictionaries can also be named as key, value to identify that they belong to type 'Dictionary'."
},
{
"code": null,
"e": 4992,
"s": 4572,
"text": "struct TOS<T> {\n var items = [T]()\n mutating func push(item: T) {\n items.append(item)\n }\n mutating func pop() -> T {\n return items.removeLast()\n }\n}\n\nvar tos = TOS<String>()\ntos.push(item: \"Swift 4\")\nprint(tos.items)\n\ntos.push(item: \"Generics\")\nprint(tos.items)\n\ntos.push(item: \"Type Parameters\")\nprint(tos.items)\n\ntos.push(item: \"Naming Type Parameters\")\nprint(tos.items)\n\nlet deletetos = tos.pop()"
},
{
"code": null,
"e": 5070,
"s": 4992,
"text": "When we run the above program using playground, we get the following result −"
},
{
"code": null,
"e": 5199,
"s": 5070,
"text": "[Swift 4]\n[Swift 4, Generics]\n[Swift 4, Generics, Type Parameters]\n[Swift 4, Generics, Type Parameters, Naming Type Parameters]\n"
},
{
"code": null,
"e": 5294,
"s": 5199,
"text": "Extending the stack property to know the top of the item is included with 'extension' keyword."
},
{
"code": null,
"e": 5867,
"s": 5294,
"text": "struct TOS<T> {\n var items = [T]()\n mutating func push(item: T) {\n items.append(item)\n }\n mutating func pop() -> T {\n return items.removeLast()\n }\n}\nvar tos = TOS<String>()\ntos.push(item: \"Swift 4\")\nprint(tos.items)\n\ntos.push(item: \"Generics\")\nprint(tos.items)\n\ntos.push(item: \"Type Parameters\")\nprint(tos.items)\n\ntos.push(item: \"Naming Type Parameters\")\nprint(tos.items)\n\nextension TOS {\n var first: T? {\n return items.isEmpty ? nil : items[items.count - 1]\n }\n}\nif let first = tos.first {\n print(\"The top item on the stack is \\(first).\")\n}"
},
{
"code": null,
"e": 5945,
"s": 5867,
"text": "When we run the above program using playground, we get the following result −"
},
{
"code": null,
"e": 6147,
"s": 5945,
"text": "[\"Swift 4\"]\n[\"Swift 4\", \"Generics\"]\n[\"Swift 4\", \"Generics\", \"Type Parameters\"]\n[\"Swift 4\", \"Generics\", \"Type Parameters\", \"Naming Type Parameters\"]\nThe top item on the stack is Naming Type Parameters.\n"
},
{
"code": null,
"e": 6304,
"s": 6147,
"text": "Swift 4 language allows 'type constraints' to specify whether the type parameter inherits from a specific class, or to ensure protocol conformance standard."
},
{
"code": null,
"e": 6778,
"s": 6304,
"text": "func exchange<T>(a: inout T, b: inout T) {\n let temp = a\n a = b\n b = temp\n}\nvar numb1 = 100\nvar numb2 = 200\n\nprint(\"Before Swapping Int values are: \\(numb1) and \\(numb2)\")\nexchange(a: &numb1, b: &numb2)\nprint(\"After Swapping Int values are: \\(numb1) and \\(numb2)\")\n\nvar str1 = \"Generics\"\nvar str2 = \"Functions\"\n\nprint(\"Before Swapping String values are: \\(str1) and \\(str2)\")\nexchange(a: &str1, b: &str2)\nprint(\"After Swapping String values are: \\(str1) and \\(str2)\")"
},
{
"code": null,
"e": 6856,
"s": 6778,
"text": "When we run the above program using playground, we get the following result −"
},
{
"code": null,
"e": 7059,
"s": 6856,
"text": "Before Swapping Int values are: 100 and 200\nAfter Swapping Int values are: 200 and 100\nBefore Swapping String values are: Generics and Functions\nAfter Swapping String values are: Functions and Generics\n"
},
{
"code": null,
"e": 7170,
"s": 7059,
"text": "Swift 4 allows associated types to be declared inside the protocol definition by the keyword 'associatedtype'."
},
{
"code": null,
"e": 7990,
"s": 7170,
"text": "protocol Container {\n associatedtype ItemType\n mutating func append(item: ItemType)\n var count: Int { get }\n subscript(i: Int) -> ItemType { get }\n}\nstruct TOS<T>: Container {\n // original Stack<T> implementation\n var items = [T]()\n mutating func push(item: T) {\n items.append(item)\n }\n mutating func pop() -> T {\n return items.removeLast()\n }\n \n // conformance to the Container protocol\n mutating func append(item: T) {\n self.push(item: item)\n }\n var count: Int {\n return items.count\n }\n subscript(i: Int) -> T {\n return items[i]\n }\n}\nvar tos = TOS<String>()\ntos.push(item: \"Swift 4\")\nprint(tos.items)\n\ntos.push(item: \"Generics\")\nprint(tos.items)\n\ntos.push(item: \"Type Parameters\")\nprint(tos.items)\n\ntos.push(item: \"Naming Type Parameters\")\nprint(tos.items)"
},
{
"code": null,
"e": 8068,
"s": 7990,
"text": "When we run the above program using playground, we get the following result −"
},
{
"code": null,
"e": 8197,
"s": 8068,
"text": "[Swift 4]\n[Swift 4, Generics]\n[Swift 4, Generics, Type Parameters]\n[Swift 4, Generics, Type Parameters, Naming Type Parameters]\n"
},
{
"code": null,
"e": 8604,
"s": 8197,
"text": "Type constraints enable the user to define requirements on the type parameters associated with a generic function or type. For defining requirements for associated types 'where' clauses are declared as part of type parameter list. 'where' keyword is placed immediately after the list of type parameters followed by constraints of associated types, equality relationships between types and associated types."
},
{
"code": null,
"e": 9975,
"s": 8604,
"text": "protocol Container {\n associatedtype ItemType\n mutating func append(item: ItemType)\n var count: Int { get }\n subscript(i: Int) -> ItemType { get }\n}\nstruct Stack<T>: Container {\n // original Stack<T> implementation\n var items = [T]()\n mutating func push(item: T) {\n items.append(item)\n }\n mutating func pop() -> T {\n return items.removeLast()\n }\n\n // conformance to the Container protocol\n mutating func append(item: T) {\n self.push(item: item)\n }\n var count: Int {\n return items.count\n }\n subscript(i: Int) -> T {\n return items[i]\n }\n}\nfunc allItemsMatch<\nC1: Container, C2: Container\nwhere C1.ItemType == C2.ItemType, C1.ItemType: Equatable>\n(someContainer: C1, anotherContainer: C2) -> Bool {\n // check that both containers contain the same number of items\n if someContainer.count != anotherContainer.count {\n return false\n }\n \n // check each pair of items to see if they are equivalent\n for i in 0..<someContainer.count {\n if someContainer[i] != anotherContainer[i] {\n return false\n }\n }\n // all items match, so return true\n return true\n} \nvar tos = Stack<String>()\n\ntos.push(item: \"Swift 4\")\nprint(tos.items)\n\ntos.push(item: \"Generics\")\nprint(tos.items)\n\ntos.push(item: \"Where Clause\")\nprint(tos.items)\n\nvar eos = [\"Swift 4\", \"Generics\", \"Where Clause\"]\nprint(eos)"
},
{
"code": null,
"e": 10053,
"s": 9975,
"text": "When we run the above program using playground, we get the following result −"
},
{
"code": null,
"e": 10152,
"s": 10053,
"text": "[Swift 4]\n[Swift 4, Generics]\n[Swift 4, Generics, Where Clause]\n[Swift 4, Generics, Where Clause]\n"
},
{
"code": null,
"e": 10185,
"s": 10152,
"text": "\n 38 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10200,
"s": 10185,
"text": " Ashish Sharma"
},
{
"code": null,
"e": 10233,
"s": 10200,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 10252,
"s": 10233,
"text": " Three Millennials"
},
{
"code": null,
"e": 10284,
"s": 10252,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10303,
"s": 10284,
"text": " Three Millennials"
},
{
"code": null,
"e": 10336,
"s": 10303,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10353,
"s": 10336,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 10385,
"s": 10353,
"text": "\n 12 Lectures \n 39 mins\n"
},
{
"code": null,
"e": 10405,
"s": 10385,
"text": " Devasena Rajendran"
},
{
"code": null,
"e": 10440,
"s": 10405,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 10457,
"s": 10440,
"text": " Grant Klimaytys"
},
{
"code": null,
"e": 10464,
"s": 10457,
"text": " Print"
},
{
"code": null,
"e": 10475,
"s": 10464,
"text": " Add Notes"
}
] |
Convert BST to Max Heap in C++ | In this tutorial, we will be discussing a program to convert a binary search tree to a max heap.
For this we will be provided with a binary search tree. Our task is to convert the given binary search tree into a max heap such that following the condition of the binary search tree when elements are compared with themselves.
Live Demo
#include <bits/stdc++.h>
using namespace std;
//node structure of BST
struct Node {
int data;
Node *left, *right;
};
//node creation
struct Node* getNode(int data) {
struct Node* newNode = new Node;
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
//performing post order traversal
void postorderTraversal(Node*);
//moving in a sorted manner using inorder traversal
void inorderTraversal(Node* root, vector<int>& arr) {
if (root == NULL)
return;
inorderTraversal(root->left, arr);
arr.push_back(root->data);
inorderTraversal(root->right, arr);
}
void convert_BSTHeap(Node* root, vector<int> arr, int* i){
if (root == NULL)
return;
convert_BSTHeap(root->left, arr, i);
convert_BSTHeap(root->right, arr, i);
//copying data from array to node
root->data = arr[++*i];
}
//converting to max heap
void convert_maxheap(Node* root) {
vector<int> arr;
int i = -1;
inorderTraversal(root, arr);
convert_BSTHeap(root, arr, &i);
}
//printing post order traversal
void postorderTraversal(Node* root) {
if (!root)
return;
postorderTraversal(root->left);
postorderTraversal(root->right);
cout << root->data << " ";
}
int main() {
struct Node* root = getNode(4);
root->left = getNode(2);
root->right = getNode(6);
root->left->left = getNode(1);
root->left->right = getNode(3);
root->right->left = getNode(5);
root->right->right = getNode(7);
convert_maxheap(root);
cout << "Postorder Traversal:" << endl;
postorderTraversal(root);
return 0;
}
Postorder Traversal:
1 2 3 4 5 6 7 | [
{
"code": null,
"e": 1159,
"s": 1062,
"text": "In this tutorial, we will be discussing a program to convert a binary search tree to a max heap."
},
{
"code": null,
"e": 1387,
"s": 1159,
"text": "For this we will be provided with a binary search tree. Our task is to convert the given binary search tree into a max heap such that following the condition of the binary search tree when elements are compared with themselves."
},
{
"code": null,
"e": 1398,
"s": 1387,
"text": " Live Demo"
},
{
"code": null,
"e": 2974,
"s": 1398,
"text": "#include <bits/stdc++.h>\nusing namespace std;\n//node structure of BST\nstruct Node {\n int data;\n Node *left, *right;\n};\n//node creation\nstruct Node* getNode(int data) {\n struct Node* newNode = new Node;\n newNode->data = data;\n newNode->left = newNode->right = NULL;\n return newNode;\n}\n//performing post order traversal\nvoid postorderTraversal(Node*);\n//moving in a sorted manner using inorder traversal\nvoid inorderTraversal(Node* root, vector<int>& arr) {\n if (root == NULL)\n return;\n inorderTraversal(root->left, arr);\n arr.push_back(root->data);\n inorderTraversal(root->right, arr);\n}\nvoid convert_BSTHeap(Node* root, vector<int> arr, int* i){\n if (root == NULL)\n return;\n convert_BSTHeap(root->left, arr, i);\n convert_BSTHeap(root->right, arr, i);\n //copying data from array to node\n root->data = arr[++*i];\n}\n//converting to max heap\nvoid convert_maxheap(Node* root) {\n vector<int> arr;\n int i = -1;\n inorderTraversal(root, arr);\n convert_BSTHeap(root, arr, &i);\n}\n//printing post order traversal\nvoid postorderTraversal(Node* root) {\n if (!root)\n return;\n postorderTraversal(root->left);\n postorderTraversal(root->right);\n cout << root->data << \" \";\n}\nint main() {\n struct Node* root = getNode(4);\n root->left = getNode(2);\n root->right = getNode(6);\n root->left->left = getNode(1);\n root->left->right = getNode(3);\n root->right->left = getNode(5);\n root->right->right = getNode(7);\n convert_maxheap(root);\n cout << \"Postorder Traversal:\" << endl;\n postorderTraversal(root);\n return 0;\n}"
},
{
"code": null,
"e": 3009,
"s": 2974,
"text": "Postorder Traversal:\n1 2 3 4 5 6 7"
}
] |
How to add empty border to JPanel in Java? | To add empty border, use the createEmtyBorder() method. Let us first create a new JLabel −
JLabel label;
label = new JLabel("Label with empty border!");
Now, set empty border using the setBorder() method −
label.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
The following is an example to add empty border to JPanel −
package my;
import javax.swing.BorderFactory;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class SwingDemo {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Demo");
JLabel label;
label = new JLabel("Label with empty border!");
label.setFont(new Font("Verdana", Font.PLAIN, 16));
label.setVerticalAlignment(JLabel.BOTTOM);
label.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
frame.add(label);
frame.setSize(550,350);
frame.setVisible(true);
}
} | [
{
"code": null,
"e": 1153,
"s": 1062,
"text": "To add empty border, use the createEmtyBorder() method. Let us first create a new JLabel −"
},
{
"code": null,
"e": 1216,
"s": 1153,
"text": "JLabel label;\n\nlabel = new JLabel(\"Label with empty border!\");"
},
{
"code": null,
"e": 1269,
"s": 1216,
"text": "Now, set empty border using the setBorder() method −"
},
{
"code": null,
"e": 1335,
"s": 1269,
"text": "label.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));"
},
{
"code": null,
"e": 1395,
"s": 1335,
"text": "The following is an example to add empty border to JPanel −"
},
{
"code": null,
"e": 1988,
"s": 1395,
"text": "package my;\nimport javax.swing.BorderFactory;\nimport java.awt.Font;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\npublic class SwingDemo {\n public static void main(String[] args) throws Exception {\n JFrame frame = new JFrame(\"Demo\");\n JLabel label;\n label = new JLabel(\"Label with empty border!\");\n label.setFont(new Font(\"Verdana\", Font.PLAIN, 16));\n label.setVerticalAlignment(JLabel.BOTTOM);\n label.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));\n frame.add(label);\n frame.setSize(550,350);\n frame.setVisible(true);\n }\n}"
}
] |
An Easy Way to Get Started with Databases on Your Own Computer | by Byron Dolon | Towards Data Science | SQL is the third most popular language for developers, based on the StackOverflow 2020 Developer Survey. Everyone knows that you should learn to use SQL, but what about actually creating and managing a database?
While you can follow courses that let you play with SQL on a browser with predefined tables (which is not a bad way to learn), it’s also valuable to experience creating, managing, and interacting with a database of your own.
The DB Browser for SQLite (DB4S) is a tool that makes relational databases accessible to anyone. It allows you to interact with an SQLite database, the entirety of which is contained in a single file. No servers or extensive configuration are needed to get it running. Both DB4S and SQLite are free!
If you don’t have any experience working with databases or SQL, this is a tool that will help you get up to speed with the fundamentals. The DB4S has a spreadsheet-like interface similar to Excel, which means that you can create and edit tables in your own database without using SQL. You also have the option to write custom SQL queries and view the results.
Using the DB4S is a great way to get your hands dirty creating and working with relational databases. This piece will get you started with using the tool. The walkthrough is broken down into 7 parts:
Installation and setup on your own machineCreating a database fileImporting and exporting tables with CSV filesAdding, modifying and deleting rows (records) and columnsSearching and filtering recordsRunning SQL queriesVisualizing data with graphs or SQL queries
Installation and setup on your own machine
Creating a database file
Importing and exporting tables with CSV files
Adding, modifying and deleting rows (records) and columns
Searching and filtering records
Running SQL queries
Visualizing data with graphs or SQL queries
You can check out the installation details on the DB4S website here. You can download the latest versions for both Windows and macOS. It’s also available for Linux based distributions.
If you have Homebrew on macOS, you can also install the latest release with this line:
brew cask install db-browser-for-sqlite
Once you’ve gotten DB4S installed on your machine, open the application and you’re ready to begin!
When you open DB4S, on the top left you see a button labeled “New Database”. Click on it, type out a name for your database, and hit “Save” to your desired folder.
That’s it! You’ve created your first SQL database. You should now see this:
Now let’s create our first table. To do so, we’re going to import a CSV file with metadata for pieces featured on Medium’s popular page. I got the data in an earlier Python project that you can check out here.
The CSV looks like this:
To create a table with this file, on DB4S, you do:
File > Import > Table from CSV file...
After that, select your desired CSV file and hit “Open”.
This will prompt another window for a couple of customization options. Change the name to something that’s easy to remember. If the column headers are already in the first line of your CSV file, tick the box to make sure DB4S recognizes that. It will shift the first row to become the column names. Then hit “Ok”.
And boom! You’ve created your first table.
Exporting the database file to CSV is just as easy. All you have to do is right-click on the table and click “Export as CSV file”.
Or to bulk export more than one table, do this:
File > Export > Table(s) as CSV file...
Now let’s take a look at our table on DB4S. Right-click the table and select “Browse Table”.
You will now see the table in a classic spreadsheet-like format.
If you want to add a new row, just click “New Record”, and DB4S will create a new row (already with a primary key) for you to fill in with values, just like you would on Excel. In this case, we may want to do so every time a new piece is added to Medium’s popular page. DB4S will even suggest a row value based on the first letters you type in if the value already exists in the database.
To delete a row, you just need to select a row (click on a primary key on the leftmost column) and then click “Delete Record”.
Once you’re done with all your changes, click “Write Changes” to save all your modifications and update the table in your database.
Now on the table, you can see there’s a column called “field1”. This is because my CSV extract already included an index column. As DB4S automatically creates an index, I don’t need this column anymore.
Writing SQLite queries will allow you to make some table schema changes, but there is no one line “DROP COLUMN” feature available. The SQLite docs will give you a workaround for how to drop a column, which involves creating a new table with only the desired columns, copying the data from the old table to the new table, and deleting the old table.
In DB4S, dropping a column is a lot simpler. To delete a column, in the Database Structure tab, right-click on your desired table and click “Modify Table”.
You will see a list of columns currently in your table. Select the column you would like to delete, then click “Remove field” and “Yes”.
If we go back to “Browse Table”, we’ll see that “field1” is no longer in the table.
Earlier, we added a record with the author “Dana G Smith”. If we wanted to look for all articles published by Dana in the table, we just need to write the name in the “Filter” box under “Author”.
You can also add filter by more than one column at a time. If we wanted to find all articles in 2019 that had an 11 minute read time, you would just need to fill in two of the filter columns. The table would refresh automatically to show you just the results you need.
You can run all kinds of SQLite queries via the “Execute SQL” tab. For example, if we wanted to see all articles with a reading time of 5, just typing “5” in the filter column like we did earlier would show some unwanted results. In this case, we’ll also get articles that have a reading time of “15”.
To fix this, we’ll write a basic SQL query that filters results to only have a reading time of 5.
SELECT * FROM popular_metadata WHERE "ReadingTime(mins)" = '5';
You can easily save this filtered set of results to a CSV. Click the button circled below and select “Export to CSV”.
Then, you can configure the CSV output and choose the location to output your file.
Your resulting file will now be filtered to only have articles with a reading time of “5”.
Say we wanted to create a graph that looked at the total reading time of articles per day over-time. To do so without any SQL, we can use the DB4S plot function. Click on “View” and then select “Plot”.
This will open up a new dialog for you to select which columns you want on the X and Y axes of your graph. Below, I selected “Date Published” and “ReadingTime(mins)”. DB4S generated a bar graph to show me the reading time in minutes for every day.
You can also generate graphs from your SQL queries. Say we wanted to count the number of articles published every day. We could write a simple “GROUP BY” query and graph the results.
First, go back to the “Execute SQL” window demonstrated before. Then fill in your SQL query, run it, click “Plot”, and select the columns for your axis. You’ll see a graph version of the table the SQL query generates.
By now, we’ve gone through the complete set-up and usage of your own relational database using DB4S! The simple visual interface of the tool allows you to easily get started with creating and managing an SQLite database. After you’ve gotten comfortable with that, we also looked at how you can actually use the tool to run SQL queries and even visualize data with simple graphs.
This piece was meant to help you get started. For further reading, I’d highly recommend checking out the SQLite docs and the DB4S docs.
If you want to look at how you can write to a database using Pandas, feel free to check out this piece: | [
{
"code": null,
"e": 383,
"s": 171,
"text": "SQL is the third most popular language for developers, based on the StackOverflow 2020 Developer Survey. Everyone knows that you should learn to use SQL, but what about actually creating and managing a database?"
},
{
"code": null,
"e": 608,
"s": 383,
"text": "While you can follow courses that let you play with SQL on a browser with predefined tables (which is not a bad way to learn), it’s also valuable to experience creating, managing, and interacting with a database of your own."
},
{
"code": null,
"e": 908,
"s": 608,
"text": "The DB Browser for SQLite (DB4S) is a tool that makes relational databases accessible to anyone. It allows you to interact with an SQLite database, the entirety of which is contained in a single file. No servers or extensive configuration are needed to get it running. Both DB4S and SQLite are free!"
},
{
"code": null,
"e": 1268,
"s": 908,
"text": "If you don’t have any experience working with databases or SQL, this is a tool that will help you get up to speed with the fundamentals. The DB4S has a spreadsheet-like interface similar to Excel, which means that you can create and edit tables in your own database without using SQL. You also have the option to write custom SQL queries and view the results."
},
{
"code": null,
"e": 1468,
"s": 1268,
"text": "Using the DB4S is a great way to get your hands dirty creating and working with relational databases. This piece will get you started with using the tool. The walkthrough is broken down into 7 parts:"
},
{
"code": null,
"e": 1730,
"s": 1468,
"text": "Installation and setup on your own machineCreating a database fileImporting and exporting tables with CSV filesAdding, modifying and deleting rows (records) and columnsSearching and filtering recordsRunning SQL queriesVisualizing data with graphs or SQL queries"
},
{
"code": null,
"e": 1773,
"s": 1730,
"text": "Installation and setup on your own machine"
},
{
"code": null,
"e": 1798,
"s": 1773,
"text": "Creating a database file"
},
{
"code": null,
"e": 1844,
"s": 1798,
"text": "Importing and exporting tables with CSV files"
},
{
"code": null,
"e": 1902,
"s": 1844,
"text": "Adding, modifying and deleting rows (records) and columns"
},
{
"code": null,
"e": 1934,
"s": 1902,
"text": "Searching and filtering records"
},
{
"code": null,
"e": 1954,
"s": 1934,
"text": "Running SQL queries"
},
{
"code": null,
"e": 1998,
"s": 1954,
"text": "Visualizing data with graphs or SQL queries"
},
{
"code": null,
"e": 2183,
"s": 1998,
"text": "You can check out the installation details on the DB4S website here. You can download the latest versions for both Windows and macOS. It’s also available for Linux based distributions."
},
{
"code": null,
"e": 2270,
"s": 2183,
"text": "If you have Homebrew on macOS, you can also install the latest release with this line:"
},
{
"code": null,
"e": 2310,
"s": 2270,
"text": "brew cask install db-browser-for-sqlite"
},
{
"code": null,
"e": 2409,
"s": 2310,
"text": "Once you’ve gotten DB4S installed on your machine, open the application and you’re ready to begin!"
},
{
"code": null,
"e": 2573,
"s": 2409,
"text": "When you open DB4S, on the top left you see a button labeled “New Database”. Click on it, type out a name for your database, and hit “Save” to your desired folder."
},
{
"code": null,
"e": 2649,
"s": 2573,
"text": "That’s it! You’ve created your first SQL database. You should now see this:"
},
{
"code": null,
"e": 2859,
"s": 2649,
"text": "Now let’s create our first table. To do so, we’re going to import a CSV file with metadata for pieces featured on Medium’s popular page. I got the data in an earlier Python project that you can check out here."
},
{
"code": null,
"e": 2884,
"s": 2859,
"text": "The CSV looks like this:"
},
{
"code": null,
"e": 2935,
"s": 2884,
"text": "To create a table with this file, on DB4S, you do:"
},
{
"code": null,
"e": 2974,
"s": 2935,
"text": "File > Import > Table from CSV file..."
},
{
"code": null,
"e": 3031,
"s": 2974,
"text": "After that, select your desired CSV file and hit “Open”."
},
{
"code": null,
"e": 3345,
"s": 3031,
"text": "This will prompt another window for a couple of customization options. Change the name to something that’s easy to remember. If the column headers are already in the first line of your CSV file, tick the box to make sure DB4S recognizes that. It will shift the first row to become the column names. Then hit “Ok”."
},
{
"code": null,
"e": 3388,
"s": 3345,
"text": "And boom! You’ve created your first table."
},
{
"code": null,
"e": 3519,
"s": 3388,
"text": "Exporting the database file to CSV is just as easy. All you have to do is right-click on the table and click “Export as CSV file”."
},
{
"code": null,
"e": 3567,
"s": 3519,
"text": "Or to bulk export more than one table, do this:"
},
{
"code": null,
"e": 3607,
"s": 3567,
"text": "File > Export > Table(s) as CSV file..."
},
{
"code": null,
"e": 3700,
"s": 3607,
"text": "Now let’s take a look at our table on DB4S. Right-click the table and select “Browse Table”."
},
{
"code": null,
"e": 3765,
"s": 3700,
"text": "You will now see the table in a classic spreadsheet-like format."
},
{
"code": null,
"e": 4154,
"s": 3765,
"text": "If you want to add a new row, just click “New Record”, and DB4S will create a new row (already with a primary key) for you to fill in with values, just like you would on Excel. In this case, we may want to do so every time a new piece is added to Medium’s popular page. DB4S will even suggest a row value based on the first letters you type in if the value already exists in the database."
},
{
"code": null,
"e": 4281,
"s": 4154,
"text": "To delete a row, you just need to select a row (click on a primary key on the leftmost column) and then click “Delete Record”."
},
{
"code": null,
"e": 4413,
"s": 4281,
"text": "Once you’re done with all your changes, click “Write Changes” to save all your modifications and update the table in your database."
},
{
"code": null,
"e": 4616,
"s": 4413,
"text": "Now on the table, you can see there’s a column called “field1”. This is because my CSV extract already included an index column. As DB4S automatically creates an index, I don’t need this column anymore."
},
{
"code": null,
"e": 4965,
"s": 4616,
"text": "Writing SQLite queries will allow you to make some table schema changes, but there is no one line “DROP COLUMN” feature available. The SQLite docs will give you a workaround for how to drop a column, which involves creating a new table with only the desired columns, copying the data from the old table to the new table, and deleting the old table."
},
{
"code": null,
"e": 5121,
"s": 4965,
"text": "In DB4S, dropping a column is a lot simpler. To delete a column, in the Database Structure tab, right-click on your desired table and click “Modify Table”."
},
{
"code": null,
"e": 5258,
"s": 5121,
"text": "You will see a list of columns currently in your table. Select the column you would like to delete, then click “Remove field” and “Yes”."
},
{
"code": null,
"e": 5342,
"s": 5258,
"text": "If we go back to “Browse Table”, we’ll see that “field1” is no longer in the table."
},
{
"code": null,
"e": 5538,
"s": 5342,
"text": "Earlier, we added a record with the author “Dana G Smith”. If we wanted to look for all articles published by Dana in the table, we just need to write the name in the “Filter” box under “Author”."
},
{
"code": null,
"e": 5807,
"s": 5538,
"text": "You can also add filter by more than one column at a time. If we wanted to find all articles in 2019 that had an 11 minute read time, you would just need to fill in two of the filter columns. The table would refresh automatically to show you just the results you need."
},
{
"code": null,
"e": 6109,
"s": 5807,
"text": "You can run all kinds of SQLite queries via the “Execute SQL” tab. For example, if we wanted to see all articles with a reading time of 5, just typing “5” in the filter column like we did earlier would show some unwanted results. In this case, we’ll also get articles that have a reading time of “15”."
},
{
"code": null,
"e": 6207,
"s": 6109,
"text": "To fix this, we’ll write a basic SQL query that filters results to only have a reading time of 5."
},
{
"code": null,
"e": 6271,
"s": 6207,
"text": "SELECT * FROM popular_metadata WHERE \"ReadingTime(mins)\" = '5';"
},
{
"code": null,
"e": 6389,
"s": 6271,
"text": "You can easily save this filtered set of results to a CSV. Click the button circled below and select “Export to CSV”."
},
{
"code": null,
"e": 6473,
"s": 6389,
"text": "Then, you can configure the CSV output and choose the location to output your file."
},
{
"code": null,
"e": 6564,
"s": 6473,
"text": "Your resulting file will now be filtered to only have articles with a reading time of “5”."
},
{
"code": null,
"e": 6766,
"s": 6564,
"text": "Say we wanted to create a graph that looked at the total reading time of articles per day over-time. To do so without any SQL, we can use the DB4S plot function. Click on “View” and then select “Plot”."
},
{
"code": null,
"e": 7014,
"s": 6766,
"text": "This will open up a new dialog for you to select which columns you want on the X and Y axes of your graph. Below, I selected “Date Published” and “ReadingTime(mins)”. DB4S generated a bar graph to show me the reading time in minutes for every day."
},
{
"code": null,
"e": 7197,
"s": 7014,
"text": "You can also generate graphs from your SQL queries. Say we wanted to count the number of articles published every day. We could write a simple “GROUP BY” query and graph the results."
},
{
"code": null,
"e": 7415,
"s": 7197,
"text": "First, go back to the “Execute SQL” window demonstrated before. Then fill in your SQL query, run it, click “Plot”, and select the columns for your axis. You’ll see a graph version of the table the SQL query generates."
},
{
"code": null,
"e": 7794,
"s": 7415,
"text": "By now, we’ve gone through the complete set-up and usage of your own relational database using DB4S! The simple visual interface of the tool allows you to easily get started with creating and managing an SQLite database. After you’ve gotten comfortable with that, we also looked at how you can actually use the tool to run SQL queries and even visualize data with simple graphs."
},
{
"code": null,
"e": 7930,
"s": 7794,
"text": "This piece was meant to help you get started. For further reading, I’d highly recommend checking out the SQLite docs and the DB4S docs."
}
] |
Building A Collaborative Filtering Recommender System with TensorFlow | by Susan Li | Towards Data Science | Therefore, collaborative filtering is not a suitable model to deal with cold start problem, in which it cannot draw any inference for users or items about which it has not yet gathered sufficient information.
But once you have relative large user — item interaction data, then collaborative filtering is the most widely used recommendation approach. And we are going to learn how to build a collaborative filtering recommender system using TensorFlow.
We are again using booking crossing dataset that can be found here. The data pre-processing steps does the following:
Merge user, rating and book data.
Remove unused columns.
Filtering books that have had at least 25 ratings.
Filtering users that have given at least 20 ratings. Remember, collaborative filtering algorithms often require users’ active participation.
So, our final dataset contains 3,192 users for 5,850 books. And each user has given at least 20 ratings and each book has received at least 25 ratings. If you do not have a GPU, this would be a good size.
The collaborative filtering approach focuses on finding users who have given similar ratings to the same books, thus creating a link between users, to whom will be suggested books that were reviewed in a positive way. In this way, we look for associations between users, not between books. Therefore, collaborative filtering relies only on observed user behavior to make recommendations — no profile data or content data is necessary.
Our technique will be based on the following observations:
Users who rate books in a similar manner share one or more hidden preferences.
Users with shared preferences are likely to give ratings in the same way to the same books.
First, we will normalize the rating feature.
scaler = MinMaxScaler()combined['Book-Rating'] = combined['Book-Rating'].values.astype(float)rating_scaled = pd.DataFrame(scaler.fit_transform(combined['Book-Rating'].values.reshape(-1,1)))combined['Book-Rating'] = rating_scaled
Then, build user, book matrix with three features:
combined = combined.drop_duplicates(['User-ID', 'Book-Title'])user_book_matrix = combined.pivot(index='User-ID', columns='Book-Title', values='Book-Rating')user_book_matrix.fillna(0, inplace=True)users = user_book_matrix.index.tolist()books = user_book_matrix.columns.tolist()user_book_matrix = user_book_matrix.as_matrix()
tf.placeholder only available in v1, so I have to work around like so:
import tensorflow.compat.v1 as tftf.disable_v2_behavior()
In the following code scrips
We set up some network parameters, such as the dimension of each hidden layer.
We will initialize the TensorFlow placeholder.
Weights and biases are randomly initialized.
The following code are taken from the book: Python Machine Learning Cook Book — Second Edition
Now, we can build the encoder and decoder model.
Now, we construct the model and the predictions
encoder_op = encoder(X)decoder_op = decoder(encoder_op)y_pred = decoder_opy_true = X
In the following code, we define loss function and optimizer, and minimize the squared error, and define the evaluation metrics.
loss = tf.losses.mean_squared_error(y_true, y_pred)optimizer = tf.train.RMSPropOptimizer(0.03).minimize(loss)eval_x = tf.placeholder(tf.int32, )eval_y = tf.placeholder(tf.int32, )pre, pre_op = tf.metrics.precision(labels=eval_x, predictions=eval_y)
Because TensorFlow uses computational graphs for its operations, placeholders and variables must be initialized before they have values. So in the following code, we initialize the variables, then create an empty data frame to store the result table, which will be top 10 recommendations for every user.
init = tf.global_variables_initializer()local_init = tf.local_variables_initializer()pred_data = pd.DataFrame()
We can finally start training our model.
We split training data into batches, and we feed the network with them.
We train our model with vectors of user ratings, each vector represents a user and each column a book, and entries are ratings that the user gave to books.
After a few trials, I discovered that training model for 100 epochs with a batch size of 35 would be consuming enough memories. This means that the entire training set will feed our neural network 100 times, every time using 35 users.
At the end, we must make sure to remove user’s ratings in the training set. That is, we must not recommend books to a user in which he (or she) has already rated.
Finally, let’s see how our model works. I randomly selected a user, to see what books we should recommended to him (or her).
top_ten_ranked.loc[top_ten_ranked['User-ID'] == 278582]
The above are the top 10 results for this user, sorted by the normalized predicted ratings.
Let’s see what books he (or she) has rated, sorted by ratings.
book_rating.loc[book_rating['User-ID'] == 278582].sort_values(by=['Book-Rating'], ascending=False)
The types of the books this user liked are: historical mystery novel, thriller and suspense novel, science and fiction novel, fantasy novel and so on.
The top 10 results for this user are: murder fantasy novel, mystery thriller novel and so on.
The results were not disappointing.
The Jupyter notebook can be found on Github. Happy Friday!
References:
Python Machine Learning Cook Book — Second Edition | [
{
"code": null,
"e": 381,
"s": 172,
"text": "Therefore, collaborative filtering is not a suitable model to deal with cold start problem, in which it cannot draw any inference for users or items about which it has not yet gathered sufficient information."
},
{
"code": null,
"e": 624,
"s": 381,
"text": "But once you have relative large user — item interaction data, then collaborative filtering is the most widely used recommendation approach. And we are going to learn how to build a collaborative filtering recommender system using TensorFlow."
},
{
"code": null,
"e": 742,
"s": 624,
"text": "We are again using booking crossing dataset that can be found here. The data pre-processing steps does the following:"
},
{
"code": null,
"e": 776,
"s": 742,
"text": "Merge user, rating and book data."
},
{
"code": null,
"e": 799,
"s": 776,
"text": "Remove unused columns."
},
{
"code": null,
"e": 850,
"s": 799,
"text": "Filtering books that have had at least 25 ratings."
},
{
"code": null,
"e": 991,
"s": 850,
"text": "Filtering users that have given at least 20 ratings. Remember, collaborative filtering algorithms often require users’ active participation."
},
{
"code": null,
"e": 1196,
"s": 991,
"text": "So, our final dataset contains 3,192 users for 5,850 books. And each user has given at least 20 ratings and each book has received at least 25 ratings. If you do not have a GPU, this would be a good size."
},
{
"code": null,
"e": 1631,
"s": 1196,
"text": "The collaborative filtering approach focuses on finding users who have given similar ratings to the same books, thus creating a link between users, to whom will be suggested books that were reviewed in a positive way. In this way, we look for associations between users, not between books. Therefore, collaborative filtering relies only on observed user behavior to make recommendations — no profile data or content data is necessary."
},
{
"code": null,
"e": 1690,
"s": 1631,
"text": "Our technique will be based on the following observations:"
},
{
"code": null,
"e": 1769,
"s": 1690,
"text": "Users who rate books in a similar manner share one or more hidden preferences."
},
{
"code": null,
"e": 1861,
"s": 1769,
"text": "Users with shared preferences are likely to give ratings in the same way to the same books."
},
{
"code": null,
"e": 1906,
"s": 1861,
"text": "First, we will normalize the rating feature."
},
{
"code": null,
"e": 2135,
"s": 1906,
"text": "scaler = MinMaxScaler()combined['Book-Rating'] = combined['Book-Rating'].values.astype(float)rating_scaled = pd.DataFrame(scaler.fit_transform(combined['Book-Rating'].values.reshape(-1,1)))combined['Book-Rating'] = rating_scaled"
},
{
"code": null,
"e": 2186,
"s": 2135,
"text": "Then, build user, book matrix with three features:"
},
{
"code": null,
"e": 2510,
"s": 2186,
"text": "combined = combined.drop_duplicates(['User-ID', 'Book-Title'])user_book_matrix = combined.pivot(index='User-ID', columns='Book-Title', values='Book-Rating')user_book_matrix.fillna(0, inplace=True)users = user_book_matrix.index.tolist()books = user_book_matrix.columns.tolist()user_book_matrix = user_book_matrix.as_matrix()"
},
{
"code": null,
"e": 2581,
"s": 2510,
"text": "tf.placeholder only available in v1, so I have to work around like so:"
},
{
"code": null,
"e": 2639,
"s": 2581,
"text": "import tensorflow.compat.v1 as tftf.disable_v2_behavior()"
},
{
"code": null,
"e": 2668,
"s": 2639,
"text": "In the following code scrips"
},
{
"code": null,
"e": 2747,
"s": 2668,
"text": "We set up some network parameters, such as the dimension of each hidden layer."
},
{
"code": null,
"e": 2794,
"s": 2747,
"text": "We will initialize the TensorFlow placeholder."
},
{
"code": null,
"e": 2839,
"s": 2794,
"text": "Weights and biases are randomly initialized."
},
{
"code": null,
"e": 2934,
"s": 2839,
"text": "The following code are taken from the book: Python Machine Learning Cook Book — Second Edition"
},
{
"code": null,
"e": 2983,
"s": 2934,
"text": "Now, we can build the encoder and decoder model."
},
{
"code": null,
"e": 3031,
"s": 2983,
"text": "Now, we construct the model and the predictions"
},
{
"code": null,
"e": 3116,
"s": 3031,
"text": "encoder_op = encoder(X)decoder_op = decoder(encoder_op)y_pred = decoder_opy_true = X"
},
{
"code": null,
"e": 3245,
"s": 3116,
"text": "In the following code, we define loss function and optimizer, and minimize the squared error, and define the evaluation metrics."
},
{
"code": null,
"e": 3494,
"s": 3245,
"text": "loss = tf.losses.mean_squared_error(y_true, y_pred)optimizer = tf.train.RMSPropOptimizer(0.03).minimize(loss)eval_x = tf.placeholder(tf.int32, )eval_y = tf.placeholder(tf.int32, )pre, pre_op = tf.metrics.precision(labels=eval_x, predictions=eval_y)"
},
{
"code": null,
"e": 3798,
"s": 3494,
"text": "Because TensorFlow uses computational graphs for its operations, placeholders and variables must be initialized before they have values. So in the following code, we initialize the variables, then create an empty data frame to store the result table, which will be top 10 recommendations for every user."
},
{
"code": null,
"e": 3910,
"s": 3798,
"text": "init = tf.global_variables_initializer()local_init = tf.local_variables_initializer()pred_data = pd.DataFrame()"
},
{
"code": null,
"e": 3951,
"s": 3910,
"text": "We can finally start training our model."
},
{
"code": null,
"e": 4023,
"s": 3951,
"text": "We split training data into batches, and we feed the network with them."
},
{
"code": null,
"e": 4179,
"s": 4023,
"text": "We train our model with vectors of user ratings, each vector represents a user and each column a book, and entries are ratings that the user gave to books."
},
{
"code": null,
"e": 4414,
"s": 4179,
"text": "After a few trials, I discovered that training model for 100 epochs with a batch size of 35 would be consuming enough memories. This means that the entire training set will feed our neural network 100 times, every time using 35 users."
},
{
"code": null,
"e": 4577,
"s": 4414,
"text": "At the end, we must make sure to remove user’s ratings in the training set. That is, we must not recommend books to a user in which he (or she) has already rated."
},
{
"code": null,
"e": 4702,
"s": 4577,
"text": "Finally, let’s see how our model works. I randomly selected a user, to see what books we should recommended to him (or her)."
},
{
"code": null,
"e": 4758,
"s": 4702,
"text": "top_ten_ranked.loc[top_ten_ranked['User-ID'] == 278582]"
},
{
"code": null,
"e": 4850,
"s": 4758,
"text": "The above are the top 10 results for this user, sorted by the normalized predicted ratings."
},
{
"code": null,
"e": 4913,
"s": 4850,
"text": "Let’s see what books he (or she) has rated, sorted by ratings."
},
{
"code": null,
"e": 5012,
"s": 4913,
"text": "book_rating.loc[book_rating['User-ID'] == 278582].sort_values(by=['Book-Rating'], ascending=False)"
},
{
"code": null,
"e": 5163,
"s": 5012,
"text": "The types of the books this user liked are: historical mystery novel, thriller and suspense novel, science and fiction novel, fantasy novel and so on."
},
{
"code": null,
"e": 5257,
"s": 5163,
"text": "The top 10 results for this user are: murder fantasy novel, mystery thriller novel and so on."
},
{
"code": null,
"e": 5293,
"s": 5257,
"text": "The results were not disappointing."
},
{
"code": null,
"e": 5352,
"s": 5293,
"text": "The Jupyter notebook can be found on Github. Happy Friday!"
},
{
"code": null,
"e": 5364,
"s": 5352,
"text": "References:"
}
] |
Check if the number formed by the last digits of N numbers is divisible by 10 or not - GeeksforGeeks | 13 Mar, 2022
Given an array arr[] of size N consisting of non-zero positive integers. The task is to determine whether the number that is formed by selecting the last digits of all the numbers is divisible by 10 or not. If the number is divisible by 10, then print Yes otherwise print No.Examples:
Input: arr[] = {12, 65, 46, 37, 99} Output: No 25679 is not divisible by 10.Input: arr[] = {24, 37, 46, 50} Output: Yes 4760 is divisible by 10.
Approach: In order for an integer to be divisible by 10, it must be ending with a 0. So, the last element of the array will decide whether the number formed will be divisible by 10 or not. If the last digit of the last element is 0 then print Yes otherwise print No.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <iostream>using namespace std; // Function that returns true if the// number formed by the last digits of// all the elements is divisible by 10bool isDivisible(int arr[], int n){ // Last digit of the last element int lastDigit = arr[n - 1] % 10; // Number formed will be divisible by 10 if (lastDigit == 0) return true; return false;} // Driver codeint main(){ int arr[] = { 12, 65, 46, 37, 99 }; int n = sizeof(arr) / sizeof(arr[0]); if (isDivisible(arr, n)) cout << "Yes"; else cout << "No"; return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // Function that returns true if the// number formed by the last digits of// all the elements is divisible by 10static boolean isDivisible(int arr[], int n){ // Last digit of the last element int lastDigit = arr[n - 1] % 10; // Number formed will be divisible by 10 if (lastDigit == 0) return true; return false;} // Driver codestatic public void main ( String []arg){ int arr[] = { 12, 65, 46, 37, 99 }; int n = arr.length; if (isDivisible(arr, n)) System.out.println("Yes"); else System.out.println("No");}} // This code is contributed by Rajput-Ji
# Python3 implementation of the approach # Function that returns true if the# number formed by the last digits of# all the elements is divisible by 10def isDivisible(arr, n) : # Last digit of the last element lastDigit = arr[n - 1] % 10; # Number formed will be divisible by 10 if (lastDigit == 0) : return True; return False; # Driver codeif __name__ == "__main__" : arr = [ 12, 65, 46, 37, 99 ]; n = len(arr); if (isDivisible(arr, n)) : print("Yes"); else : print("No"); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System; class GFG{ // Function that returns true if the// number formed by the last digits of// all the elements is divisible by 10static bool isDivisible(int []arr, int n){ // Last digit of the last element int lastDigit = arr[n - 1] % 10; // Number formed will be divisible by 10 if (lastDigit == 0) return true; return false;} // Driver codestatic public void Main(String []arg){ int []arr = { 12, 65, 46, 37, 99 }; int n = arr.Length; if (isDivisible(arr, n)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed by Rajput-Ji
<script>// Javascript implementation of the approach // Function that returns true if the// number formed by the last digits of// all the elements is divisible by 10function isDivisible(arr, n){ // Last digit of the last element let lastDigit = arr[n - 1] % 10; // Number formed will be divisible by 10 if (lastDigit == 0) return true; return false;} // Driver code let arr = [ 12, 65, 46, 37, 99 ]; let n = arr.length; if (isDivisible(arr, n)) document.write("Yes"); else document.write("No"); </script>
No
Time Complexity: O(1)
Auxiliary Space: O(1)
ankthon
Rajput-Ji
subham348
subhammahato348
Number Divisibility
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find all factors of a natural number | Set 1
Check if a number is Palindrome
Program to print prime numbers from 1 to N.
Program to add two binary strings
Program to multiply two matrices
Fizz Buzz Implementation
Find pair with maximum GCD in an array
Find Union and Intersection of two unsorted arrays
Count all possible paths from top left to bottom right of a mXn matrix
Count ways to reach the n'th stair | [
{
"code": null,
"e": 24301,
"s": 24273,
"text": "\n13 Mar, 2022"
},
{
"code": null,
"e": 24588,
"s": 24301,
"text": "Given an array arr[] of size N consisting of non-zero positive integers. The task is to determine whether the number that is formed by selecting the last digits of all the numbers is divisible by 10 or not. If the number is divisible by 10, then print Yes otherwise print No.Examples: "
},
{
"code": null,
"e": 24735,
"s": 24588,
"text": "Input: arr[] = {12, 65, 46, 37, 99} Output: No 25679 is not divisible by 10.Input: arr[] = {24, 37, 46, 50} Output: Yes 4760 is divisible by 10. "
},
{
"code": null,
"e": 25056,
"s": 24737,
"text": "Approach: In order for an integer to be divisible by 10, it must be ending with a 0. So, the last element of the array will decide whether the number formed will be divisible by 10 or not. If the last digit of the last element is 0 then print Yes otherwise print No.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25060,
"s": 25056,
"text": "C++"
},
{
"code": null,
"e": 25065,
"s": 25060,
"text": "Java"
},
{
"code": null,
"e": 25073,
"s": 25065,
"text": "Python3"
},
{
"code": null,
"e": 25076,
"s": 25073,
"text": "C#"
},
{
"code": null,
"e": 25087,
"s": 25076,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function that returns true if the// number formed by the last digits of// all the elements is divisible by 10bool isDivisible(int arr[], int n){ // Last digit of the last element int lastDigit = arr[n - 1] % 10; // Number formed will be divisible by 10 if (lastDigit == 0) return true; return false;} // Driver codeint main(){ int arr[] = { 12, 65, 46, 37, 99 }; int n = sizeof(arr) / sizeof(arr[0]); if (isDivisible(arr, n)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 25693,
"s": 25087,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function that returns true if the// number formed by the last digits of// all the elements is divisible by 10static boolean isDivisible(int arr[], int n){ // Last digit of the last element int lastDigit = arr[n - 1] % 10; // Number formed will be divisible by 10 if (lastDigit == 0) return true; return false;} // Driver codestatic public void main ( String []arg){ int arr[] = { 12, 65, 46, 37, 99 }; int n = arr.length; if (isDivisible(arr, n)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code is contributed by Rajput-Ji",
"e": 26368,
"s": 25693,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function that returns true if the# number formed by the last digits of# all the elements is divisible by 10def isDivisible(arr, n) : # Last digit of the last element lastDigit = arr[n - 1] % 10; # Number formed will be divisible by 10 if (lastDigit == 0) : return True; return False; # Driver codeif __name__ == \"__main__\" : arr = [ 12, 65, 46, 37, 99 ]; n = len(arr); if (isDivisible(arr, n)) : print(\"Yes\"); else : print(\"No\"); # This code is contributed by AnkitRai01",
"e": 26935,
"s": 26368,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function that returns true if the// number formed by the last digits of// all the elements is divisible by 10static bool isDivisible(int []arr, int n){ // Last digit of the last element int lastDigit = arr[n - 1] % 10; // Number formed will be divisible by 10 if (lastDigit == 0) return true; return false;} // Driver codestatic public void Main(String []arg){ int []arr = { 12, 65, 46, 37, 99 }; int n = arr.Length; if (isDivisible(arr, n)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed by Rajput-Ji",
"e": 27599,
"s": 26935,
"text": null
},
{
"code": "<script>// Javascript implementation of the approach // Function that returns true if the// number formed by the last digits of// all the elements is divisible by 10function isDivisible(arr, n){ // Last digit of the last element let lastDigit = arr[n - 1] % 10; // Number formed will be divisible by 10 if (lastDigit == 0) return true; return false;} // Driver code let arr = [ 12, 65, 46, 37, 99 ]; let n = arr.length; if (isDivisible(arr, n)) document.write(\"Yes\"); else document.write(\"No\"); </script>",
"e": 28155,
"s": 27599,
"text": null
},
{
"code": null,
"e": 28158,
"s": 28155,
"text": "No"
},
{
"code": null,
"e": 28182,
"s": 28160,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 28204,
"s": 28182,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 28212,
"s": 28204,
"text": "ankthon"
},
{
"code": null,
"e": 28222,
"s": 28212,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 28232,
"s": 28222,
"text": "subham348"
},
{
"code": null,
"e": 28248,
"s": 28232,
"text": "subhammahato348"
},
{
"code": null,
"e": 28268,
"s": 28248,
"text": "Number Divisibility"
},
{
"code": null,
"e": 28281,
"s": 28268,
"text": "Mathematical"
},
{
"code": null,
"e": 28294,
"s": 28281,
"text": "Mathematical"
},
{
"code": null,
"e": 28392,
"s": 28294,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28401,
"s": 28392,
"text": "Comments"
},
{
"code": null,
"e": 28414,
"s": 28401,
"text": "Old Comments"
},
{
"code": null,
"e": 28459,
"s": 28414,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 28491,
"s": 28459,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 28535,
"s": 28491,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 28569,
"s": 28535,
"text": "Program to add two binary strings"
},
{
"code": null,
"e": 28602,
"s": 28569,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 28627,
"s": 28602,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 28666,
"s": 28627,
"text": "Find pair with maximum GCD in an array"
},
{
"code": null,
"e": 28717,
"s": 28666,
"text": "Find Union and Intersection of two unsorted arrays"
},
{
"code": null,
"e": 28788,
"s": 28717,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
}
] |
Batch Script - String Interpolation | String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal.
In DOS scripting, the string interpolation can be done using the set command and lining up the numeric defined variables or any other literals in one line when using the set command.
The following example shows how a string interpolation can be done with numeric values as well.
@echo off
SET a = Hello
SET b = World
SET /A d = 50
SET c=%a% and %b% %d%
echo %c%
The above command produces the following output.
Hello and World 50
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2344,
"s": 2169,
"text": "String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal."
},
{
"code": null,
"e": 2527,
"s": 2344,
"text": "In DOS scripting, the string interpolation can be done using the set command and lining up the numeric defined variables or any other literals in one line when using the set command."
},
{
"code": null,
"e": 2623,
"s": 2527,
"text": "The following example shows how a string interpolation can be done with numeric values as well."
},
{
"code": null,
"e": 2710,
"s": 2623,
"text": "@echo off \nSET a = Hello \nSET b = World \nSET /A d = 50 \nSET c=%a% and %b% %d%\necho %c%"
},
{
"code": null,
"e": 2759,
"s": 2710,
"text": "The above command produces the following output."
},
{
"code": null,
"e": 2779,
"s": 2759,
"text": "Hello and World 50\n"
},
{
"code": null,
"e": 2786,
"s": 2779,
"text": " Print"
},
{
"code": null,
"e": 2797,
"s": 2786,
"text": " Add Notes"
}
] |
C++ Class Access Modifiers | Data hiding is one of the important features of Object Oriented Programming which allows preventing the functions of a program to access directly the internal representation of a class type. The access restriction to the class members is specified by the labeled public, private, and protected sections within the class body. The keywords public, private, and protected are called access specifiers.
A class can have multiple public, protected, or private labeled sections. Each section remains in effect until either another section label or the closing right brace of the class body is seen. The default access for members and classes is private.
class Base {
public:
// public members go here
protected:
// protected members go here
private:
// private members go here
};
A public member is accessible from anywhere outside the class but within a program. You can set and get the value of public variables without any member function as shown in the following example −
#include <iostream>
using namespace std;
class Line {
public:
double length;
void setLength( double len );
double getLength( void );
};
// Member functions definitions
double Line::getLength(void) {
return length ;
}
void Line::setLength( double len) {
length = len;
}
// Main function for the program
int main() {
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
// set line length without member function
line.length = 10.0; // OK: because length is public
cout << "Length of line : " << line.length <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Length of line : 6
Length of line : 10
A private member variable or function cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members.
By default all the members of a class would be private, for example in the following class width is a private member, which means until you label a member, it will be assumed a private member −
class Box {
double width;
public:
double length;
void setWidth( double wid );
double getWidth( void );
};
Practically, we define data in private section and related functions in public section so that they can be called from outside of the class as shown in the following program.
#include <iostream>
using namespace std;
class Box {
public:
double length;
void setWidth( double wid );
double getWidth( void );
private:
double width;
};
// Member functions definitions
double Box::getWidth(void) {
return width ;
}
void Box::setWidth( double wid ) {
width = wid;
}
// Main function for the program
int main() {
Box box;
// set box length without member function
box.length = 10.0; // OK: because length is public
cout << "Length of box : " << box.length <<endl;
// set box width without member function
// box.width = 10.0; // Error: because width is private
box.setWidth(10.0); // Use member function to set it.
cout << "Width of box : " << box.getWidth() <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Length of box : 10
Width of box : 10
A protected member variable or function is very similar to a private member but it provided one additional benefit that they can be accessed in child classes which are called derived classes.
You will learn derived classes and inheritance in next chapter. For now you can check following example where I have derived one child class SmallBox from a parent class Box.
Following example is similar to above example and here width member will be accessible by any member function of its derived class SmallBox.
#include <iostream>
using namespace std;
class Box {
protected:
double width;
};
class SmallBox:Box { // SmallBox is the derived class.
public:
void setSmallWidth( double wid );
double getSmallWidth( void );
};
// Member functions of child class
double SmallBox::getSmallWidth(void) {
return width ;
}
void SmallBox::setSmallWidth( double wid ) {
width = wid;
}
// Main function for the program
int main() {
SmallBox box;
// set box width using member function
box.setSmallWidth(5.0);
cout << "Width of box : "<< box.getSmallWidth() << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Width of box : 5
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": 2718,
"s": 2318,
"text": "Data hiding is one of the important features of Object Oriented Programming which allows preventing the functions of a program to access directly the internal representation of a class type. The access restriction to the class members is specified by the labeled public, private, and protected sections within the class body. The keywords public, private, and protected are called access specifiers."
},
{
"code": null,
"e": 2967,
"s": 2718,
"text": "A class can have multiple public, protected, or private labeled sections. Each section remains in effect until either another section label or the closing right brace of the class body is seen. The default access for members and classes is private."
},
{
"code": null,
"e": 3123,
"s": 2967,
"text": "class Base { \n public:\n // public members go here\n protected:\n \n // protected members go here\n private:\n // private members go here\n \n};\n"
},
{
"code": null,
"e": 3321,
"s": 3123,
"text": "A public member is accessible from anywhere outside the class but within a program. You can set and get the value of public variables without any member function as shown in the following example −"
},
{
"code": null,
"e": 3971,
"s": 3321,
"text": "#include <iostream>\n \nusing namespace std;\n \nclass Line {\n public:\n double length;\n void setLength( double len );\n double getLength( void );\n};\n \n// Member functions definitions\ndouble Line::getLength(void) {\n return length ;\n}\n \nvoid Line::setLength( double len) {\n length = len;\n}\n \n// Main function for the program\nint main() {\n Line line;\n \n // set line length\n line.setLength(6.0); \n cout << \"Length of line : \" << line.getLength() <<endl;\n \n // set line length without member function\n line.length = 10.0; // OK: because length is public\n cout << \"Length of line : \" << line.length <<endl;\n \n return 0;\n}"
},
{
"code": null,
"e": 4052,
"s": 3971,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4092,
"s": 4052,
"text": "Length of line : 6\nLength of line : 10\n"
},
{
"code": null,
"e": 4253,
"s": 4092,
"text": "A private member variable or function cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members."
},
{
"code": null,
"e": 4447,
"s": 4253,
"text": "By default all the members of a class would be private, for example in the following class width is a private member, which means until you label a member, it will be assumed a private member −"
},
{
"code": null,
"e": 4582,
"s": 4447,
"text": "class Box {\n double width;\n \n public:\n double length;\n void setWidth( double wid );\n double getWidth( void );\n};\n"
},
{
"code": null,
"e": 4758,
"s": 4582,
"text": "Practically, we define data in private section and related functions in public section so that they can be called from outside of the class as shown in the following program."
},
{
"code": null,
"e": 5536,
"s": 4758,
"text": "#include <iostream>\n \nusing namespace std;\n \nclass Box {\n public:\n double length;\n void setWidth( double wid );\n double getWidth( void );\n \n private:\n double width;\n};\n \n// Member functions definitions\ndouble Box::getWidth(void) {\n return width ;\n}\n \nvoid Box::setWidth( double wid ) {\n width = wid;\n}\n \n// Main function for the program\nint main() {\n Box box;\n \n // set box length without member function\n box.length = 10.0; // OK: because length is public\n cout << \"Length of box : \" << box.length <<endl;\n \n // set box width without member function\n // box.width = 10.0; // Error: because width is private\n box.setWidth(10.0); // Use member function to set it.\n cout << \"Width of box : \" << box.getWidth() <<endl;\n \n return 0;\n}"
},
{
"code": null,
"e": 5617,
"s": 5536,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5655,
"s": 5617,
"text": "Length of box : 10\nWidth of box : 10\n"
},
{
"code": null,
"e": 5847,
"s": 5655,
"text": "A protected member variable or function is very similar to a private member but it provided one additional benefit that they can be accessed in child classes which are called derived classes."
},
{
"code": null,
"e": 6022,
"s": 5847,
"text": "You will learn derived classes and inheritance in next chapter. For now you can check following example where I have derived one child class SmallBox from a parent class Box."
},
{
"code": null,
"e": 6163,
"s": 6022,
"text": "Following example is similar to above example and here width member will be accessible by any member function of its derived class SmallBox."
},
{
"code": null,
"e": 6776,
"s": 6163,
"text": "#include <iostream>\nusing namespace std;\n \nclass Box {\n protected:\n double width;\n};\n \nclass SmallBox:Box { // SmallBox is the derived class.\n public:\n void setSmallWidth( double wid );\n double getSmallWidth( void );\n};\n \n// Member functions of child class\ndouble SmallBox::getSmallWidth(void) {\n return width ;\n}\n \nvoid SmallBox::setSmallWidth( double wid ) {\n width = wid;\n}\n \n// Main function for the program\nint main() {\n SmallBox box;\n \n // set box width using member function\n box.setSmallWidth(5.0);\n cout << \"Width of box : \"<< box.getSmallWidth() << endl;\n \n return 0;\n}"
},
{
"code": null,
"e": 6857,
"s": 6776,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 6875,
"s": 6857,
"text": "Width of box : 5\n"
},
{
"code": null,
"e": 6912,
"s": 6875,
"text": "\n 154 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 6931,
"s": 6912,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6963,
"s": 6931,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 6986,
"s": 6963,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 7022,
"s": 6986,
"text": "\n 30 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 7039,
"s": 7022,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7074,
"s": 7039,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7091,
"s": 7074,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7126,
"s": 7091,
"text": "\n 77 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7143,
"s": 7126,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7178,
"s": 7143,
"text": "\n 12 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7195,
"s": 7178,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7202,
"s": 7195,
"text": " Print"
},
{
"code": null,
"e": 7213,
"s": 7202,
"text": " Add Notes"
}
] |
Scala short ==(x: Int): Boolean - GeeksforGeeks | 14 Jan, 2020
Short, a 16-bit signed integer (equivalent to Java’s short primitive type) is a subtype of scala.AnyVal. The ==(x: Int) method is utilized to return true if this value is equal to x, false otherwise.
Method Definition: def ==(x: Int): Boolean
Return Type: It returns true if this value is equal to x, otherwise false.
Example #1:
// Scala program of Short ==(x: Int) // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying Short ==(x: Int) function val result = (99.toShort).==(99:Int) // Displays output println(result) } }
Output:
true
Example #2:
// Scala program of Short ==(x: Int) // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying Short ==(x: Int) function val result = (102.toShort).==(101:Int) // Displays output println(result) } }
Output:
false
Scala
scala-short
Python
Scala
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
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
For Loop in Scala
Scala | flatMap Method
Scala Lists
Class and Object in Scala
Scala | map() method | [
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n14 Jan, 2020"
},
{
"code": null,
"e": 24412,
"s": 24212,
"text": "Short, a 16-bit signed integer (equivalent to Java’s short primitive type) is a subtype of scala.AnyVal. The ==(x: Int) method is utilized to return true if this value is equal to x, false otherwise."
},
{
"code": null,
"e": 24455,
"s": 24412,
"text": "Method Definition: def ==(x: Int): Boolean"
},
{
"code": null,
"e": 24530,
"s": 24455,
"text": "Return Type: It returns true if this value is equal to x, otherwise false."
},
{
"code": null,
"e": 24542,
"s": 24530,
"text": "Example #1:"
},
{
"code": "// Scala program of Short ==(x: Int) // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying Short ==(x: Int) function val result = (99.toShort).==(99:Int) // Displays output println(result) } } ",
"e": 24855,
"s": 24542,
"text": null
},
{
"code": null,
"e": 24863,
"s": 24855,
"text": "Output:"
},
{
"code": null,
"e": 24868,
"s": 24863,
"text": "true"
},
{
"code": null,
"e": 24880,
"s": 24868,
"text": "Example #2:"
},
{
"code": "// Scala program of Short ==(x: Int) // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying Short ==(x: Int) function val result = (102.toShort).==(101:Int) // Displays output println(result) } } ",
"e": 25195,
"s": 24880,
"text": null
},
{
"code": null,
"e": 25203,
"s": 25195,
"text": "Output:"
},
{
"code": null,
"e": 25209,
"s": 25203,
"text": "false"
},
{
"code": null,
"e": 25215,
"s": 25209,
"text": "Scala"
},
{
"code": null,
"e": 25227,
"s": 25215,
"text": "scala-short"
},
{
"code": null,
"e": 25234,
"s": 25227,
"text": "Python"
},
{
"code": null,
"e": 25240,
"s": 25234,
"text": "Scala"
},
{
"code": null,
"e": 25338,
"s": 25240,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25347,
"s": 25338,
"text": "Comments"
},
{
"code": null,
"e": 25360,
"s": 25347,
"text": "Old Comments"
},
{
"code": null,
"e": 25392,
"s": 25360,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25448,
"s": 25392,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25469,
"s": 25448,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 25508,
"s": 25469,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25550,
"s": 25508,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25568,
"s": 25550,
"text": "For Loop in Scala"
},
{
"code": null,
"e": 25591,
"s": 25568,
"text": "Scala | flatMap Method"
},
{
"code": null,
"e": 25603,
"s": 25591,
"text": "Scala Lists"
},
{
"code": null,
"e": 25629,
"s": 25603,
"text": "Class and Object in Scala"
}
] |
Quick Semantic Search using Siamese-BERT Networks | by Aneesha Bakharia | Towards Data Science | I’ve been working on a tool that needed to embed semantic search based on BERT. The idea was simple: get BERT encodings for each sentence in the corpus and then use cosine similarity to match to a query (either a word or another short sentence). Depending upon the size of the corpus returning a BERT embedding for each sentence takes a while. I was tempted to use a simpler model (eg ELMO or BERT-As-A-Service) until I came across the “Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks” 2019 ACL paper by Nils Reimers and Iryna Gurevych. Source code for the paper was available from Github and PyPi had the Sentence-BERT library ready to be pip installed (if you use Python). In this blog post, I’ll briefly describe the problem the paper solves and present a Google Collab notebook that illustrates just how easy it is to achieve semantic search functionality using a SOTA BERT model.
BERT uses cross-encoder networks that take 2 sentences as input to the transformer network and then predict a target value. BERT is able to achieve SOTA performance on Semantic Textual Similarity tasks but both sentences must be passed through the full network. In a corpus consisting of 10000 sentences, finding similar pairs of sentences requires about 50 million inference computations taking approximately 65 hours (if you have the right computation capacity power eg. V100 GPU). Sentence-BERT impressively can provide the encodings for 10000 sentences in approximately 5 seconds!!!
Sentence-BERT finetunes a pre-trained BERT network using Siamese and triplet network structures and adds a pooling operation to the output of BERT to derive a fixed-sized sentence embedding vector. The produced embedding vector is more appropriate for sentence similarity comparisons within a vector space (i.e. that can be compared using cosine similarity).
The popular BERT-As-A-Service library runs a sentence through BERT and derives a fixed-sized vector by averaging the outputs of the model. BERT-As-A-Service has also not been evaluated in the context of producing useful sentence embeddings.
I’ve created a Google Colab notebook to illustrate using the Sentence-BERT library to create a semantic search example. The Github repo is available here: SiameseBERT_SemanticSearch.ipynb
A gist version of the Collab Notebook is displayed below:
This Google Colab Notebook illustrates using the Sentence Transformer python library to quickly create BERT embeddings for sentences and perform fast semantic searches.
The Sentence Transformer library is available on pypi and github. The library implements code from the ACL 2019 paper entitled "Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks" by Nils Reimers and Iryna Gurevych.
# Install the library using pip
!pip install sentence-transformers
Collecting sentence-transformers
Downloading https://files.pythonhosted.org/packages/c9/91/c85ddef872d5bb39949386930c1f834ac382e145fcd30155b09d6fb65c5a/sentence-transformers-0.2.5.tar.gz (49kB)
|████████████████████████████████| 51kB 1.7MB/s
Collecting transformers==2.3.0
Downloading https://files.pythonhosted.org/packages/50/10/aeefced99c8a59d828a92cc11d213e2743212d3641c87c82d61b035a7d5c/transformers-2.3.0-py3-none-any.whl (447kB)
|████████████████████████████████| 450kB 7.2MB/s
Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from sentence-transformers) (4.28.1)
Requirement already satisfied: torch>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from sentence-transformers) (1.3.1)
Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from sentence-transformers) (1.17.5)
Requirement already satisfied: scikit-learn in /usr/local/lib/python3.6/dist-packages (from sentence-transformers) (0.22.1)
Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from sentence-transformers) (1.4.1)
Requirement already satisfied: nltk in /usr/local/lib/python3.6/dist-packages (from sentence-transformers) (3.2.5)
Requirement already satisfied: boto3 in /usr/local/lib/python3.6/dist-packages (from transformers==2.3.0->sentence-transformers) (1.10.47)
Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.6/dist-packages (from transformers==2.3.0->sentence-transformers) (2019.12.20)
Requirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from transformers==2.3.0->sentence-transformers) (2.21.0)
Collecting sacremoses
Downloading https://files.pythonhosted.org/packages/a6/b4/7a41d630547a4afd58143597d5a49e07bfd4c42914d8335b2a5657efc14b/sacremoses-0.0.38.tar.gz (860kB)
|████████████████████████████████| 870kB 26.9MB/s
Collecting sentencepiece
Downloading https://files.pythonhosted.org/packages/74/f4/2d5214cbf13d06e7cb2c20d84115ca25b53ea76fa1f0ade0e3c9749de214/sentencepiece-0.1.85-cp36-cp36m-manylinux1_x86_64.whl (1.0MB)
|████████████████████████████████| 1.0MB 42.6MB/s
Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn->sentence-transformers) (0.14.1)
Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from nltk->sentence-transformers) (1.12.0)
Requirement already satisfied: jmespath<1.0.0,>=0.7.1 in /usr/local/lib/python3.6/dist-packages (from boto3->transformers==2.3.0->sentence-transformers) (0.9.4)
Requirement already satisfied: s3transfer<0.3.0,>=0.2.0 in /usr/local/lib/python3.6/dist-packages (from boto3->transformers==2.3.0->sentence-transformers) (0.2.1)
Requirement already satisfied: botocore<1.14.0,>=1.13.47 in /usr/local/lib/python3.6/dist-packages (from boto3->transformers==2.3.0->sentence-transformers) (1.13.47)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->transformers==2.3.0->sentence-transformers) (3.0.4)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->transformers==2.3.0->sentence-transformers) (2019.11.28)
Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->transformers==2.3.0->sentence-transformers) (1.24.3)
Requirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->transformers==2.3.0->sentence-transformers) (2.8)
Requirement already satisfied: click in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers==2.3.0->sentence-transformers) (7.0)
Requirement already satisfied: docutils<0.16,>=0.10 in /usr/local/lib/python3.6/dist-packages (from botocore<1.14.0,>=1.13.47->boto3->transformers==2.3.0->sentence-transformers) (0.15.2)
Requirement already satisfied: python-dateutil<3.0.0,>=2.1; python_version >= "2.7" in /usr/local/lib/python3.6/dist-packages (from botocore<1.14.0,>=1.13.47->boto3->transformers==2.3.0->sentence-transformers) (2.6.1)
Building wheels for collected packages: sentence-transformers, sacremoses
Building wheel for sentence-transformers (setup.py) ... done
Created wheel for sentence-transformers: filename=sentence_transformers-0.2.5-cp36-none-any.whl size=64943 sha256=973f7a74060aad6ed6f617b3879e3340babb4d0ecd2d47508f1538ef02d1a587
Stored in directory: /root/.cache/pip/wheels/b4/ce/39/5bbda8ac34eb52df8c6531382ca077773fbfcbfb6386e5d66c
Building wheel for sacremoses (setup.py) ... done
Created wheel for sacremoses: filename=sacremoses-0.0.38-cp36-none-any.whl size=884629 sha256=63585f2eb5e65adb473e2e282bda1bdc423a86bfde2a175308c56709911f6678
Stored in directory: /root/.cache/pip/wheels/6d/ec/1a/21b8912e35e02741306f35f66c785f3afe94de754a0eaf1422
Successfully built sentence-transformers sacremoses
Installing collected packages: sacremoses, sentencepiece, transformers, sentence-transformers
Successfully installed sacremoses-0.0.38 sentence-transformers-0.2.5 sentencepiece-0.1.85 transformers-2.3.0
from sentence_transformers import SentenceTransformer
# Load the BERT model. Various models trained on Natural Language Inference (NLI) https://github.com/UKPLab/sentence-transformers/blob/master/docs/pretrained-models/nli-models.md and
# Semantic Textual Similarity are available https://github.com/UKPLab/sentence-transformers/blob/master/docs/pretrained-models/sts-models.md
model = SentenceTransformer('bert-base-nli-mean-tokens')
The default version of TensorFlow in Colab will soon switch to TensorFlow 2.x.
We recommend you upgrade now
or ensure your notebook will continue to use TensorFlow 1.x via the %tensorflow_version 1.x magic:
more info.
100%|██████████| 405M/405M [00:18<00:00, 21.8MB/s]
# A corpus is a list with documents split by sentences.
sentences = ['Absence of sanity',
'Lack of saneness',
'A man is eating food.',
'A man is eating a piece of bread.',
'The girl is carrying a baby.',
'A man is riding a horse.',
'A woman is playing violin.',
'Two men pushed carts through the woods.',
'A man is riding a white horse on an enclosed ground.',
'A monkey is playing drums.',
'A cheetah is running behind its prey.']
# Each sentence is encoded as a 1-D vector with 78 columns
sentence_embeddings = model.encode(sentences)
print('Sample BERT embedding vector - length', len(sentence_embeddings[0]))
print('Sample BERT embedding vector - note includes negative values', sentence_embeddings[0])
Sample BERT embedding vector - length 768
Sample BERT embedding vector - note includes negative values [ 2.95403183e-01 2.91810960e-01 2.16480136e+00 2.20419839e-01
-1.30865965e-02 1.01950336e+00 1.51298153e+00 2.34131858e-01
2.73058057e-01 1.35122865e-01 -1.11313331e+00 -1.25884697e-01
1.45378590e-01 9.77708638e-01 1.39352250e+00 4.57705110e-01
-5.82131505e-01 -7.24940956e-01 -3.61734480e-01 -2.27514893e-01
1.66630689e-02 2.04861969e-01 6.55133009e-01 -1.29376340e+00
-7.26099372e-01 -1.91135541e-01 -3.07211697e-01 -1.30278623e+00
-1.42963886e+00 5.67453261e-03 3.54811519e-01 4.83712614e-01
6.65388048e-01 5.33848584e-01 6.40496492e-01 5.90408444e-01
7.83850178e-02 -1.07759213e+00 -1.24676526e-01 -3.98406386e-01
7.36313939e-01 5.28293252e-01 5.63290775e-01 4.14546162e-01
4.49179649e-01 -9.58786383e-02 1.45424592e+00 -2.69145072e-01
-2.44059876e-01 -1.10387051e+00 -2.00923532e-01 -2.17437861e-03
1.83387971e+00 1.06518459e+00 -5.11945903e-01 -1.11248529e+00
5.59790373e-01 -5.89609563e-01 1.07621944e+00 7.49265671e-01
4.32666481e-01 1.76307142e-01 -1.72125660e-02 1.19170345e-01
-8.37448120e-01 1.88445479e-01 -7.46789854e-03 1.70312412e-02
-4.29175943e-01 -5.72340369e-01 6.22608125e-01 -3.38023841e-01
1.03712715e-01 2.42106587e-01 -9.82075334e-01 -2.63344377e-01
4.15540874e-01 2.79155314e-01 -1.03487372e-01 7.32837498e-01
2.78023511e-01 7.52160132e-01 8.08235168e-01 -4.87504005e-01
-7.64050961e-01 -7.08029419e-02 5.39888680e-01 2.24032193e-01
-1.66969836e+00 -2.01102495e-01 2.13853925e-01 1.08926618e+00
5.79520047e-01 -3.32589626e-01 -9.75302875e-01 2.37982087e-02
-1.68780282e-01 2.63479292e-01 1.64727420e-01 2.03110695e-01
8.12745094e-03 3.75387013e-01 4.53516781e-01 4.21480648e-02
4.72985119e-01 3.53581369e-01 -1.55092627e-01 3.71253103e-01
3.54824960e-01 5.11555187e-02 -9.36767399e-01 1.42013264e+00
7.63064623e-01 -8.58592212e-01 -5.74659705e-01 2.43800841e-02
-1.39292669e+00 3.14162791e-01 -2.08897144e-02 4.01286274e-01
8.56514335e-01 2.12013125e-01 1.93166375e-01 -8.65448266e-02
3.66492569e-01 -5.34847438e-01 9.08364177e-01 -1.47459909e-01
-4.34119612e-01 1.38952568e-01 -2.85755783e-01 8.91503990e-01
-9.49378788e-01 -6.12362102e-02 -1.63513094e-01 2.15337463e-02
9.33672637e-02 -1.83846831e-01 -7.05079511e-02 -9.50030535e-02
-7.78035462e-01 5.08425236e-01 -2.38957599e-01 1.18628956e-01
-2.22939938e-01 -4.55788314e-01 7.77875900e-01 5.58182418e-01
-6.46435559e-01 -3.76423895e-01 -9.94759917e-01 -2.24633545e-01
2.56237477e-01 3.92683744e-01 -3.80205333e-01 -5.66550314e-01
1.06151199e+00 6.39036715e-01 2.45125726e-01 -2.10276559e-01
-2.03608587e-01 5.58223248e-01 5.87122440e-02 4.09846961e-01
9.85415801e-02 5.68384044e-02 -3.91428530e-01 2.61983126e-01
1.85061485e-01 -7.71071732e-01 6.81889176e-01 -6.14751518e-01
-9.09989655e-01 -5.37011623e-01 -2.67421097e-01 6.41145855e-02
-1.47129208e-01 8.36788297e-01 2.73965627e-01 2.99047649e-01
1.75318837e-01 -8.45175162e-02 1.32096362e+00 -1.32269931e+00
-8.96274865e-01 -7.21393704e-01 9.03015211e-02 -5.28525472e-01
-5.90585284e-02 -1.73461944e-01 -1.08447266e+00 -9.68358815e-01
7.07607031e-01 -1.08554244e+00 7.90785030e-02 -1.23736322e-01
1.04828671e-01 -4.38560009e-01 -9.64857712e-02 1.21586382e-01
7.08318591e-01 -7.40591824e-01 -6.13734312e-02 5.97689033e-01
5.36595702e-01 9.54430461e-01 5.82716949e-02 -7.02314198e-01
-5.21191716e-01 -5.31055272e-01 -6.87113464e-01 -2.28840038e-01
-1.25095084e-01 3.82895499e-01 9.40875232e-01 -1.53620028e+00
3.08551461e-01 -1.07018912e+00 -9.22982693e-02 1.83376744e-01
2.36132234e-01 -9.44777846e-01 3.63419414e-01 1.02015033e-01
-2.61932522e-01 1.31475377e+00 -8.66960660e-02 4.19597805e-01
-5.64485192e-01 -2.40892217e-01 9.56280604e-02 2.88403451e-01
-1.26559651e+00 9.68216509e-02 -6.86096549e-01 -9.73237216e-01
4.98169512e-01 -6.72291875e-01 6.18023753e-01 -2.36299157e-01
-1.19642895e-02 2.23920777e-01 1.29233646e+00 9.04313385e-01
-6.94556832e-01 2.12914258e-01 1.41126677e-01 -1.09073651e+00
-2.61027157e-01 3.72416407e-01 5.65627873e-01 -7.63028026e-01
2.54305422e-01 2.96842039e-01 6.39281869e-01 -3.68397057e-01
-1.50474444e-01 -2.06995815e-01 4.89718974e-01 -1.07649386e+00
-4.69321489e-01 5.64345777e-01 -8.54324996e-01 2.01307058e-01
-3.64126265e-01 -4.83238310e-01 -2.99138606e-01 -2.37890765e-01
-7.14595199e-01 3.88846397e-02 2.88149297e-01 -8.43381286e-01
-1.32528901e-01 3.20764244e-01 -5.64771175e-01 -6.50783896e-01
1.23112619e+00 -3.79267991e-01 -5.36719501e-01 -1.18963256e-01
5.57513535e-01 7.38234401e-01 -1.65188718e+00 4.81852919e-01
-9.48715389e-01 9.54266250e-01 6.12537324e-01 2.52186596e-01
-2.26502508e-01 -1.06311001e-01 -6.21922791e-01 7.16752052e-01
-3.86202455e-01 -7.54139066e-01 5.86001515e-01 -2.63744980e-01
2.03416556e-01 -5.31250715e-01 -9.58163381e-01 7.24046588e-01
-6.24141991e-01 -1.32546872e-01 -7.14519739e-01 2.18565226e-01
-6.77284122e-01 -1.44099727e-01 -3.61371309e-01 8.55807483e-01
4.30027187e-01 5.20425677e-01 -1.25135791e+00 8.63247830e-03
-8.13418508e-01 -1.89723641e-01 6.97539449e-01 -2.71261573e-01
-9.60209668e-01 -5.67387223e-01 -1.97102293e-01 -8.45597088e-01
4.09596503e-01 4.65882063e-01 1.00616157e-01 1.79212242e-01
3.18223983e-01 -1.94156840e-01 -2.31451839e-02 5.31907439e-01
2.07857490e-01 -1.38748586e-01 -1.25763610e-01 -1.67028809e+00
7.72697479e-02 3.29649597e-01 9.59621310e-01 9.71129060e-01
-8.59887302e-01 -7.97947407e-01 -4.50175434e-01 6.09351099e-01
-9.92598385e-02 -1.26160526e+00 -4.80852902e-01 -4.37261537e-02
7.61089265e-01 -4.90454495e-01 -1.16635013e+00 -1.26680553e+00
4.23249960e-01 -3.28321755e-01 1.13249719e-01 1.19094634e+00
-4.76775408e-01 2.77292818e-01 -6.62052512e-01 -6.26967430e-01
-3.28043163e-01 4.62100357e-01 4.22713980e-02 1.11225937e-02
3.49018514e-01 3.41067076e-01 -2.20341116e-01 -8.18507969e-01
6.06628835e-01 -6.28642023e-01 2.82574117e-01 4.81881082e-01
1.42555833e+00 -1.52616878e-03 -5.17759204e-01 -2.46807709e-02
-5.39778233e-01 2.85306722e-01 -2.21777245e-01 -1.85012728e-01
3.11429322e-01 -2.07644105e-01 -2.50214398e-01 -9.53149140e-01
4.12619442e-01 3.92308757e-02 1.41120523e-01 -3.55187565e-01
1.18068099e+00 -3.14618677e-01 4.79557097e-01 -4.70073700e-01
1.77134991e-01 6.75846696e-01 9.84487832e-01 2.68136203e-01
-7.01508764e-03 -2.85394371e-01 -1.52261570e-01 -1.11626387e+00
1.02338985e-01 5.77064395e-01 3.41381252e-01 4.19948399e-01
4.03284848e-01 2.95105875e-01 9.24367547e-01 1.26249242e+00
1.20447159e+00 9.47556794e-01 4.87714596e-02 4.61912721e-01
-8.18414986e-01 4.46733892e-01 6.60865068e-01 4.44435418e-01
-9.46657002e-01 3.16685140e-01 -5.51689267e-01 -1.82610482e-01
-1.46252900e-01 -1.01644254e+00 7.33198643e-01 1.08742762e+00
-6.23244762e-01 -6.87371850e-01 -1.63677886e-01 2.05873415e-01
-1.28120184e-04 1.58518422e+00 -2.15279460e-01 -3.93540442e-01
-2.25850105e-01 -4.96896729e-02 -3.16225171e-01 -2.08421387e-02
-7.36599624e-01 5.96843779e-01 -6.45120263e-01 -5.47669291e-01
1.46693140e-01 -1.00796354e+00 2.46947721e-01 -1.16965592e-01
1.06088769e+00 1.71407703e-02 1.60032183e-01 -1.61021389e-02
-4.65260029e-01 -3.54801744e-01 -7.89501548e-01 -5.38766980e-01
4.41756576e-01 -1.14354692e-01 2.15809137e-01 3.88403803e-01
-5.96565425e-01 6.83732331e-01 1.11033058e+00 8.61530006e-01
-1.48576707e-01 1.11748576e+00 3.42844248e-01 -8.33445191e-02
3.36354747e-02 3.10089946e-01 -1.54736900e+00 -4.20448691e-01
8.92356411e-02 -1.90214276e-01 -7.60470182e-02 -9.25956726e-01
-2.31246114e-01 3.78083646e-01 -9.29461479e-01 -2.05470651e-01
-1.10455379e-01 2.51403034e-01 8.28987211e-02 4.65330124e-01
-1.59002924e+00 1.67836659e-02 -1.03855811e-01 4.42655265e-01
5.59934914e-01 4.51579571e-01 -7.67547116e-02 -4.73889589e-01
-1.16150534e+00 2.94715017e-01 2.40399241e-01 3.64251673e-01
5.29475212e-01 2.42404942e-03 1.62730403e-02 -1.22207522e-01
-1.02022350e+00 -1.01030040e+00 -3.02590966e-01 -2.43045136e-01
-7.07274854e-01 1.77668497e-01 2.10999519e-01 7.66401470e-01
3.03304732e-01 -9.95232444e-03 -5.04402518e-01 -5.96487880e-01
4.28530633e-01 7.56300837e-02 1.18148172e+00 2.74924375e-02
1.09997904e+00 1.69377640e-01 1.15801789e-01 7.44199634e-01
-1.96190163e-01 -5.51071048e-01 -3.15140635e-01 -7.55082488e-01
-5.86989045e-01 4.44423974e-01 -3.26272547e-01 -5.73182702e-01
-4.43318665e-01 3.59878451e-01 -4.29275706e-02 8.31856728e-01
6.22972071e-01 -2.17173025e-01 -9.20350194e-01 9.19905782e-01
-7.29426295e-02 5.15981987e-02 -9.65983048e-02 -1.27199262e-01
-3.96581441e-01 4.10287194e-02 2.23799735e-01 2.97161460e-01
2.92265236e-01 -5.09368777e-01 -5.68877220e-01 4.27781045e-01
4.16459739e-01 4.65236485e-01 1.06364763e+00 -6.52427852e-01
-8.28918576e-01 3.47210914e-02 3.42104435e-01 1.88819021e-01
5.04421771e-01 -2.34061807e-01 1.80037186e-01 4.29086864e-01
2.30355531e-01 -2.83437073e-01 2.34264821e-01 -5.11488378e-01
4.76539314e-01 1.56475782e-01 -1.47166222e-01 -1.02309191e+00
-5.59814811e-01 -3.14807624e-01 1.36164622e-02 2.48336405e-01
-5.14447033e-01 -9.95983899e-01 2.44898498e-02 -2.81420350e-02
2.93588758e-01 -6.17680728e-01 2.71538556e-01 -6.88656926e-01
5.12018561e-01 -5.74781522e-02 -2.89483726e-01 -2.38752604e-01
5.62780797e-01 -1.02241468e+00 -6.51534200e-01 2.27026194e-01
3.18955034e-01 8.17963704e-02 -5.93574420e-02 -1.17566586e+00
-4.10225168e-02 -2.96685398e-01 5.82193732e-01 -7.70743072e-01
-7.15863481e-02 4.76808727e-01 3.29380572e-01 -5.99579334e-01
5.35179069e-03 -3.21955502e-01 1.17016971e+00 -1.79935068e-01
-5.21227658e-01 -2.49460310e-01 4.84306246e-01 -2.64465153e-01
-2.03607529e-01 3.04992557e-01 -1.25715005e+00 7.55809188e-01
-6.03417039e-01 8.71127471e-02 -1.06220879e-01 -5.40654659e-01
-5.11184096e-01 -4.32208218e-02 6.84743106e-01 -9.05072093e-01
4.51821312e-02 -2.63025343e-01 -7.73667634e-01 -7.93841958e-01
-3.95872891e-01 2.98925154e-02 1.12445605e+00 8.02642941e-01
-3.85727108e-01 -7.29575157e-01 6.11615479e-01 -1.75381213e-01
-1.70760036e-01 -1.05162525e+00 1.05051017e+00 -6.94110632e-01
6.68203294e-01 -1.40023530e-01 4.58647013e-01 5.88184372e-02
3.39238942e-01 2.20731258e-01 -4.91491079e-01 8.13486099e-01
1.32252109e+00 1.83042541e-01 2.82913625e-01 -4.13827658e-01
2.75093645e-01 -1.03679979e+00 4.73541558e-01 6.67740345e-01
-7.56594315e-02 9.01946127e-02 -8.08835685e-01 -1.11946911e-02
-4.65080068e-02 7.15481877e-01 -1.27312958e-01 -6.92539990e-01
-7.13321805e-01 2.09888488e-01 -3.56735557e-01 -2.66319543e-01
-4.60457742e-01 7.38253538e-03 -8.48066330e-01 -8.13465118e-01
2.13946342e-01 -5.31533599e-01 -8.76827091e-02 3.71386945e-01
4.14129198e-01 8.61194253e-01 8.82488936e-02 3.36408019e-01
8.24467689e-02 1.00937831e+00 1.82786733e-01 4.32668254e-02
1.73484877e-01 -1.22647047e+00 -1.27435565e-01 -7.31793106e-01
9.08650219e-01 -8.02064896e-01 2.60243356e-01 8.27428102e-02
1.52959555e-01 1.81248933e-01 -7.75716007e-01 3.96855772e-01
6.91959858e-01 -2.00028941e-01 -1.84013590e-01 7.82088488e-02
-4.08993483e-01 -3.83011028e-02 8.61753106e-01 -2.74388075e-01
-9.74847972e-02 -1.02602720e+00 -1.26833722e-01 1.11962497e+00
6.53884351e-01 1.42315373e-01 -4.75912750e-01 -3.21260281e-02
-2.65989333e-01 -1.16977885e-01 -5.93443096e-01 6.56192124e-01
-5.73520660e-01 -7.07489491e-01 -7.29676127e-01 6.20043557e-03
6.79842353e-01 4.15460885e-01 -3.41880143e-01 2.28170443e+00
-1.02978444e+00 4.97357070e-01 -4.68666613e-01 1.19644988e+00
-6.38581872e-01 -1.35883436e-01 -7.98879743e-01 -5.45745015e-01
-4.36387926e-01 -4.08294976e-01 -2.27469355e-01 -1.78951710e-01
5.60200289e-02 2.35111445e-01 -8.29315543e-01 1.66124683e-02
-8.07581782e-01 -6.34335399e-01 3.33200425e-01 2.99568564e-01
-8.49243045e-01 5.52447960e-02 8.02986920e-01 4.63941514e-01
6.54758275e-01 -5.37097454e-04 -2.04843923e-01 9.76368427e-01
-3.53015751e-01 9.11225975e-01 7.22659290e-01 -3.19766104e-01
2.27475837e-01 -2.76821464e-01 4.26936716e-01 3.22493613e-01
-4.22099531e-01 2.96951920e-01 6.81850255e-01 1.47002387e+00
-2.75375154e-02 -7.22703218e-01 3.05495150e-02 -5.42968288e-02
-5.06122649e-01 4.57347259e-02 8.26341063e-02 4.99086320e-01
9.00193095e-01 -8.83195698e-01 -9.96071637e-01 -2.98155367e-01
-4.14106518e-01 -5.26974797e-01 -5.91103375e-01 -2.92363405e-01]
#@title Sematic Search Form
# code adapted from https://github.com/UKPLab/sentence-transformers/blob/master/examples/application_semantic_search.py
query = 'Nobody has sane thoughts' #@param {type: 'string'}
queries = [query]
query_embeddings = model.encode(queries)
# Find the closest 3 sentences of the corpus for each query sentence based on cosine similarity
number_top_matches = 3 #@param {type: "number"}
print("Semantic Search Results")
for query, query_embedding in zip(queries, query_embeddings):
distances = scipy.spatial.distance.cdist([query_embedding], sentence_embeddings, "cosine")[0]
results = zip(range(len(distances)), distances)
results = sorted(results, key=lambda x: x[1])
print("\n\n======================\n\n")
print("Query:", query)
print("\nTop 5 most similar sentences in corpus:")
for idx, distance in results[0:number_top_matches]:
print(sentences[idx].strip(), "(Cosine Score: %.4f)" % (1-distance))
Semantic Search Results
======================
Query: Nobody has sane thoughts
Top 5 most similar sentences in corpus:
Lack of saneness (Cosine Score: 0.8958)
Absence of sanity (Cosine Score: 0.8744)
A man is riding a horse. (Cosine Score: 0.1705) | [
{
"code": null,
"e": 1072,
"s": 172,
"text": "I’ve been working on a tool that needed to embed semantic search based on BERT. The idea was simple: get BERT encodings for each sentence in the corpus and then use cosine similarity to match to a query (either a word or another short sentence). Depending upon the size of the corpus returning a BERT embedding for each sentence takes a while. I was tempted to use a simpler model (eg ELMO or BERT-As-A-Service) until I came across the “Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks” 2019 ACL paper by Nils Reimers and Iryna Gurevych. Source code for the paper was available from Github and PyPi had the Sentence-BERT library ready to be pip installed (if you use Python). In this blog post, I’ll briefly describe the problem the paper solves and present a Google Collab notebook that illustrates just how easy it is to achieve semantic search functionality using a SOTA BERT model."
},
{
"code": null,
"e": 1659,
"s": 1072,
"text": "BERT uses cross-encoder networks that take 2 sentences as input to the transformer network and then predict a target value. BERT is able to achieve SOTA performance on Semantic Textual Similarity tasks but both sentences must be passed through the full network. In a corpus consisting of 10000 sentences, finding similar pairs of sentences requires about 50 million inference computations taking approximately 65 hours (if you have the right computation capacity power eg. V100 GPU). Sentence-BERT impressively can provide the encodings for 10000 sentences in approximately 5 seconds!!!"
},
{
"code": null,
"e": 2018,
"s": 1659,
"text": "Sentence-BERT finetunes a pre-trained BERT network using Siamese and triplet network structures and adds a pooling operation to the output of BERT to derive a fixed-sized sentence embedding vector. The produced embedding vector is more appropriate for sentence similarity comparisons within a vector space (i.e. that can be compared using cosine similarity)."
},
{
"code": null,
"e": 2259,
"s": 2018,
"text": "The popular BERT-As-A-Service library runs a sentence through BERT and derives a fixed-sized vector by averaging the outputs of the model. BERT-As-A-Service has also not been evaluated in the context of producing useful sentence embeddings."
},
{
"code": null,
"e": 2447,
"s": 2259,
"text": "I’ve created a Google Colab notebook to illustrate using the Sentence-BERT library to create a semantic search example. The Github repo is available here: SiameseBERT_SemanticSearch.ipynb"
},
{
"code": null,
"e": 2505,
"s": 2447,
"text": "A gist version of the Collab Notebook is displayed below:"
},
{
"code": null,
"e": 2674,
"s": 2505,
"text": "This Google Colab Notebook illustrates using the Sentence Transformer python library to quickly create BERT embeddings for sentences and perform fast semantic searches."
},
{
"code": null,
"e": 2902,
"s": 2674,
"text": "The Sentence Transformer library is available on pypi and github. The library implements code from the ACL 2019 paper entitled \"Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks\" by Nils Reimers and Iryna Gurevych."
},
{
"code": null,
"e": 2970,
"s": 2902,
"text": "# Install the library using pip\n!pip install sentence-transformers\n"
},
{
"code": null,
"e": 8060,
"s": 2970,
"text": "Collecting sentence-transformers\n Downloading https://files.pythonhosted.org/packages/c9/91/c85ddef872d5bb39949386930c1f834ac382e145fcd30155b09d6fb65c5a/sentence-transformers-0.2.5.tar.gz (49kB)\n |████████████████████████████████| 51kB 1.7MB/s \nCollecting transformers==2.3.0\n Downloading https://files.pythonhosted.org/packages/50/10/aeefced99c8a59d828a92cc11d213e2743212d3641c87c82d61b035a7d5c/transformers-2.3.0-py3-none-any.whl (447kB)\n |████████████████████████████████| 450kB 7.2MB/s \nRequirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from sentence-transformers) (4.28.1)\nRequirement already satisfied: torch>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from sentence-transformers) (1.3.1)\nRequirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from sentence-transformers) (1.17.5)\nRequirement already satisfied: scikit-learn in /usr/local/lib/python3.6/dist-packages (from sentence-transformers) (0.22.1)\nRequirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from sentence-transformers) (1.4.1)\nRequirement already satisfied: nltk in /usr/local/lib/python3.6/dist-packages (from sentence-transformers) (3.2.5)\nRequirement already satisfied: boto3 in /usr/local/lib/python3.6/dist-packages (from transformers==2.3.0->sentence-transformers) (1.10.47)\nRequirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.6/dist-packages (from transformers==2.3.0->sentence-transformers) (2019.12.20)\nRequirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from transformers==2.3.0->sentence-transformers) (2.21.0)\nCollecting sacremoses\n Downloading https://files.pythonhosted.org/packages/a6/b4/7a41d630547a4afd58143597d5a49e07bfd4c42914d8335b2a5657efc14b/sacremoses-0.0.38.tar.gz (860kB)\n |████████████████████████████████| 870kB 26.9MB/s \nCollecting sentencepiece\n Downloading https://files.pythonhosted.org/packages/74/f4/2d5214cbf13d06e7cb2c20d84115ca25b53ea76fa1f0ade0e3c9749de214/sentencepiece-0.1.85-cp36-cp36m-manylinux1_x86_64.whl (1.0MB)\n |████████████████████████████████| 1.0MB 42.6MB/s \nRequirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn->sentence-transformers) (0.14.1)\nRequirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from nltk->sentence-transformers) (1.12.0)\nRequirement already satisfied: jmespath<1.0.0,>=0.7.1 in /usr/local/lib/python3.6/dist-packages (from boto3->transformers==2.3.0->sentence-transformers) (0.9.4)\nRequirement already satisfied: s3transfer<0.3.0,>=0.2.0 in /usr/local/lib/python3.6/dist-packages (from boto3->transformers==2.3.0->sentence-transformers) (0.2.1)\nRequirement already satisfied: botocore<1.14.0,>=1.13.47 in /usr/local/lib/python3.6/dist-packages (from boto3->transformers==2.3.0->sentence-transformers) (1.13.47)\nRequirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->transformers==2.3.0->sentence-transformers) (3.0.4)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->transformers==2.3.0->sentence-transformers) (2019.11.28)\nRequirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->transformers==2.3.0->sentence-transformers) (1.24.3)\nRequirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->transformers==2.3.0->sentence-transformers) (2.8)\nRequirement already satisfied: click in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers==2.3.0->sentence-transformers) (7.0)\nRequirement already satisfied: docutils<0.16,>=0.10 in /usr/local/lib/python3.6/dist-packages (from botocore<1.14.0,>=1.13.47->boto3->transformers==2.3.0->sentence-transformers) (0.15.2)\nRequirement already satisfied: python-dateutil<3.0.0,>=2.1; python_version >= \"2.7\" in /usr/local/lib/python3.6/dist-packages (from botocore<1.14.0,>=1.13.47->boto3->transformers==2.3.0->sentence-transformers) (2.6.1)\nBuilding wheels for collected packages: sentence-transformers, sacremoses\n Building wheel for sentence-transformers (setup.py) ... done\n Created wheel for sentence-transformers: filename=sentence_transformers-0.2.5-cp36-none-any.whl size=64943 sha256=973f7a74060aad6ed6f617b3879e3340babb4d0ecd2d47508f1538ef02d1a587\n Stored in directory: /root/.cache/pip/wheels/b4/ce/39/5bbda8ac34eb52df8c6531382ca077773fbfcbfb6386e5d66c\n Building wheel for sacremoses (setup.py) ... done\n Created wheel for sacremoses: filename=sacremoses-0.0.38-cp36-none-any.whl size=884629 sha256=63585f2eb5e65adb473e2e282bda1bdc423a86bfde2a175308c56709911f6678\n Stored in directory: /root/.cache/pip/wheels/6d/ec/1a/21b8912e35e02741306f35f66c785f3afe94de754a0eaf1422\nSuccessfully built sentence-transformers sacremoses\nInstalling collected packages: sacremoses, sentencepiece, transformers, sentence-transformers\nSuccessfully installed sacremoses-0.0.38 sentence-transformers-0.2.5 sentencepiece-0.1.85 transformers-2.3.0\n"
},
{
"code": null,
"e": 8499,
"s": 8060,
"text": "from sentence_transformers import SentenceTransformer\n\n# Load the BERT model. Various models trained on Natural Language Inference (NLI) https://github.com/UKPLab/sentence-transformers/blob/master/docs/pretrained-models/nli-models.md and \n# Semantic Textual Similarity are available https://github.com/UKPLab/sentence-transformers/blob/master/docs/pretrained-models/sts-models.md\n\nmodel = SentenceTransformer('bert-base-nli-mean-tokens')\n"
},
{
"code": null,
"e": 8719,
"s": 8499,
"text": "\nThe default version of TensorFlow in Colab will soon switch to TensorFlow 2.x.\nWe recommend you upgrade now \nor ensure your notebook will continue to use TensorFlow 1.x via the %tensorflow_version 1.x magic:\nmore info."
},
{
"code": null,
"e": 8771,
"s": 8719,
"text": "100%|██████████| 405M/405M [00:18<00:00, 21.8MB/s]\n"
},
{
"code": null,
"e": 9614,
"s": 8771,
"text": "# A corpus is a list with documents split by sentences.\n\nsentences = ['Absence of sanity', \n 'Lack of saneness',\n 'A man is eating food.',\n 'A man is eating a piece of bread.',\n 'The girl is carrying a baby.',\n 'A man is riding a horse.',\n 'A woman is playing violin.',\n 'Two men pushed carts through the woods.',\n 'A man is riding a white horse on an enclosed ground.',\n 'A monkey is playing drums.',\n 'A cheetah is running behind its prey.']\n\n# Each sentence is encoded as a 1-D vector with 78 columns\nsentence_embeddings = model.encode(sentences)\n\nprint('Sample BERT embedding vector - length', len(sentence_embeddings[0]))\n\nprint('Sample BERT embedding vector - note includes negative values', sentence_embeddings[0])\n"
},
{
"code": null,
"e": 22199,
"s": 9614,
"text": "Sample BERT embedding vector - length 768\nSample BERT embedding vector - note includes negative values [ 2.95403183e-01 2.91810960e-01 2.16480136e+00 2.20419839e-01\n -1.30865965e-02 1.01950336e+00 1.51298153e+00 2.34131858e-01\n 2.73058057e-01 1.35122865e-01 -1.11313331e+00 -1.25884697e-01\n 1.45378590e-01 9.77708638e-01 1.39352250e+00 4.57705110e-01\n -5.82131505e-01 -7.24940956e-01 -3.61734480e-01 -2.27514893e-01\n 1.66630689e-02 2.04861969e-01 6.55133009e-01 -1.29376340e+00\n -7.26099372e-01 -1.91135541e-01 -3.07211697e-01 -1.30278623e+00\n -1.42963886e+00 5.67453261e-03 3.54811519e-01 4.83712614e-01\n 6.65388048e-01 5.33848584e-01 6.40496492e-01 5.90408444e-01\n 7.83850178e-02 -1.07759213e+00 -1.24676526e-01 -3.98406386e-01\n 7.36313939e-01 5.28293252e-01 5.63290775e-01 4.14546162e-01\n 4.49179649e-01 -9.58786383e-02 1.45424592e+00 -2.69145072e-01\n -2.44059876e-01 -1.10387051e+00 -2.00923532e-01 -2.17437861e-03\n 1.83387971e+00 1.06518459e+00 -5.11945903e-01 -1.11248529e+00\n 5.59790373e-01 -5.89609563e-01 1.07621944e+00 7.49265671e-01\n 4.32666481e-01 1.76307142e-01 -1.72125660e-02 1.19170345e-01\n -8.37448120e-01 1.88445479e-01 -7.46789854e-03 1.70312412e-02\n -4.29175943e-01 -5.72340369e-01 6.22608125e-01 -3.38023841e-01\n 1.03712715e-01 2.42106587e-01 -9.82075334e-01 -2.63344377e-01\n 4.15540874e-01 2.79155314e-01 -1.03487372e-01 7.32837498e-01\n 2.78023511e-01 7.52160132e-01 8.08235168e-01 -4.87504005e-01\n -7.64050961e-01 -7.08029419e-02 5.39888680e-01 2.24032193e-01\n -1.66969836e+00 -2.01102495e-01 2.13853925e-01 1.08926618e+00\n 5.79520047e-01 -3.32589626e-01 -9.75302875e-01 2.37982087e-02\n -1.68780282e-01 2.63479292e-01 1.64727420e-01 2.03110695e-01\n 8.12745094e-03 3.75387013e-01 4.53516781e-01 4.21480648e-02\n 4.72985119e-01 3.53581369e-01 -1.55092627e-01 3.71253103e-01\n 3.54824960e-01 5.11555187e-02 -9.36767399e-01 1.42013264e+00\n 7.63064623e-01 -8.58592212e-01 -5.74659705e-01 2.43800841e-02\n -1.39292669e+00 3.14162791e-01 -2.08897144e-02 4.01286274e-01\n 8.56514335e-01 2.12013125e-01 1.93166375e-01 -8.65448266e-02\n 3.66492569e-01 -5.34847438e-01 9.08364177e-01 -1.47459909e-01\n -4.34119612e-01 1.38952568e-01 -2.85755783e-01 8.91503990e-01\n -9.49378788e-01 -6.12362102e-02 -1.63513094e-01 2.15337463e-02\n 9.33672637e-02 -1.83846831e-01 -7.05079511e-02 -9.50030535e-02\n -7.78035462e-01 5.08425236e-01 -2.38957599e-01 1.18628956e-01\n -2.22939938e-01 -4.55788314e-01 7.77875900e-01 5.58182418e-01\n -6.46435559e-01 -3.76423895e-01 -9.94759917e-01 -2.24633545e-01\n 2.56237477e-01 3.92683744e-01 -3.80205333e-01 -5.66550314e-01\n 1.06151199e+00 6.39036715e-01 2.45125726e-01 -2.10276559e-01\n -2.03608587e-01 5.58223248e-01 5.87122440e-02 4.09846961e-01\n 9.85415801e-02 5.68384044e-02 -3.91428530e-01 2.61983126e-01\n 1.85061485e-01 -7.71071732e-01 6.81889176e-01 -6.14751518e-01\n -9.09989655e-01 -5.37011623e-01 -2.67421097e-01 6.41145855e-02\n -1.47129208e-01 8.36788297e-01 2.73965627e-01 2.99047649e-01\n 1.75318837e-01 -8.45175162e-02 1.32096362e+00 -1.32269931e+00\n -8.96274865e-01 -7.21393704e-01 9.03015211e-02 -5.28525472e-01\n -5.90585284e-02 -1.73461944e-01 -1.08447266e+00 -9.68358815e-01\n 7.07607031e-01 -1.08554244e+00 7.90785030e-02 -1.23736322e-01\n 1.04828671e-01 -4.38560009e-01 -9.64857712e-02 1.21586382e-01\n 7.08318591e-01 -7.40591824e-01 -6.13734312e-02 5.97689033e-01\n 5.36595702e-01 9.54430461e-01 5.82716949e-02 -7.02314198e-01\n -5.21191716e-01 -5.31055272e-01 -6.87113464e-01 -2.28840038e-01\n -1.25095084e-01 3.82895499e-01 9.40875232e-01 -1.53620028e+00\n 3.08551461e-01 -1.07018912e+00 -9.22982693e-02 1.83376744e-01\n 2.36132234e-01 -9.44777846e-01 3.63419414e-01 1.02015033e-01\n -2.61932522e-01 1.31475377e+00 -8.66960660e-02 4.19597805e-01\n -5.64485192e-01 -2.40892217e-01 9.56280604e-02 2.88403451e-01\n -1.26559651e+00 9.68216509e-02 -6.86096549e-01 -9.73237216e-01\n 4.98169512e-01 -6.72291875e-01 6.18023753e-01 -2.36299157e-01\n -1.19642895e-02 2.23920777e-01 1.29233646e+00 9.04313385e-01\n -6.94556832e-01 2.12914258e-01 1.41126677e-01 -1.09073651e+00\n -2.61027157e-01 3.72416407e-01 5.65627873e-01 -7.63028026e-01\n 2.54305422e-01 2.96842039e-01 6.39281869e-01 -3.68397057e-01\n -1.50474444e-01 -2.06995815e-01 4.89718974e-01 -1.07649386e+00\n -4.69321489e-01 5.64345777e-01 -8.54324996e-01 2.01307058e-01\n -3.64126265e-01 -4.83238310e-01 -2.99138606e-01 -2.37890765e-01\n -7.14595199e-01 3.88846397e-02 2.88149297e-01 -8.43381286e-01\n -1.32528901e-01 3.20764244e-01 -5.64771175e-01 -6.50783896e-01\n 1.23112619e+00 -3.79267991e-01 -5.36719501e-01 -1.18963256e-01\n 5.57513535e-01 7.38234401e-01 -1.65188718e+00 4.81852919e-01\n -9.48715389e-01 9.54266250e-01 6.12537324e-01 2.52186596e-01\n -2.26502508e-01 -1.06311001e-01 -6.21922791e-01 7.16752052e-01\n -3.86202455e-01 -7.54139066e-01 5.86001515e-01 -2.63744980e-01\n 2.03416556e-01 -5.31250715e-01 -9.58163381e-01 7.24046588e-01\n -6.24141991e-01 -1.32546872e-01 -7.14519739e-01 2.18565226e-01\n -6.77284122e-01 -1.44099727e-01 -3.61371309e-01 8.55807483e-01\n 4.30027187e-01 5.20425677e-01 -1.25135791e+00 8.63247830e-03\n -8.13418508e-01 -1.89723641e-01 6.97539449e-01 -2.71261573e-01\n -9.60209668e-01 -5.67387223e-01 -1.97102293e-01 -8.45597088e-01\n 4.09596503e-01 4.65882063e-01 1.00616157e-01 1.79212242e-01\n 3.18223983e-01 -1.94156840e-01 -2.31451839e-02 5.31907439e-01\n 2.07857490e-01 -1.38748586e-01 -1.25763610e-01 -1.67028809e+00\n 7.72697479e-02 3.29649597e-01 9.59621310e-01 9.71129060e-01\n -8.59887302e-01 -7.97947407e-01 -4.50175434e-01 6.09351099e-01\n -9.92598385e-02 -1.26160526e+00 -4.80852902e-01 -4.37261537e-02\n 7.61089265e-01 -4.90454495e-01 -1.16635013e+00 -1.26680553e+00\n 4.23249960e-01 -3.28321755e-01 1.13249719e-01 1.19094634e+00\n -4.76775408e-01 2.77292818e-01 -6.62052512e-01 -6.26967430e-01\n -3.28043163e-01 4.62100357e-01 4.22713980e-02 1.11225937e-02\n 3.49018514e-01 3.41067076e-01 -2.20341116e-01 -8.18507969e-01\n 6.06628835e-01 -6.28642023e-01 2.82574117e-01 4.81881082e-01\n 1.42555833e+00 -1.52616878e-03 -5.17759204e-01 -2.46807709e-02\n -5.39778233e-01 2.85306722e-01 -2.21777245e-01 -1.85012728e-01\n 3.11429322e-01 -2.07644105e-01 -2.50214398e-01 -9.53149140e-01\n 4.12619442e-01 3.92308757e-02 1.41120523e-01 -3.55187565e-01\n 1.18068099e+00 -3.14618677e-01 4.79557097e-01 -4.70073700e-01\n 1.77134991e-01 6.75846696e-01 9.84487832e-01 2.68136203e-01\n -7.01508764e-03 -2.85394371e-01 -1.52261570e-01 -1.11626387e+00\n 1.02338985e-01 5.77064395e-01 3.41381252e-01 4.19948399e-01\n 4.03284848e-01 2.95105875e-01 9.24367547e-01 1.26249242e+00\n 1.20447159e+00 9.47556794e-01 4.87714596e-02 4.61912721e-01\n -8.18414986e-01 4.46733892e-01 6.60865068e-01 4.44435418e-01\n -9.46657002e-01 3.16685140e-01 -5.51689267e-01 -1.82610482e-01\n -1.46252900e-01 -1.01644254e+00 7.33198643e-01 1.08742762e+00\n -6.23244762e-01 -6.87371850e-01 -1.63677886e-01 2.05873415e-01\n -1.28120184e-04 1.58518422e+00 -2.15279460e-01 -3.93540442e-01\n -2.25850105e-01 -4.96896729e-02 -3.16225171e-01 -2.08421387e-02\n -7.36599624e-01 5.96843779e-01 -6.45120263e-01 -5.47669291e-01\n 1.46693140e-01 -1.00796354e+00 2.46947721e-01 -1.16965592e-01\n 1.06088769e+00 1.71407703e-02 1.60032183e-01 -1.61021389e-02\n -4.65260029e-01 -3.54801744e-01 -7.89501548e-01 -5.38766980e-01\n 4.41756576e-01 -1.14354692e-01 2.15809137e-01 3.88403803e-01\n -5.96565425e-01 6.83732331e-01 1.11033058e+00 8.61530006e-01\n -1.48576707e-01 1.11748576e+00 3.42844248e-01 -8.33445191e-02\n 3.36354747e-02 3.10089946e-01 -1.54736900e+00 -4.20448691e-01\n 8.92356411e-02 -1.90214276e-01 -7.60470182e-02 -9.25956726e-01\n -2.31246114e-01 3.78083646e-01 -9.29461479e-01 -2.05470651e-01\n -1.10455379e-01 2.51403034e-01 8.28987211e-02 4.65330124e-01\n -1.59002924e+00 1.67836659e-02 -1.03855811e-01 4.42655265e-01\n 5.59934914e-01 4.51579571e-01 -7.67547116e-02 -4.73889589e-01\n -1.16150534e+00 2.94715017e-01 2.40399241e-01 3.64251673e-01\n 5.29475212e-01 2.42404942e-03 1.62730403e-02 -1.22207522e-01\n -1.02022350e+00 -1.01030040e+00 -3.02590966e-01 -2.43045136e-01\n -7.07274854e-01 1.77668497e-01 2.10999519e-01 7.66401470e-01\n 3.03304732e-01 -9.95232444e-03 -5.04402518e-01 -5.96487880e-01\n 4.28530633e-01 7.56300837e-02 1.18148172e+00 2.74924375e-02\n 1.09997904e+00 1.69377640e-01 1.15801789e-01 7.44199634e-01\n -1.96190163e-01 -5.51071048e-01 -3.15140635e-01 -7.55082488e-01\n -5.86989045e-01 4.44423974e-01 -3.26272547e-01 -5.73182702e-01\n -4.43318665e-01 3.59878451e-01 -4.29275706e-02 8.31856728e-01\n 6.22972071e-01 -2.17173025e-01 -9.20350194e-01 9.19905782e-01\n -7.29426295e-02 5.15981987e-02 -9.65983048e-02 -1.27199262e-01\n -3.96581441e-01 4.10287194e-02 2.23799735e-01 2.97161460e-01\n 2.92265236e-01 -5.09368777e-01 -5.68877220e-01 4.27781045e-01\n 4.16459739e-01 4.65236485e-01 1.06364763e+00 -6.52427852e-01\n -8.28918576e-01 3.47210914e-02 3.42104435e-01 1.88819021e-01\n 5.04421771e-01 -2.34061807e-01 1.80037186e-01 4.29086864e-01\n 2.30355531e-01 -2.83437073e-01 2.34264821e-01 -5.11488378e-01\n 4.76539314e-01 1.56475782e-01 -1.47166222e-01 -1.02309191e+00\n -5.59814811e-01 -3.14807624e-01 1.36164622e-02 2.48336405e-01\n -5.14447033e-01 -9.95983899e-01 2.44898498e-02 -2.81420350e-02\n 2.93588758e-01 -6.17680728e-01 2.71538556e-01 -6.88656926e-01\n 5.12018561e-01 -5.74781522e-02 -2.89483726e-01 -2.38752604e-01\n 5.62780797e-01 -1.02241468e+00 -6.51534200e-01 2.27026194e-01\n 3.18955034e-01 8.17963704e-02 -5.93574420e-02 -1.17566586e+00\n -4.10225168e-02 -2.96685398e-01 5.82193732e-01 -7.70743072e-01\n -7.15863481e-02 4.76808727e-01 3.29380572e-01 -5.99579334e-01\n 5.35179069e-03 -3.21955502e-01 1.17016971e+00 -1.79935068e-01\n -5.21227658e-01 -2.49460310e-01 4.84306246e-01 -2.64465153e-01\n -2.03607529e-01 3.04992557e-01 -1.25715005e+00 7.55809188e-01\n -6.03417039e-01 8.71127471e-02 -1.06220879e-01 -5.40654659e-01\n -5.11184096e-01 -4.32208218e-02 6.84743106e-01 -9.05072093e-01\n 4.51821312e-02 -2.63025343e-01 -7.73667634e-01 -7.93841958e-01\n -3.95872891e-01 2.98925154e-02 1.12445605e+00 8.02642941e-01\n -3.85727108e-01 -7.29575157e-01 6.11615479e-01 -1.75381213e-01\n -1.70760036e-01 -1.05162525e+00 1.05051017e+00 -6.94110632e-01\n 6.68203294e-01 -1.40023530e-01 4.58647013e-01 5.88184372e-02\n 3.39238942e-01 2.20731258e-01 -4.91491079e-01 8.13486099e-01\n 1.32252109e+00 1.83042541e-01 2.82913625e-01 -4.13827658e-01\n 2.75093645e-01 -1.03679979e+00 4.73541558e-01 6.67740345e-01\n -7.56594315e-02 9.01946127e-02 -8.08835685e-01 -1.11946911e-02\n -4.65080068e-02 7.15481877e-01 -1.27312958e-01 -6.92539990e-01\n -7.13321805e-01 2.09888488e-01 -3.56735557e-01 -2.66319543e-01\n -4.60457742e-01 7.38253538e-03 -8.48066330e-01 -8.13465118e-01\n 2.13946342e-01 -5.31533599e-01 -8.76827091e-02 3.71386945e-01\n 4.14129198e-01 8.61194253e-01 8.82488936e-02 3.36408019e-01\n 8.24467689e-02 1.00937831e+00 1.82786733e-01 4.32668254e-02\n 1.73484877e-01 -1.22647047e+00 -1.27435565e-01 -7.31793106e-01\n 9.08650219e-01 -8.02064896e-01 2.60243356e-01 8.27428102e-02\n 1.52959555e-01 1.81248933e-01 -7.75716007e-01 3.96855772e-01\n 6.91959858e-01 -2.00028941e-01 -1.84013590e-01 7.82088488e-02\n -4.08993483e-01 -3.83011028e-02 8.61753106e-01 -2.74388075e-01\n -9.74847972e-02 -1.02602720e+00 -1.26833722e-01 1.11962497e+00\n 6.53884351e-01 1.42315373e-01 -4.75912750e-01 -3.21260281e-02\n -2.65989333e-01 -1.16977885e-01 -5.93443096e-01 6.56192124e-01\n -5.73520660e-01 -7.07489491e-01 -7.29676127e-01 6.20043557e-03\n 6.79842353e-01 4.15460885e-01 -3.41880143e-01 2.28170443e+00\n -1.02978444e+00 4.97357070e-01 -4.68666613e-01 1.19644988e+00\n -6.38581872e-01 -1.35883436e-01 -7.98879743e-01 -5.45745015e-01\n -4.36387926e-01 -4.08294976e-01 -2.27469355e-01 -1.78951710e-01\n 5.60200289e-02 2.35111445e-01 -8.29315543e-01 1.66124683e-02\n -8.07581782e-01 -6.34335399e-01 3.33200425e-01 2.99568564e-01\n -8.49243045e-01 5.52447960e-02 8.02986920e-01 4.63941514e-01\n 6.54758275e-01 -5.37097454e-04 -2.04843923e-01 9.76368427e-01\n -3.53015751e-01 9.11225975e-01 7.22659290e-01 -3.19766104e-01\n 2.27475837e-01 -2.76821464e-01 4.26936716e-01 3.22493613e-01\n -4.22099531e-01 2.96951920e-01 6.81850255e-01 1.47002387e+00\n -2.75375154e-02 -7.22703218e-01 3.05495150e-02 -5.42968288e-02\n -5.06122649e-01 4.57347259e-02 8.26341063e-02 4.99086320e-01\n 9.00193095e-01 -8.83195698e-01 -9.96071637e-01 -2.98155367e-01\n -4.14106518e-01 -5.26974797e-01 -5.91103375e-01 -2.92363405e-01]\n"
},
{
"code": null,
"e": 23174,
"s": 22199,
"text": "#@title Sematic Search Form\n\n# code adapted from https://github.com/UKPLab/sentence-transformers/blob/master/examples/application_semantic_search.py\n\nquery = 'Nobody has sane thoughts' #@param {type: 'string'}\n\nqueries = [query]\nquery_embeddings = model.encode(queries)\n\n# Find the closest 3 sentences of the corpus for each query sentence based on cosine similarity\nnumber_top_matches = 3 #@param {type: \"number\"}\n\nprint(\"Semantic Search Results\")\n\nfor query, query_embedding in zip(queries, query_embeddings):\n distances = scipy.spatial.distance.cdist([query_embedding], sentence_embeddings, \"cosine\")[0]\n\n results = zip(range(len(distances)), distances)\n results = sorted(results, key=lambda x: x[1])\n\n print(\"\\n\\n======================\\n\\n\")\n print(\"Query:\", query)\n print(\"\\nTop 5 most similar sentences in corpus:\")\n\n for idx, distance in results[0:number_top_matches]:\n print(sentences[idx].strip(), \"(Cosine Score: %.4f)\" % (1-distance))\n"
}
] |
What are the member variables of a class in C#? | A class is a blueprint that has member variables and functions in C#. This describes the behavior of an object.
Let us see the syntax of a class to learn what are member variables −
<access specifier> class class_name {
// member variables
<access specifier> <data type> variable1;
<access specifier> <data type> variable2;
...
<access specifier> <data type> variableN;
// member methods
<access specifier> <return type> method1(parameter_list) {
// method body
}
<access specifier> <return type> method2(parameter_list) {
// method body
}
...
<access specifier> <return type> methodN(parameter_list) {
// method body
}
}
Member variables are the attributes of an object (from design perspective) and they are kept private to implement encapsulation. These variables can only be accessed using the public member functions.
Below length and width are member variables because a new instance/ of this variable will get created for each new instance of Rectangle class.
Live Demo
using System;
namespace RectangleApplication {
class Rectangle {
//member variables
private double length;
private double width;
public void Acceptdetails() {
length = 10;
width = 14;
}
public double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
} //end class Rectangle
class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}
Length: 10
Width: 14
Area: 140 | [
{
"code": null,
"e": 1174,
"s": 1062,
"text": "A class is a blueprint that has member variables and functions in C#. This describes the behavior of an object."
},
{
"code": null,
"e": 1244,
"s": 1174,
"text": "Let us see the syntax of a class to learn what are member variables −"
},
{
"code": null,
"e": 1741,
"s": 1244,
"text": "<access specifier> class class_name {\n // member variables\n <access specifier> <data type> variable1;\n <access specifier> <data type> variable2;\n ...\n <access specifier> <data type> variableN;\n // member methods\n <access specifier> <return type> method1(parameter_list) {\n // method body\n }\n <access specifier> <return type> method2(parameter_list) {\n // method body\n }\n ...\n <access specifier> <return type> methodN(parameter_list) {\n // method body\n }\n}"
},
{
"code": null,
"e": 1942,
"s": 1741,
"text": "Member variables are the attributes of an object (from design perspective) and they are kept private to implement encapsulation. These variables can only be accessed using the public member functions."
},
{
"code": null,
"e": 2086,
"s": 1942,
"text": "Below length and width are member variables because a new instance/ of this variable will get created for each new instance of Rectangle class."
},
{
"code": null,
"e": 2097,
"s": 2086,
"text": " Live Demo"
},
{
"code": null,
"e": 2831,
"s": 2097,
"text": "using System;\n\nnamespace RectangleApplication {\n class Rectangle {\n //member variables\n private double length;\n private double width;\n\n public void Acceptdetails() {\n length = 10;\n width = 14;\n }\n\n public double GetArea() {\n return length * width;\n }\n\n public void Display() {\n Console.WriteLine(\"Length: {0}\", length);\n Console.WriteLine(\"Width: {0}\", width);\n Console.WriteLine(\"Area: {0}\", GetArea());\n }\n\n } //end class Rectangle\n\n class ExecuteRectangle {\n static void Main(string[] args) {\n Rectangle r = new Rectangle();\n r.Acceptdetails();\n r.Display();\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 2862,
"s": 2831,
"text": "Length: 10\nWidth: 14\nArea: 140"
}
] |
Learning Rate Schedules and Adaptive Learning Rate Methods for Deep Learning | by Suki Lau | Towards Data Science | When training deep neural networks, it is often useful to reduce learning rate as the training progresses. This can be done by using pre-defined learning rate schedules or adaptive learning rate methods. In this article, I train a convolutional neural network on CIFAR-10 using differing learning rate schedules and adaptive learning rate methods to compare their model performances.
Learning rate schedules seek to adjust the learning rate during training by reducing the learning rate according to a pre-defined schedule. Common learning rate schedules include time-based decay, step decay and exponential decay. For illustrative purpose, I construct a convolutional neural network trained on CIFAR-10, using stochastic gradient descent (SGD) optimization algorithm with different learning rate schedules to compare the performances.
Constant learning rate is the default learning rate schedule in SGD optimizer in Keras. Momentum and decay rate are both set to zero by default. It is tricky to choose the right learning rate. By experimenting with range of learning rates in our example, lr=0.1 shows a relative good performance to start with. This can serve as a baseline for us to experiment with different learning rate strategies.
keras.optimizers.SGD(lr=0.1, momentum=0.0, decay=0.0, nesterov=False)
The mathematical form of time-based decay is lr = lr0/(1+kt) where lr, k are hyperparameters and t is the iteration number. Looking into the source code of Keras, the SGD optimizer takes decay and lr arguments and update the learning rate by a decreasing factor in each epoch.
lr *= (1. / (1. + self.decay * self.iterations))
Momentum is another argument in SGD optimizer which we could tweak to obtain faster convergence. Unlike classical SGD, momentum method helps the parameter vector to build up velocity in any direction with constant gradient descent so as to prevent oscillations. A typical choice of momentum is between 0.5 to 0.9.
SGD optimizer also has an argument called nesterov which is set to false by default. Nesterov momentum is a different version of the momentum method which has stronger theoretical converge guarantees for convex functions. In practice, it works slightly better than standard momentum.
In Keras, we can implement time-based decay by setting the initial learning rate, decay rate and momentum in the SGD optimizer.
learning_rate = 0.1decay_rate = learning_rate / epochsmomentum = 0.8sgd = SGD(lr=learning_rate, momentum=momentum, decay=decay_rate, nesterov=False)
Step decay schedule drops the learning rate by a factor every few epochs. The mathematical form of step decay is :
lr = lr0 * drop^floor(epoch / epochs_drop)
A typical way is to to drop the learning rate by half every 10 epochs. To implement this in Keras, we can define a step decay function and use LearningRateScheduler callback to take the step decay function as argument and return the updated learning rates for use in SGD optimizer.
def step_decay(epoch): initial_lrate = 0.1 drop = 0.5 epochs_drop = 10.0 lrate = initial_lrate * math.pow(drop, math.floor((1+epoch)/epochs_drop)) return lratelrate = LearningRateScheduler(step_decay)
As a digression, a callback is a set of functions to be applied at given stages of the training procedure. We can use callbacks to get a view on internal states and statistics of the model during training. In our example, we create a custom callback by extending the base class keras.callbacks.Callback to record loss history and learning rate during the training procedure.
class LossHistory(keras.callbacks.Callback): def on_train_begin(self, logs={}): self.losses = [] self.lr = [] def on_epoch_end(self, batch, logs={}): self.losses.append(logs.get(‘loss’)) self.lr.append(step_decay(len(self.losses)))
Putting everything together, we can pass a callback list consisting of LearningRateScheduler callback and our custom callback to fit the model. We can then visualize the learning rate schedule and the loss history by accessing loss_history.lr and loss_history.losses.
loss_history = LossHistory()lrate = LearningRateScheduler(step_decay)callbacks_list = [loss_history, lrate]history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=epochs, batch_size=batch_size, callbacks=callbacks_list, verbose=2)
Another common schedule is exponential decay. It has the mathematical form lr = lr0 * e^(−kt), where lr, k are hyperparameters and t is the iteration number. Similarly, we can implement this by defining exponential decay function and pass it to LearningRateScheduler. In fact, any custom decay schedule can be implemented in Keras using this approach. The only difference is to define a different custom decay function.
def exp_decay(epoch): initial_lrate = 0.1 k = 0.1 lrate = initial_lrate * exp(-k*t) return lratelrate = LearningRateScheduler(exp_decay)
Let us now compare the model accuracy using different learning rate schedules in our example.
The challenge of using learning rate schedules is that their hyperparameters have to be defined in advance and they depend heavily on the type of model and problem. Another problem is that the same learning rate is applied to all parameter updates. If we have sparse data, we may want to update the parameters in different extent instead.
Adaptive gradient descent algorithms such as Adagrad, Adadelta, RMSprop, Adam, provide an alternative to classical SGD. These per-parameter learning rate methods provide heuristic approach without requiring expensive work in tuning hyperparameters for the learning rate schedule manually.
In brief, Adagrad performs larger updates for more sparse parameters and smaller updates for less sparse parameter. It has good performance with sparse data and training large-scale neural network. However, its monotonic learning rate usually proves too aggressive and stops learning too early when training deep neural networks. Adadelta is an extension of Adagrad that seeks to reduce its aggressive, monotonically decreasing learning rate. RMSprop adjusts the Adagrad method in a very simple way in an attempt to reduce its aggressive, monotonically decreasing learning rate. Adam is an update to the RMSProp optimizer which is like RMSprop with momentum.
In Keras, we can implement these adaptive learning algorithms easily using corresponding optimizers. It is usually recommended to leave the hyperparameters of these optimizers at their default values (except lr sometimes).
keras.optimizers.Adagrad(lr=0.01, epsilon=1e-08, decay=0.0)keras.optimizers.Adadelta(lr=1.0, rho=0.95, epsilon=1e-08, decay=0.0)keras.optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)
Let us now look at the model performances using different adaptive learning rate methods. In our example, Adadelta gives the best model accuracy among other adaptive learning rate methods.
Finally, we compare the performances of all the learning rate schedules and adaptive learning rate methods we have discussed.
In many examples I have worked on, adaptive learning rate methods demonstrate better performance than learning rate schedules, and they require much less effort in hyperparamater settings. We can also use LearningRateScheduler in Keras to create custom learning rate schedules which is specific to our data problem.
For further reading, Yoshua Bengio’s paper provides very good practical recommendations for tuning learning rate for deep learning, such as how to set initial learning rate, mini-batch size, number of epochs and use of early stopping and momentum.
Source code
Practical Recommendations for Gradient-Based Training of Deep Architectures by Yoshua Bengio
Convolutional Neural Networks for Visual Recognition
Using Learning Rate Schedules for Deep Learning Models in Python with Keras | [
{
"code": null,
"e": 556,
"s": 172,
"text": "When training deep neural networks, it is often useful to reduce learning rate as the training progresses. This can be done by using pre-defined learning rate schedules or adaptive learning rate methods. In this article, I train a convolutional neural network on CIFAR-10 using differing learning rate schedules and adaptive learning rate methods to compare their model performances."
},
{
"code": null,
"e": 1008,
"s": 556,
"text": "Learning rate schedules seek to adjust the learning rate during training by reducing the learning rate according to a pre-defined schedule. Common learning rate schedules include time-based decay, step decay and exponential decay. For illustrative purpose, I construct a convolutional neural network trained on CIFAR-10, using stochastic gradient descent (SGD) optimization algorithm with different learning rate schedules to compare the performances."
},
{
"code": null,
"e": 1410,
"s": 1008,
"text": "Constant learning rate is the default learning rate schedule in SGD optimizer in Keras. Momentum and decay rate are both set to zero by default. It is tricky to choose the right learning rate. By experimenting with range of learning rates in our example, lr=0.1 shows a relative good performance to start with. This can serve as a baseline for us to experiment with different learning rate strategies."
},
{
"code": null,
"e": 1480,
"s": 1410,
"text": "keras.optimizers.SGD(lr=0.1, momentum=0.0, decay=0.0, nesterov=False)"
},
{
"code": null,
"e": 1757,
"s": 1480,
"text": "The mathematical form of time-based decay is lr = lr0/(1+kt) where lr, k are hyperparameters and t is the iteration number. Looking into the source code of Keras, the SGD optimizer takes decay and lr arguments and update the learning rate by a decreasing factor in each epoch."
},
{
"code": null,
"e": 1806,
"s": 1757,
"text": "lr *= (1. / (1. + self.decay * self.iterations))"
},
{
"code": null,
"e": 2120,
"s": 1806,
"text": "Momentum is another argument in SGD optimizer which we could tweak to obtain faster convergence. Unlike classical SGD, momentum method helps the parameter vector to build up velocity in any direction with constant gradient descent so as to prevent oscillations. A typical choice of momentum is between 0.5 to 0.9."
},
{
"code": null,
"e": 2404,
"s": 2120,
"text": "SGD optimizer also has an argument called nesterov which is set to false by default. Nesterov momentum is a different version of the momentum method which has stronger theoretical converge guarantees for convex functions. In practice, it works slightly better than standard momentum."
},
{
"code": null,
"e": 2532,
"s": 2404,
"text": "In Keras, we can implement time-based decay by setting the initial learning rate, decay rate and momentum in the SGD optimizer."
},
{
"code": null,
"e": 2681,
"s": 2532,
"text": "learning_rate = 0.1decay_rate = learning_rate / epochsmomentum = 0.8sgd = SGD(lr=learning_rate, momentum=momentum, decay=decay_rate, nesterov=False)"
},
{
"code": null,
"e": 2796,
"s": 2681,
"text": "Step decay schedule drops the learning rate by a factor every few epochs. The mathematical form of step decay is :"
},
{
"code": null,
"e": 2840,
"s": 2796,
"text": "lr = lr0 * drop^floor(epoch / epochs_drop) "
},
{
"code": null,
"e": 3122,
"s": 2840,
"text": "A typical way is to to drop the learning rate by half every 10 epochs. To implement this in Keras, we can define a step decay function and use LearningRateScheduler callback to take the step decay function as argument and return the updated learning rates for use in SGD optimizer."
},
{
"code": null,
"e": 3345,
"s": 3122,
"text": "def step_decay(epoch): initial_lrate = 0.1 drop = 0.5 epochs_drop = 10.0 lrate = initial_lrate * math.pow(drop, math.floor((1+epoch)/epochs_drop)) return lratelrate = LearningRateScheduler(step_decay)"
},
{
"code": null,
"e": 3720,
"s": 3345,
"text": "As a digression, a callback is a set of functions to be applied at given stages of the training procedure. We can use callbacks to get a view on internal states and statistics of the model during training. In our example, we create a custom callback by extending the base class keras.callbacks.Callback to record loss history and learning rate during the training procedure."
},
{
"code": null,
"e": 3983,
"s": 3720,
"text": "class LossHistory(keras.callbacks.Callback): def on_train_begin(self, logs={}): self.losses = [] self.lr = [] def on_epoch_end(self, batch, logs={}): self.losses.append(logs.get(‘loss’)) self.lr.append(step_decay(len(self.losses)))"
},
{
"code": null,
"e": 4251,
"s": 3983,
"text": "Putting everything together, we can pass a callback list consisting of LearningRateScheduler callback and our custom callback to fit the model. We can then visualize the learning rate schedule and the loss history by accessing loss_history.lr and loss_history.losses."
},
{
"code": null,
"e": 4520,
"s": 4251,
"text": "loss_history = LossHistory()lrate = LearningRateScheduler(step_decay)callbacks_list = [loss_history, lrate]history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=epochs, batch_size=batch_size, callbacks=callbacks_list, verbose=2)"
},
{
"code": null,
"e": 4940,
"s": 4520,
"text": "Another common schedule is exponential decay. It has the mathematical form lr = lr0 * e^(−kt), where lr, k are hyperparameters and t is the iteration number. Similarly, we can implement this by defining exponential decay function and pass it to LearningRateScheduler. In fact, any custom decay schedule can be implemented in Keras using this approach. The only difference is to define a different custom decay function."
},
{
"code": null,
"e": 5085,
"s": 4940,
"text": "def exp_decay(epoch): initial_lrate = 0.1 k = 0.1 lrate = initial_lrate * exp(-k*t) return lratelrate = LearningRateScheduler(exp_decay)"
},
{
"code": null,
"e": 5179,
"s": 5085,
"text": "Let us now compare the model accuracy using different learning rate schedules in our example."
},
{
"code": null,
"e": 5518,
"s": 5179,
"text": "The challenge of using learning rate schedules is that their hyperparameters have to be defined in advance and they depend heavily on the type of model and problem. Another problem is that the same learning rate is applied to all parameter updates. If we have sparse data, we may want to update the parameters in different extent instead."
},
{
"code": null,
"e": 5807,
"s": 5518,
"text": "Adaptive gradient descent algorithms such as Adagrad, Adadelta, RMSprop, Adam, provide an alternative to classical SGD. These per-parameter learning rate methods provide heuristic approach without requiring expensive work in tuning hyperparameters for the learning rate schedule manually."
},
{
"code": null,
"e": 6466,
"s": 5807,
"text": "In brief, Adagrad performs larger updates for more sparse parameters and smaller updates for less sparse parameter. It has good performance with sparse data and training large-scale neural network. However, its monotonic learning rate usually proves too aggressive and stops learning too early when training deep neural networks. Adadelta is an extension of Adagrad that seeks to reduce its aggressive, monotonically decreasing learning rate. RMSprop adjusts the Adagrad method in a very simple way in an attempt to reduce its aggressive, monotonically decreasing learning rate. Adam is an update to the RMSProp optimizer which is like RMSprop with momentum."
},
{
"code": null,
"e": 6689,
"s": 6466,
"text": "In Keras, we can implement these adaptive learning algorithms easily using corresponding optimizers. It is usually recommended to leave the hyperparameters of these optimizers at their default values (except lr sometimes)."
},
{
"code": null,
"e": 6970,
"s": 6689,
"text": "keras.optimizers.Adagrad(lr=0.01, epsilon=1e-08, decay=0.0)keras.optimizers.Adadelta(lr=1.0, rho=0.95, epsilon=1e-08, decay=0.0)keras.optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)"
},
{
"code": null,
"e": 7159,
"s": 6970,
"text": "Let us now look at the model performances using different adaptive learning rate methods. In our example, Adadelta gives the best model accuracy among other adaptive learning rate methods."
},
{
"code": null,
"e": 7285,
"s": 7159,
"text": "Finally, we compare the performances of all the learning rate schedules and adaptive learning rate methods we have discussed."
},
{
"code": null,
"e": 7601,
"s": 7285,
"text": "In many examples I have worked on, adaptive learning rate methods demonstrate better performance than learning rate schedules, and they require much less effort in hyperparamater settings. We can also use LearningRateScheduler in Keras to create custom learning rate schedules which is specific to our data problem."
},
{
"code": null,
"e": 7849,
"s": 7601,
"text": "For further reading, Yoshua Bengio’s paper provides very good practical recommendations for tuning learning rate for deep learning, such as how to set initial learning rate, mini-batch size, number of epochs and use of early stopping and momentum."
},
{
"code": null,
"e": 7861,
"s": 7849,
"text": "Source code"
},
{
"code": null,
"e": 7954,
"s": 7861,
"text": "Practical Recommendations for Gradient-Based Training of Deep Architectures by Yoshua Bengio"
},
{
"code": null,
"e": 8007,
"s": 7954,
"text": "Convolutional Neural Networks for Visual Recognition"
}
] |
C++ Library - <ostream> | It is an output stream objects can write sequences of characters and represent other kinds of data. Specific members are provided to perform these output operations.
Below is definition of std::ostream.
typedef basic_ostream<char> ostream;
charT − Character type.
charT − Character type.
traits − Character traits class that defines essential properties of the characters used by stream objects.
traits − Character traits class that defines essential properties of the characters used by stream objects.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2769,
"s": 2603,
"text": "It is an output stream objects can write sequences of characters and represent other kinds of data. Specific members are provided to perform these output operations."
},
{
"code": null,
"e": 2806,
"s": 2769,
"text": "Below is definition of std::ostream."
},
{
"code": null,
"e": 2843,
"s": 2806,
"text": "typedef basic_ostream<char> ostream;"
},
{
"code": null,
"e": 2867,
"s": 2843,
"text": "charT − Character type."
},
{
"code": null,
"e": 2891,
"s": 2867,
"text": "charT − Character type."
},
{
"code": null,
"e": 2999,
"s": 2891,
"text": "traits − Character traits class that defines essential properties of the characters used by stream objects."
},
{
"code": null,
"e": 3107,
"s": 2999,
"text": "traits − Character traits class that defines essential properties of the characters used by stream objects."
},
{
"code": null,
"e": 3114,
"s": 3107,
"text": " Print"
},
{
"code": null,
"e": 3125,
"s": 3114,
"text": " Add Notes"
}
] |
Mastering Random Sampling in Python | by Sadrach Pierre, Ph.D. | Towards Data Science | Python provides many useful tools for random sampling as well as functions for generating random numbers. Random sampling has applications in statistics where often times a random subset of a population is observed and used to make inferences about the overall population. Further, random number generation has many application in the sciences. For example, in chemistry and physics Monte Carlo simulations require random number generation. In this post, we will discuss how to randomly sample items from lists as well as how to generate pseudorandom numbers in python.
Let’s get started!
The random module in python has many functions that are useful for generating random numbers and random sampling.
Consider a list of BMI values for people living in a rural area:
bmi_list = [29, 18, 20, 22, 19, 25, 30, 28,22, 21, 18, 19, 20, 20, 22, 23]
Let’s use the ‘random.choice()’ method to randomly select individual BMI values from this list:
import random print("First random choice:", random.choice(bmi_list))print("Second random choice:", random.choice(bmi_list))print("Third random choice:", random.choice(bmi_list))
If we run this code once more, we should get another set of randomly selected BMIs:
The ‘random.sample()’ method is useful for randomly sampling N items from a list. For example, if we’d like to sample N=5 items from our BMI list we do the following:
print("Random sample, N = 5 :", random.sample(bmi_list, 5))
Let’s try sampling 10 items:
print("Random sample, N = 10:", random.sample(bmi_list, 10))
In addition to random selection and sampling, the random module has a function for shuffling items in a list. Let’s print our BMI list and then print the result of shuffling our BMI list:
print("BMI list: ", bmi_list)random.shuffle(bmi_list)print("Shuffled BMI list: ", bmi_list)
The random module has a function for generating a random integer provided a range of values. Let’s generate a random integer in the range from 1 to 5:
print("Random Integer: ", random.randint(1,5))
Using this function, we can easily generate a list of random integers in a for-loop:
random_ints_list = []for i in range(1,50): n = random.randint(1,5) random_ints_list.append(n)print("My random integer list: ", random_ints_list)
The random module also has a function for generating a random floating point value between 0 and 1:
print("Random Float: ", random.random())
We can also generate a list of random floats between 0 and 1:
random_float_list = []for i in range(1,5): n = random.random() random_float_list.append(n)print("My random float list: ", random_float_list)
Further, we can scale the random float numbers. If we want random numbers between 0 and 500 we just multiply our random number by 500:
random_float_list = []for i in range(1,5): n = random.random()*500 random_float_list.append(n)print("My random float list: ", random_float_list)
And if we want to add a lower bound as well we can add a conditional statement before appending. For example to generate random numbers between 100 and 500 we do the following:
random_float_list = []for i in range(1,10): n = random.random()*500 if n>=100.0: random_float_list.append(n)print("My random float list: ", random_float_list)
The random module has a function for computing uniformly distributed numbers. For example, to generate 50 uniformly distributed numbers between -10 and 1 we do the following:
import numpy as npuniform_list = np.random.uniform(-10,1,50)print("Uniformly Distributed Numbers: ", uniform_list)
Finally, the random module has a function for computing normally distributed numbers. For example, to generate 50 normally distributed numbers between -50 and 0 we do the following:
normal_list = np.random.uniform(-50,0,50)print("Normally Distributed Numbers: ", normal_list)
I’ll stop here but I encourage you to play around with the code yourself.
To summarize, we discussed how to randomly select and sample items from lists in python. We showed how to use the ‘random.choice()’ method to select a single item randomly from a list. We also used the ‘random.sample()’ method, which allows you to randomly select N items from a list. We also discussed how to shuffle items in a list using the ‘random.shuffle()’ method. Additionally, we showed how to generate random numbers using the random module. We generated random integers using ‘random.randint()’and random floating point values using ‘random.random()’. Finally, we went over how to generate uniformly and normally distributed numbers with ‘random.uniform()’ and ‘random.gauss()’ respectively. I hope you found this post useful/interesting. The code in this post is available on GitHub. Thank you for reading! | [
{
"code": null,
"e": 741,
"s": 171,
"text": "Python provides many useful tools for random sampling as well as functions for generating random numbers. Random sampling has applications in statistics where often times a random subset of a population is observed and used to make inferences about the overall population. Further, random number generation has many application in the sciences. For example, in chemistry and physics Monte Carlo simulations require random number generation. In this post, we will discuss how to randomly sample items from lists as well as how to generate pseudorandom numbers in python."
},
{
"code": null,
"e": 760,
"s": 741,
"text": "Let’s get started!"
},
{
"code": null,
"e": 874,
"s": 760,
"text": "The random module in python has many functions that are useful for generating random numbers and random sampling."
},
{
"code": null,
"e": 939,
"s": 874,
"text": "Consider a list of BMI values for people living in a rural area:"
},
{
"code": null,
"e": 1014,
"s": 939,
"text": "bmi_list = [29, 18, 20, 22, 19, 25, 30, 28,22, 21, 18, 19, 20, 20, 22, 23]"
},
{
"code": null,
"e": 1110,
"s": 1014,
"text": "Let’s use the ‘random.choice()’ method to randomly select individual BMI values from this list:"
},
{
"code": null,
"e": 1288,
"s": 1110,
"text": "import random print(\"First random choice:\", random.choice(bmi_list))print(\"Second random choice:\", random.choice(bmi_list))print(\"Third random choice:\", random.choice(bmi_list))"
},
{
"code": null,
"e": 1372,
"s": 1288,
"text": "If we run this code once more, we should get another set of randomly selected BMIs:"
},
{
"code": null,
"e": 1539,
"s": 1372,
"text": "The ‘random.sample()’ method is useful for randomly sampling N items from a list. For example, if we’d like to sample N=5 items from our BMI list we do the following:"
},
{
"code": null,
"e": 1599,
"s": 1539,
"text": "print(\"Random sample, N = 5 :\", random.sample(bmi_list, 5))"
},
{
"code": null,
"e": 1628,
"s": 1599,
"text": "Let’s try sampling 10 items:"
},
{
"code": null,
"e": 1689,
"s": 1628,
"text": "print(\"Random sample, N = 10:\", random.sample(bmi_list, 10))"
},
{
"code": null,
"e": 1877,
"s": 1689,
"text": "In addition to random selection and sampling, the random module has a function for shuffling items in a list. Let’s print our BMI list and then print the result of shuffling our BMI list:"
},
{
"code": null,
"e": 1969,
"s": 1877,
"text": "print(\"BMI list: \", bmi_list)random.shuffle(bmi_list)print(\"Shuffled BMI list: \", bmi_list)"
},
{
"code": null,
"e": 2120,
"s": 1969,
"text": "The random module has a function for generating a random integer provided a range of values. Let’s generate a random integer in the range from 1 to 5:"
},
{
"code": null,
"e": 2167,
"s": 2120,
"text": "print(\"Random Integer: \", random.randint(1,5))"
},
{
"code": null,
"e": 2252,
"s": 2167,
"text": "Using this function, we can easily generate a list of random integers in a for-loop:"
},
{
"code": null,
"e": 2403,
"s": 2252,
"text": "random_ints_list = []for i in range(1,50): n = random.randint(1,5) random_ints_list.append(n)print(\"My random integer list: \", random_ints_list)"
},
{
"code": null,
"e": 2503,
"s": 2403,
"text": "The random module also has a function for generating a random floating point value between 0 and 1:"
},
{
"code": null,
"e": 2544,
"s": 2503,
"text": "print(\"Random Float: \", random.random())"
},
{
"code": null,
"e": 2606,
"s": 2544,
"text": "We can also generate a list of random floats between 0 and 1:"
},
{
"code": null,
"e": 2753,
"s": 2606,
"text": "random_float_list = []for i in range(1,5): n = random.random() random_float_list.append(n)print(\"My random float list: \", random_float_list)"
},
{
"code": null,
"e": 2888,
"s": 2753,
"text": "Further, we can scale the random float numbers. If we want random numbers between 0 and 500 we just multiply our random number by 500:"
},
{
"code": null,
"e": 3039,
"s": 2888,
"text": "random_float_list = []for i in range(1,5): n = random.random()*500 random_float_list.append(n)print(\"My random float list: \", random_float_list)"
},
{
"code": null,
"e": 3216,
"s": 3039,
"text": "And if we want to add a lower bound as well we can add a conditional statement before appending. For example to generate random numbers between 100 and 500 we do the following:"
},
{
"code": null,
"e": 3388,
"s": 3216,
"text": "random_float_list = []for i in range(1,10): n = random.random()*500 if n>=100.0: random_float_list.append(n)print(\"My random float list: \", random_float_list)"
},
{
"code": null,
"e": 3563,
"s": 3388,
"text": "The random module has a function for computing uniformly distributed numbers. For example, to generate 50 uniformly distributed numbers between -10 and 1 we do the following:"
},
{
"code": null,
"e": 3678,
"s": 3563,
"text": "import numpy as npuniform_list = np.random.uniform(-10,1,50)print(\"Uniformly Distributed Numbers: \", uniform_list)"
},
{
"code": null,
"e": 3860,
"s": 3678,
"text": "Finally, the random module has a function for computing normally distributed numbers. For example, to generate 50 normally distributed numbers between -50 and 0 we do the following:"
},
{
"code": null,
"e": 3954,
"s": 3860,
"text": "normal_list = np.random.uniform(-50,0,50)print(\"Normally Distributed Numbers: \", normal_list)"
},
{
"code": null,
"e": 4028,
"s": 3954,
"text": "I’ll stop here but I encourage you to play around with the code yourself."
}
] |
How to check a key exists in JavaScript object? - GeeksforGeeks | 26 Jul, 2021
There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”.
Method 1: Using ‘in’ operator: The in operator returns a boolean value if the specified property is in the object.
Syntax:
propertyName in object
Example: This example uses “in” operator to check the existence of key in JavaScript object.
<!DOCTYPE html><html> <head> <title> How to check a key exists in JavaScript object? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to check a key exists in JavaScript object? </b> <p> Click on the button to check if key exists in object </p> Checking for 'name': <p class="output1"></p> Checking for 'remarks': <p class="output2"></p> <button onclick="checkKey()"> Click here </button> <script type="text/javascript"> function checkKey() { // Define an object exampleObj = { id: 1, remarks: 'Good' } // Check for the keys output1 = 'name' in exampleObj; output2 = 'remarks' in exampleObj; document.querySelector('.output1').innerHTML = output1; document.querySelector('.output2').innerHTML = output2; } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Method 2: Using the hasOwnProperty() method: The hasOwnProperty() method returns a boolean value which indicates whether the object has the specified property. The required key name could be passed in this function to check if it exists in the object.
Syntax:
object.hasOwnProperty(propertyName)
Example: This example uses hasOwnProperty() method to check the existence of key in JavaScript object.
<!DOCTYPE html><html> <head> <title> How to check a key exists in JavaScript object? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to check a key exists in JavaScript object? </b> <p> Click on the button to check if key exists in object </p> Checking for 'name': <p class="output1"></p> Checking for 'remarks': <p class="output2"></p> <button onclick="checkKey()"> Click here </button> <script type="text/javascript"> function checkKey() { // Define an object exampleObj = { id: 1, remarks: 'Good' } // Check for the keys output1 = exampleObj.hasOwnProperty('name'); output2 = exampleObj.hasOwnProperty('remarks'); document.querySelector('.output1').innerHTML = output1; document.querySelector('.output2').innerHTML = output2; } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
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 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24722,
"s": 24694,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 24897,
"s": 24722,
"text": "There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”."
},
{
"code": null,
"e": 25012,
"s": 24897,
"text": "Method 1: Using ‘in’ operator: The in operator returns a boolean value if the specified property is in the object."
},
{
"code": null,
"e": 25020,
"s": 25012,
"text": "Syntax:"
},
{
"code": null,
"e": 25043,
"s": 25020,
"text": "propertyName in object"
},
{
"code": null,
"e": 25136,
"s": 25043,
"text": "Example: This example uses “in” operator to check the existence of key in JavaScript object."
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to check a key exists in JavaScript object? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to check a key exists in JavaScript object? </b> <p> Click on the button to check if key exists in object </p> Checking for 'name': <p class=\"output1\"></p> Checking for 'remarks': <p class=\"output2\"></p> <button onclick=\"checkKey()\"> Click here </button> <script type=\"text/javascript\"> function checkKey() { // Define an object exampleObj = { id: 1, remarks: 'Good' } // Check for the keys output1 = 'name' in exampleObj; output2 = 'remarks' in exampleObj; document.querySelector('.output1').innerHTML = output1; document.querySelector('.output2').innerHTML = output2; } </script></body> </html> ",
"e": 26244,
"s": 25136,
"text": null
},
{
"code": null,
"e": 26252,
"s": 26244,
"text": "Output:"
},
{
"code": null,
"e": 26280,
"s": 26252,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 26307,
"s": 26280,
"text": "After clicking the button:"
},
{
"code": null,
"e": 26559,
"s": 26307,
"text": "Method 2: Using the hasOwnProperty() method: The hasOwnProperty() method returns a boolean value which indicates whether the object has the specified property. The required key name could be passed in this function to check if it exists in the object."
},
{
"code": null,
"e": 26567,
"s": 26559,
"text": "Syntax:"
},
{
"code": null,
"e": 26603,
"s": 26567,
"text": "object.hasOwnProperty(propertyName)"
},
{
"code": null,
"e": 26706,
"s": 26603,
"text": "Example: This example uses hasOwnProperty() method to check the existence of key in JavaScript object."
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to check a key exists in JavaScript object? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to check a key exists in JavaScript object? </b> <p> Click on the button to check if key exists in object </p> Checking for 'name': <p class=\"output1\"></p> Checking for 'remarks': <p class=\"output2\"></p> <button onclick=\"checkKey()\"> Click here </button> <script type=\"text/javascript\"> function checkKey() { // Define an object exampleObj = { id: 1, remarks: 'Good' } // Check for the keys output1 = exampleObj.hasOwnProperty('name'); output2 = exampleObj.hasOwnProperty('remarks'); document.querySelector('.output1').innerHTML = output1; document.querySelector('.output2').innerHTML = output2; } </script></body> </html> ",
"e": 27852,
"s": 26706,
"text": null
},
{
"code": null,
"e": 27860,
"s": 27852,
"text": "Output:"
},
{
"code": null,
"e": 27888,
"s": 27860,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 27915,
"s": 27888,
"text": "After clicking the button:"
},
{
"code": null,
"e": 28134,
"s": 27915,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 28150,
"s": 28134,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 28157,
"s": 28150,
"text": "Picked"
},
{
"code": null,
"e": 28168,
"s": 28157,
"text": "JavaScript"
},
{
"code": null,
"e": 28185,
"s": 28168,
"text": "Web Technologies"
},
{
"code": null,
"e": 28212,
"s": 28185,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28310,
"s": 28212,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28319,
"s": 28310,
"text": "Comments"
},
{
"code": null,
"e": 28332,
"s": 28319,
"text": "Old Comments"
},
{
"code": null,
"e": 28377,
"s": 28332,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28438,
"s": 28377,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28510,
"s": 28438,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28562,
"s": 28510,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 28608,
"s": 28562,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 28650,
"s": 28608,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28683,
"s": 28650,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28726,
"s": 28683,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28788,
"s": 28726,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
How to merge table columns in HTML? | To merge table columns in HTML use the colspan attribute in <td> tag. With this, merge cells with each other. For example, if your table is having 4 rows and 4 columns, then with colspan attribute, you can easily merge 2 or even 3 of the table cells.
You can try to run the following code to merge table column in HTML. Firstly, we will see how to create a table in HTML with 3 rows and 3 columns
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
width: 100px;
height: 50px;
}
</style>
</head>
<body>
<h1>Heading</h1>
<table>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>
Let’s merge columns using the colspan attribute. The first 2 columns will merge
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
width: 100px;
height: 50px;
}
</style>
</head>
<body>
<h1>Heading</h1>
<table>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
<tr>
<td colspan="2"></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
</html> | [
{
"code": null,
"e": 1313,
"s": 1062,
"text": "To merge table columns in HTML use the colspan attribute in <td> tag. With this, merge cells with each other. For example, if your table is having 4 rows and 4 columns, then with colspan attribute, you can easily merge 2 or even 3 of the table cells."
},
{
"code": null,
"e": 1459,
"s": 1313,
"text": "You can try to run the following code to merge table column in HTML. Firstly, we will see how to create a table in HTML with 3 rows and 3 columns"
},
{
"code": null,
"e": 2024,
"s": 1459,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n table, th, td {\n border: 1px solid black;\n width: 100px;\n height: 50px;\n }\n </style>\n </head>\n\n <body>\n <h1>Heading</h1>\n <table>\n <tr>\n <th></th>\n <th></th>\n <th></th>\n </tr>\n <tr>\n <td></td>\n <td></td>\n <td></td>\n </tr>\n <tr>\n <td></td>\n <td></td>\n <td></td>\n </tr>\n </table>\n </body>\n</html>"
},
{
"code": null,
"e": 2104,
"s": 2024,
"text": "Let’s merge columns using the colspan attribute. The first 2 columns will merge"
},
{
"code": null,
"e": 2658,
"s": 2104,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n table, th, td {\n border: 1px solid black;\n width: 100px;\n height: 50px;\n }\n </style>\n </head>\n <body>\n <h1>Heading</h1>\n <table>\n <tr>\n <th></th>\n <th></th>\n <th></th>\n </tr>\n <tr>\n <td colspan=\"2\"></td>\n <td></td>\n </tr>\n <tr>\n <td></td>\n <td></td>\n <td></td>\n </tr>\n </table>\n </body>\n</html>"
}
] |
Linear Regression using Gradient Descent | by Adarsh Menon | Towards Data Science | In this tutorial you can learn how the gradient descent algorithm works and implement it from scratch in python. First we look at what linear regression is, then we define the loss function. We learn how the gradient descent algorithm works and finally we will implement it on a given data set and make predictions.
This is the written version of this video. Watch it if you prefer that!
In statistics, linear regression is a linear approach to modelling the relationship between a dependent variable and one or more independent variables. Let X be the independent variable and Y be the dependent variable. We will define a linear relationship between these two variables as follows:
This is the equation for a line that you studied in high school. m is the slope of the line and c is the y intercept. Today we will use this equation to train our model with a given dataset and predict the value of Y for any given value of X. Our challenge today is to determine the value of m and c, such that the line corresponding to those values is the best fitting line or gives the minimum error.
The loss is the error in our predicted value of m and c. Our goal is to minimize this error to obtain the most accurate value of m and c.We will use the Mean Squared Error function to calculate the loss. There are three steps in this function:
Find the difference between the actual y and predicted y value(y = mx + c), for a given x.Square this difference.Find the mean of the squares for every value in X.
Find the difference between the actual y and predicted y value(y = mx + c), for a given x.
Square this difference.
Find the mean of the squares for every value in X.
Here yi is the actual value and ȳi is the predicted value. Lets substitute the value of ȳi:
So we square the error and find the mean. hence the name Mean Squared Error. Now that we have defined the loss function, lets get into the interesting part — minimizing it and finding m and c.
Gradient descent is an iterative optimization algorithm to find the minimum of a function. Here that function is our Loss Function.
Understanding Gradient Descent
Imagine a valley and a person with no sense of direction who wants to get to the bottom of the valley. He goes down the slope and takes large steps when the slope is steep and small steps when the slope is less steep. He decides his next position based on his current position and stops when he gets to the bottom of the valley which was his goal.Let’s try applying gradient descent to m and c and approach it step by step:
Initially let m = 0 and c = 0. Let L be our learning rate. This controls how much the value of m changes with each step. L could be a small value like 0.0001 for good accuracy.Calculate the partial derivative of the loss function with respect to m, and plug in the current values of x, y, m and c in it to obtain the derivative value D.
Initially let m = 0 and c = 0. Let L be our learning rate. This controls how much the value of m changes with each step. L could be a small value like 0.0001 for good accuracy.
Calculate the partial derivative of the loss function with respect to m, and plug in the current values of x, y, m and c in it to obtain the derivative value D.
Dm is the value of the partial derivative with respect to m. Similarly lets find the partial derivative with respect to c, Dc :
3. Now we update the current value of m and c using the following equation:
4. We repeat this process until our loss function is a very small value or ideally 0 (which means 0 error or 100% accuracy). The value of m and c that we are left with now will be the optimum values.
Now going back to our analogy, m can be considered the current position of the person. D is equivalent to the steepness of the slope and L can be the speed with which he moves. Now the new value of m that we calculate using the above equation will be his next position, and L×D will be the size of the steps he will take. When the slope is more steep (D is more) he takes longer steps and when it is less steep (D is less), he takes smaller steps. Finally he arrives at the bottom of the valley which corresponds to our loss = 0.Now with the optimum value of m and c our model is ready to make predictions !
Now let’s convert everything above into code and see our model in action !
1.4796491688889395 0.10148121494753726
Gradient descent is one of the simplest and widely used algorithms in machine learning, mainly because it can be applied to any function to optimize it. Learning it lays the foundation to mastering machine learning.
Find the data set and code here: https://github.com/chasinginfinity/ml-from-scratch/tree/master/02%20Linear%20Regression%20using%20Gradient%20Descent
Got questions ? Need help ? Contact me! | [
{
"code": null,
"e": 363,
"s": 47,
"text": "In this tutorial you can learn how the gradient descent algorithm works and implement it from scratch in python. First we look at what linear regression is, then we define the loss function. We learn how the gradient descent algorithm works and finally we will implement it on a given data set and make predictions."
},
{
"code": null,
"e": 435,
"s": 363,
"text": "This is the written version of this video. Watch it if you prefer that!"
},
{
"code": null,
"e": 731,
"s": 435,
"text": "In statistics, linear regression is a linear approach to modelling the relationship between a dependent variable and one or more independent variables. Let X be the independent variable and Y be the dependent variable. We will define a linear relationship between these two variables as follows:"
},
{
"code": null,
"e": 1134,
"s": 731,
"text": "This is the equation for a line that you studied in high school. m is the slope of the line and c is the y intercept. Today we will use this equation to train our model with a given dataset and predict the value of Y for any given value of X. Our challenge today is to determine the value of m and c, such that the line corresponding to those values is the best fitting line or gives the minimum error."
},
{
"code": null,
"e": 1378,
"s": 1134,
"text": "The loss is the error in our predicted value of m and c. Our goal is to minimize this error to obtain the most accurate value of m and c.We will use the Mean Squared Error function to calculate the loss. There are three steps in this function:"
},
{
"code": null,
"e": 1542,
"s": 1378,
"text": "Find the difference between the actual y and predicted y value(y = mx + c), for a given x.Square this difference.Find the mean of the squares for every value in X."
},
{
"code": null,
"e": 1633,
"s": 1542,
"text": "Find the difference between the actual y and predicted y value(y = mx + c), for a given x."
},
{
"code": null,
"e": 1657,
"s": 1633,
"text": "Square this difference."
},
{
"code": null,
"e": 1708,
"s": 1657,
"text": "Find the mean of the squares for every value in X."
},
{
"code": null,
"e": 1802,
"s": 1708,
"text": "Here yi is the actual value and ȳi is the predicted value. Lets substitute the value of ȳi:"
},
{
"code": null,
"e": 1995,
"s": 1802,
"text": "So we square the error and find the mean. hence the name Mean Squared Error. Now that we have defined the loss function, lets get into the interesting part — minimizing it and finding m and c."
},
{
"code": null,
"e": 2127,
"s": 1995,
"text": "Gradient descent is an iterative optimization algorithm to find the minimum of a function. Here that function is our Loss Function."
},
{
"code": null,
"e": 2158,
"s": 2127,
"text": "Understanding Gradient Descent"
},
{
"code": null,
"e": 2582,
"s": 2158,
"text": "Imagine a valley and a person with no sense of direction who wants to get to the bottom of the valley. He goes down the slope and takes large steps when the slope is steep and small steps when the slope is less steep. He decides his next position based on his current position and stops when he gets to the bottom of the valley which was his goal.Let’s try applying gradient descent to m and c and approach it step by step:"
},
{
"code": null,
"e": 2919,
"s": 2582,
"text": "Initially let m = 0 and c = 0. Let L be our learning rate. This controls how much the value of m changes with each step. L could be a small value like 0.0001 for good accuracy.Calculate the partial derivative of the loss function with respect to m, and plug in the current values of x, y, m and c in it to obtain the derivative value D."
},
{
"code": null,
"e": 3096,
"s": 2919,
"text": "Initially let m = 0 and c = 0. Let L be our learning rate. This controls how much the value of m changes with each step. L could be a small value like 0.0001 for good accuracy."
},
{
"code": null,
"e": 3257,
"s": 3096,
"text": "Calculate the partial derivative of the loss function with respect to m, and plug in the current values of x, y, m and c in it to obtain the derivative value D."
},
{
"code": null,
"e": 3385,
"s": 3257,
"text": "Dm is the value of the partial derivative with respect to m. Similarly lets find the partial derivative with respect to c, Dc :"
},
{
"code": null,
"e": 3461,
"s": 3385,
"text": "3. Now we update the current value of m and c using the following equation:"
},
{
"code": null,
"e": 3661,
"s": 3461,
"text": "4. We repeat this process until our loss function is a very small value or ideally 0 (which means 0 error or 100% accuracy). The value of m and c that we are left with now will be the optimum values."
},
{
"code": null,
"e": 4269,
"s": 3661,
"text": "Now going back to our analogy, m can be considered the current position of the person. D is equivalent to the steepness of the slope and L can be the speed with which he moves. Now the new value of m that we calculate using the above equation will be his next position, and L×D will be the size of the steps he will take. When the slope is more steep (D is more) he takes longer steps and when it is less steep (D is less), he takes smaller steps. Finally he arrives at the bottom of the valley which corresponds to our loss = 0.Now with the optimum value of m and c our model is ready to make predictions !"
},
{
"code": null,
"e": 4344,
"s": 4269,
"text": "Now let’s convert everything above into code and see our model in action !"
},
{
"code": null,
"e": 4383,
"s": 4344,
"text": "1.4796491688889395 0.10148121494753726"
},
{
"code": null,
"e": 4599,
"s": 4383,
"text": "Gradient descent is one of the simplest and widely used algorithms in machine learning, mainly because it can be applied to any function to optimize it. Learning it lays the foundation to mastering machine learning."
},
{
"code": null,
"e": 4749,
"s": 4599,
"text": "Find the data set and code here: https://github.com/chasinginfinity/ml-from-scratch/tree/master/02%20Linear%20Regression%20using%20Gradient%20Descent"
}
] |
How to deploy web applications using Nginx on Remote server (Ubuntu based) - Set 2 - GeeksforGeeks | 01 Aug, 2021
In the last article, we got the idea about Nginx and how we can leverage its benefits, further we installed it on our device or remote server. In this article, we will see how to deploy a web application stored in the remote server using Nginx.
We need to follow the given steps in order to deploy web applications using Nginx.
Step 1: Open the terminal, and change the directory where your web application is stored using the cd command.
# Example: Suppose test is a web application
# folder stored in downloads, I'll open terminal
# in home screen
cd ../Downloads/test/
# Check the contents once here
ls
Step 2: Installing Curl, OpenSSH-server, and vim editor in your distro for easy setup using the following commands. But before that, I’ll explain what are they and why need to use them.
Curl: CLI tool used to transfer data from a web server.
OpenSSH-server: OpenSSH-server is a collection of tools that are used for the remote control and transfer of data between remote networked computers.
Vim-editor: It is an editor that is used to create and modify text files in ubuntu.
# Commands to install all the above-required libraries in terminal
sudo apt-get install curl
sudo apt-get install openssh-server
sudo apt-get install vim
Now we have finished with our pre-requisites part.
Step 3: Now in this step we will copy our web application folder to this absolute path /var/www
# change directory to parent folder where
# you have stored the web application folder
sudo cp -r test /var/www
Step 4: Now we will point our domain name to the server where we will host this application. i.e. we need to add the IP address of your server to the DNS settings. Let’s suppose your server IP address is 0.0.0.0 and your domain name is www.test.com, then your domain name should point to your server IP address.
For that we need to also do some settings in server, we need to create a file, we will use vim for that
Firstly, change your directory to var/www/ then use the vim commands:
# Change your directory
cd var/www
# Vim command for new file
sudo vi /etc/hosts
Now you will see a file with similar contents as shown in the picture
you need to add your IP address here in starting and your domain name after it, you can use the below image for reference.
Step 5: As on a remote server, we need to add our web application folder to that server. For that, we need to change the permission of our web application folder. (your folder name of the web application can differ)
# Change directory to /var/www/test
cd /var/www/test
# Change permission for your folder
sudo chmod -R 777 *
# Secure copy your files to web server
# (Your IP address of server will be different)
# (eg: scp -r * [email protected]:var/www/FOLDER_NAME)
scp -r * 0.0.0.0:/var/www/test
So our files have securely been copied to the server.
Step 6: So now, we will configure our Nginx Server to serve our website, let’s, first of all, see the Nginx folder
# Change directory
cd /etc/nginx
# See Contents of it
ls
Here we should be interested in 2 directories, sites-available and sites-enabled.
sites-available: It contains all the individual config files possible for your all static files.
sites-enabled: It contains the link to config files that Nginx will read and run.
So we need to create a config file in sites-available and a symbolic link in sites-enabled for Nginx.
Firstly, we will create a new file and add the following contents to it.
# Command to create and open a new file
sudo vim sites-available/test
# Now add the following contents to it
server {
listen 80 default_server;
listen [::] default_server;
root /var/www/test;
index index.html;
location / {
try_files $url $url/ =404;
}
}
Here we have opened socket 80 and your application port for default_server, we have told nginx where our web application files are. Location of our Index page, and if you get some wrong URL then through a 404 error.
Step 7: Now let us add this file to the sites-enabled folder in Nginx
# Command to add file to sites-enabled folder
sudo ln -s /etc/nginx/sites-available/test /etc/nginx/sites-enabled/test
Amazing! Now we have one main issue, as earlier we had our Nginx server running, and we configured to open port 80 in our web application, and Nginx is also trying to open its default page using port 80. Hence we need to move that default files to somewhere else to avoid conflict.
# I generally move it to home directory
sudo mv /etc/nginx/sites-enabled/default /home/yashtewatia/default
# Restart Nginx service
sudo systemctl restart nginx
So we have restarted our nginx server! Now you can go to your IP address to view the contents in the browser or you can use the curl command for the same in terminal like,
curl www.test.com
# or we can give the IP address here of our server
curl 0.0.0.0
Hence we have deployed our web files using Nginx Server.
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to redirect to another page in ReactJS ?
Difference Between PUT and PATCH Request
How to execute PHP code using command line ?
How to pass data from child component to its parent in ReactJS ?
How to Insert Form Data into Database using PHP ? | [
{
"code": null,
"e": 24916,
"s": 24888,
"text": "\n01 Aug, 2021"
},
{
"code": null,
"e": 25162,
"s": 24916,
"text": "In the last article, we got the idea about Nginx and how we can leverage its benefits, further we installed it on our device or remote server. In this article, we will see how to deploy a web application stored in the remote server using Nginx."
},
{
"code": null,
"e": 25245,
"s": 25162,
"text": "We need to follow the given steps in order to deploy web applications using Nginx."
},
{
"code": null,
"e": 25356,
"s": 25245,
"text": "Step 1: Open the terminal, and change the directory where your web application is stored using the cd command."
},
{
"code": null,
"e": 25528,
"s": 25356,
"text": "# Example: Suppose test is a web application \n# folder stored in downloads, I'll open terminal \n# in home screen \ncd ../Downloads/test/\n\n# Check the contents once here\nls"
},
{
"code": null,
"e": 25714,
"s": 25528,
"text": "Step 2: Installing Curl, OpenSSH-server, and vim editor in your distro for easy setup using the following commands. But before that, I’ll explain what are they and why need to use them."
},
{
"code": null,
"e": 25770,
"s": 25714,
"text": "Curl: CLI tool used to transfer data from a web server."
},
{
"code": null,
"e": 25921,
"s": 25770,
"text": "OpenSSH-server: OpenSSH-server is a collection of tools that are used for the remote control and transfer of data between remote networked computers."
},
{
"code": null,
"e": 26005,
"s": 25921,
"text": "Vim-editor: It is an editor that is used to create and modify text files in ubuntu."
},
{
"code": null,
"e": 26160,
"s": 26005,
"text": "# Commands to install all the above-required libraries in terminal \nsudo apt-get install curl\nsudo apt-get install openssh-server\nsudo apt-get install vim"
},
{
"code": null,
"e": 26211,
"s": 26160,
"text": "Now we have finished with our pre-requisites part."
},
{
"code": null,
"e": 26308,
"s": 26211,
"text": "Step 3: Now in this step we will copy our web application folder to this absolute path /var/www "
},
{
"code": null,
"e": 26421,
"s": 26308,
"text": "# change directory to parent folder where \n# you have stored the web application folder\nsudo cp -r test /var/www"
},
{
"code": null,
"e": 26734,
"s": 26421,
"text": "Step 4: Now we will point our domain name to the server where we will host this application. i.e. we need to add the IP address of your server to the DNS settings. Let’s suppose your server IP address is 0.0.0.0 and your domain name is www.test.com, then your domain name should point to your server IP address. "
},
{
"code": null,
"e": 26838,
"s": 26734,
"text": "For that we need to also do some settings in server, we need to create a file, we will use vim for that"
},
{
"code": null,
"e": 26908,
"s": 26838,
"text": "Firstly, change your directory to var/www/ then use the vim commands:"
},
{
"code": null,
"e": 26991,
"s": 26908,
"text": "# Change your directory \ncd var/www\n\n# Vim command for new file\nsudo vi /etc/hosts"
},
{
"code": null,
"e": 27061,
"s": 26991,
"text": "Now you will see a file with similar contents as shown in the picture"
},
{
"code": null,
"e": 27184,
"s": 27061,
"text": "you need to add your IP address here in starting and your domain name after it, you can use the below image for reference."
},
{
"code": null,
"e": 27400,
"s": 27184,
"text": "Step 5: As on a remote server, we need to add our web application folder to that server. For that, we need to change the permission of our web application folder. (your folder name of the web application can differ)"
},
{
"code": null,
"e": 27679,
"s": 27400,
"text": "# Change directory to /var/www/test\ncd /var/www/test\n\n# Change permission for your folder\nsudo chmod -R 777 *\n\n# Secure copy your files to web server\n# (Your IP address of server will be different)\n# (eg: scp -r * [email protected]:var/www/FOLDER_NAME)\nscp -r * 0.0.0.0:/var/www/test"
},
{
"code": null,
"e": 27733,
"s": 27679,
"text": "So our files have securely been copied to the server."
},
{
"code": null,
"e": 27849,
"s": 27733,
"text": "Step 6: So now, we will configure our Nginx Server to serve our website, let’s, first of all, see the Nginx folder "
},
{
"code": null,
"e": 27909,
"s": 27849,
"text": "# Change directory \ncd /etc/nginx\n\n# See Contents of it \nls"
},
{
"code": null,
"e": 27991,
"s": 27909,
"text": "Here we should be interested in 2 directories, sites-available and sites-enabled."
},
{
"code": null,
"e": 28088,
"s": 27991,
"text": "sites-available: It contains all the individual config files possible for your all static files."
},
{
"code": null,
"e": 28170,
"s": 28088,
"text": "sites-enabled: It contains the link to config files that Nginx will read and run."
},
{
"code": null,
"e": 28272,
"s": 28170,
"text": "So we need to create a config file in sites-available and a symbolic link in sites-enabled for Nginx."
},
{
"code": null,
"e": 28345,
"s": 28272,
"text": "Firstly, we will create a new file and add the following contents to it."
},
{
"code": null,
"e": 28601,
"s": 28345,
"text": "# Command to create and open a new file \nsudo vim sites-available/test\n\n# Now add the following contents to it\nserver {\nlisten 80 default_server;\nlisten [::] default_server;\nroot /var/www/test;\nindex index.html;\nlocation / {\ntry_files $url $url/ =404;\n}\n}"
},
{
"code": null,
"e": 28817,
"s": 28601,
"text": "Here we have opened socket 80 and your application port for default_server, we have told nginx where our web application files are. Location of our Index page, and if you get some wrong URL then through a 404 error."
},
{
"code": null,
"e": 28887,
"s": 28817,
"text": "Step 7: Now let us add this file to the sites-enabled folder in Nginx"
},
{
"code": null,
"e": 29006,
"s": 28887,
"text": "# Command to add file to sites-enabled folder\nsudo ln -s /etc/nginx/sites-available/test /etc/nginx/sites-enabled/test"
},
{
"code": null,
"e": 29288,
"s": 29006,
"text": "Amazing! Now we have one main issue, as earlier we had our Nginx server running, and we configured to open port 80 in our web application, and Nginx is also trying to open its default page using port 80. Hence we need to move that default files to somewhere else to avoid conflict."
},
{
"code": null,
"e": 29450,
"s": 29288,
"text": "# I generally move it to home directory \nsudo mv /etc/nginx/sites-enabled/default /home/yashtewatia/default\n\n# Restart Nginx service\nsudo systemctl restart nginx"
},
{
"code": null,
"e": 29622,
"s": 29450,
"text": "So we have restarted our nginx server! Now you can go to your IP address to view the contents in the browser or you can use the curl command for the same in terminal like,"
},
{
"code": null,
"e": 29704,
"s": 29622,
"text": "curl www.test.com\n# or we can give the IP address here of our server\ncurl 0.0.0.0"
},
{
"code": null,
"e": 29761,
"s": 29704,
"text": "Hence we have deployed our web files using Nginx Server."
},
{
"code": null,
"e": 29778,
"s": 29761,
"text": "Web Technologies"
},
{
"code": null,
"e": 29876,
"s": 29778,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29918,
"s": 29876,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29961,
"s": 29918,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30006,
"s": 29961,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30067,
"s": 30006,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30139,
"s": 30067,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 30184,
"s": 30139,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 30225,
"s": 30184,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 30270,
"s": 30225,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 30335,
"s": 30270,
"text": "How to pass data from child component to its parent in ReactJS ?"
}
] |
AbstractMap put() Method in Java with Examples - GeeksforGeeks | 26 Oct, 2018
The AbstractMap.put() method of AbstractMap is used to insert a mapping into a map. This means we can insert a specific key and the value it is mapping to, into a particular map. If an existing key is passed, then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole.
Syntax:
AbstractMap.put(key, value)
Parameters: The method takes two parameters, both are of the Object type of the AbstractMap:
key: This refers to the key element that needs to be inserted into the Map for mapping.
value: This refers to the value that the above key would map into.
Return Value: If an existing key is passed then the previous value gets returned. If a new pair is passed, then NULL is returned.
Below programs are used to illustrate the working of AbstractMap.put() Method:
Program 1: When passing an existing key.
// Java code to illustrate the put() method import java.util.*; public class Abstract_Map_Demo { public static void main(String[] args) { // Creating an empty AbstractMap AbstractMap<Integer, String> abs_map = new HashMap<Integer, String>(); // Mapping string values to int keys abs_map.put(10, "Geeks"); abs_map.put(15, "4"); abs_map.put(20, "Geeks"); abs_map.put(25, "Welcomes"); abs_map.put(30, "You"); // Displaying the AbstractMap System.out.println("Initial Mappings are: " + abs_map); // Inserting existing key along with new value String returned_value = (String)abs_map.put(20, "All"); // Verifying the returned value System.out.println("Returned value is: " + returned_value); // Displayin the new map System.out.println("New map is: " + abs_map); }}
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Returned value is: Geeks
New map is: {20=All, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Program 2: When passing a new key.
// Java code to illustrate the put() method import java.util.*; public class Abstract_Map_Demo { public static void main(String[] args) { // Creating an empty AbstractMap AbstractMap<Integer, String> abs_map = new HashMap<Integer, String>(); // Mapping string values to int keys abs_map.put(10, "Geeks"); abs_map.put(15, "4"); abs_map.put(20, "Geeks"); abs_map.put(25, "Welcomes"); abs_map.put(30, "You"); // Displaying the AbstractMap System.out.println("Initial Mappings are: " + abs_map); // Inserting existing key along with new value String returned_value = (String)abs_map.put(50, "All"); // Verifying the returned value System.out.println("Returned value is: " + returned_value); // Displayin the new map System.out.println("New map is: " + abs_map); }}
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Returned value is: null
New map is: {50=All, 20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.
Java - util package
Java-AbstractMap
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Introduction to Java
Difference between Abstract Class and Interface in Java | [
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n26 Oct, 2018"
},
{
"code": null,
"e": 24278,
"s": 23948,
"text": "The AbstractMap.put() method of AbstractMap is used to insert a mapping into a map. This means we can insert a specific key and the value it is mapping to, into a particular map. If an existing key is passed, then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole."
},
{
"code": null,
"e": 24286,
"s": 24278,
"text": "Syntax:"
},
{
"code": null,
"e": 24314,
"s": 24286,
"text": "AbstractMap.put(key, value)"
},
{
"code": null,
"e": 24407,
"s": 24314,
"text": "Parameters: The method takes two parameters, both are of the Object type of the AbstractMap:"
},
{
"code": null,
"e": 24495,
"s": 24407,
"text": "key: This refers to the key element that needs to be inserted into the Map for mapping."
},
{
"code": null,
"e": 24562,
"s": 24495,
"text": "value: This refers to the value that the above key would map into."
},
{
"code": null,
"e": 24692,
"s": 24562,
"text": "Return Value: If an existing key is passed then the previous value gets returned. If a new pair is passed, then NULL is returned."
},
{
"code": null,
"e": 24771,
"s": 24692,
"text": "Below programs are used to illustrate the working of AbstractMap.put() Method:"
},
{
"code": null,
"e": 24812,
"s": 24771,
"text": "Program 1: When passing an existing key."
},
{
"code": "// Java code to illustrate the put() method import java.util.*; public class Abstract_Map_Demo { public static void main(String[] args) { // Creating an empty AbstractMap AbstractMap<Integer, String> abs_map = new HashMap<Integer, String>(); // Mapping string values to int keys abs_map.put(10, \"Geeks\"); abs_map.put(15, \"4\"); abs_map.put(20, \"Geeks\"); abs_map.put(25, \"Welcomes\"); abs_map.put(30, \"You\"); // Displaying the AbstractMap System.out.println(\"Initial Mappings are: \" + abs_map); // Inserting existing key along with new value String returned_value = (String)abs_map.put(20, \"All\"); // Verifying the returned value System.out.println(\"Returned value is: \" + returned_value); // Displayin the new map System.out.println(\"New map is: \" + abs_map); }}",
"e": 25819,
"s": 24812,
"text": null
},
{
"code": null,
"e": 25973,
"s": 25819,
"text": "Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}\nReturned value is: Geeks\nNew map is: {20=All, 25=Welcomes, 10=Geeks, 30=You, 15=4}\n"
},
{
"code": null,
"e": 26008,
"s": 25973,
"text": "Program 2: When passing a new key."
},
{
"code": "// Java code to illustrate the put() method import java.util.*; public class Abstract_Map_Demo { public static void main(String[] args) { // Creating an empty AbstractMap AbstractMap<Integer, String> abs_map = new HashMap<Integer, String>(); // Mapping string values to int keys abs_map.put(10, \"Geeks\"); abs_map.put(15, \"4\"); abs_map.put(20, \"Geeks\"); abs_map.put(25, \"Welcomes\"); abs_map.put(30, \"You\"); // Displaying the AbstractMap System.out.println(\"Initial Mappings are: \" + abs_map); // Inserting existing key along with new value String returned_value = (String)abs_map.put(50, \"All\"); // Verifying the returned value System.out.println(\"Returned value is: \" + returned_value); // Displayin the new map System.out.println(\"New map is: \" + abs_map); }}",
"e": 26989,
"s": 26008,
"text": null
},
{
"code": null,
"e": 27152,
"s": 26989,
"text": "Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}\nReturned value is: null\nNew map is: {50=All, 20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}\n"
},
{
"code": null,
"e": 27276,
"s": 27152,
"text": "Note: The same operation can be performed with any type of Mappings with variation and combination of different data types."
},
{
"code": null,
"e": 27296,
"s": 27276,
"text": "Java - util package"
},
{
"code": null,
"e": 27313,
"s": 27296,
"text": "Java-AbstractMap"
},
{
"code": null,
"e": 27330,
"s": 27313,
"text": "Java-Collections"
},
{
"code": null,
"e": 27345,
"s": 27330,
"text": "Java-Functions"
},
{
"code": null,
"e": 27350,
"s": 27345,
"text": "Java"
},
{
"code": null,
"e": 27355,
"s": 27350,
"text": "Java"
},
{
"code": null,
"e": 27372,
"s": 27355,
"text": "Java-Collections"
},
{
"code": null,
"e": 27470,
"s": 27372,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27485,
"s": 27470,
"text": "Stream In Java"
},
{
"code": null,
"e": 27531,
"s": 27485,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27552,
"s": 27531,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27571,
"s": 27552,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27601,
"s": 27571,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27618,
"s": 27601,
"text": "Generics in Java"
},
{
"code": null,
"e": 27661,
"s": 27618,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27690,
"s": 27661,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 27711,
"s": 27690,
"text": "Introduction to Java"
}
] |
HTML DOM getElementsByTagName() method | The HTML DOM getElementsByTagName() method is used for getting the collection of all the elements in the document having a given tag name. It returns all the given elements as a NodeList object. You can access any element in the returned object using the index number.
The HTMLcollection returned stays sync with the DOM tree without calling the getElementsByTagName() method again and again after removing or adding some elements.
Following is the syntax for the getElementsByTagName() method −
element.getElementsByTagName(tagname)
Here, tagname is a mandatory parameter value indicating the child elements tagname that we want to get.
Let us look at an example for the getElementsByTagName() method −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script>
function changePara() {
var p = document.getElementsByTagName("P");
p[0].innerHTML = "This text has been changed";
p[1].style.color = "red";
p[1].style.backgroundColor = "yellow";
}
</script>
</head>
<body>
<h1>getElementsByTagName() example</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</p>
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat</p>
<button onclick="changePara()">CHANGE</button>
</body>
</html>
This will produce the following output −
On clicking the CHANGE button −
In the above example −
We have created two paragraphs that have no attributes associated with them −
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</p>
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat</p>
We have then created a button CHANGE that will execute the changePara() on being clicked by the user −
<button onclick="changePara()">CHANGE</button>
The changePara() method gets both the <p> elements as nodeListObject using the getElementsByTagName() method upon the document object and assigns it to variable p. Using the index numbers we change the text for the first paragraph and apply some styling to the second paragraph −
function changePara() {
var p = document.getElementsByClassName("PARA1");
p[0].innerHTML = "This text has been changed";
p[1].style.color = "red";
p[1].style.backgroundColor = "yellow";
} | [
{
"code": null,
"e": 1331,
"s": 1062,
"text": "The HTML DOM getElementsByTagName() method is used for getting the collection of all the elements in the document having a given tag name. It returns all the given elements as a NodeList object. You can access any element in the returned object using the index number."
},
{
"code": null,
"e": 1494,
"s": 1331,
"text": "The HTMLcollection returned stays sync with the DOM tree without calling the getElementsByTagName() method again and again after removing or adding some elements."
},
{
"code": null,
"e": 1558,
"s": 1494,
"text": "Following is the syntax for the getElementsByTagName() method −"
},
{
"code": null,
"e": 1596,
"s": 1558,
"text": "element.getElementsByTagName(tagname)"
},
{
"code": null,
"e": 1700,
"s": 1596,
"text": "Here, tagname is a mandatory parameter value indicating the child elements tagname that we want to get."
},
{
"code": null,
"e": 1766,
"s": 1700,
"text": "Let us look at an example for the getElementsByTagName() method −"
},
{
"code": null,
"e": 1776,
"s": 1766,
"text": "Live Demo"
},
{
"code": null,
"e": 2399,
"s": 1776,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<script>\n function changePara() {\n var p = document.getElementsByTagName(\"P\");\n p[0].innerHTML = \"This text has been changed\";\n p[1].style.color = \"red\";\n p[1].style.backgroundColor = \"yellow\";\n }\n</script>\n</head>\n<body>\n<h1>getElementsByTagName() example</h1>\n<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</p>\n<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat</p>\n<button onclick=\"changePara()\">CHANGE</button>\n</body>\n</html>"
},
{
"code": null,
"e": 2440,
"s": 2399,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2472,
"s": 2440,
"text": "On clicking the CHANGE button −"
},
{
"code": null,
"e": 2495,
"s": 2472,
"text": "In the above example −"
},
{
"code": null,
"e": 2573,
"s": 2495,
"text": "We have created two paragraphs that have no attributes associated with them −"
},
{
"code": null,
"e": 2818,
"s": 2573,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</p>\n\n<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat</p>"
},
{
"code": null,
"e": 2921,
"s": 2818,
"text": "We have then created a button CHANGE that will execute the changePara() on being clicked by the user −"
},
{
"code": null,
"e": 2968,
"s": 2921,
"text": "<button onclick=\"changePara()\">CHANGE</button>"
},
{
"code": null,
"e": 3248,
"s": 2968,
"text": "The changePara() method gets both the <p> elements as nodeListObject using the getElementsByTagName() method upon the document object and assigns it to variable p. Using the index numbers we change the text for the first paragraph and apply some styling to the second paragraph −"
},
{
"code": null,
"e": 3448,
"s": 3248,
"text": "function changePara() {\n var p = document.getElementsByClassName(\"PARA1\");\n p[0].innerHTML = \"This text has been changed\";\n p[1].style.color = \"red\";\n p[1].style.backgroundColor = \"yellow\";\n}"
}
] |
Prototyping a Recommender System Step by Step Part 1: KNN Item-Based Collaborative Filtering | by Kevin Liao | Towards Data Science | Part 2 of recommender systems can be found here
Most internet products we use today are powered by recommender systems. Youtube, Netflix, Amazon, Pinterest, and long list of other internet products all rely on recommender systems to filter millions of contents and make personalized recommendations to their users. Recommender systems are well-studied and proven to provide tremendous values to internet businesses and their consumers. In fact, I was shock at the news that Netflix awarded a $1 million prize to a developer team in 2009, for an algorithm that increased the accuracy of the company’s recommendation system by 10%.
Although recommender systems are the secret source for those multi-billion businesses, prototyping a recommender system can be very low cost and doesn’t require a team of scientists. You can actually develop your own personalized recommender for yourself. It only takes some basic machine learning techniques and implementations in Python. In this post, we will start from scratch and walk through the process of how to prototype a minimum viable movie recommender.
Recommender systems can be loosely broken down into three categories: content based systems, collaborative filtering systems, and hybrid systems (which use a combination of the other two).
Content based approach utilizes a series of discrete characteristics of an item in order to recommend additional items with similar properties. Collaborative filtering approach builds a model from a user’s past behaviors (items previously purchased or selected and/or numerical ratings given to those items) as well as similar decisions made by other users. This model is then used to predict items (or ratings for items) that the user may have an interest in. Hybrid approach combines the previous two approaches. Most businesses probably use hybrid approach in their production recommender systems.
In this post, we are going to start with the most common approach, collaborative filtering, with a simple vanilla version. In the future posts, we will develop more advanced and sophisticated methods to further improve our recommender’s performance and scalability.
I love watching movies so I decided to build a movie recommender. It will be so cool to see how well my recommender knows my movie preferences. We will go over our movie datasets, ML model choices, how to evaluate our recommender, and lastly I will give some pros and cons about this approach.
Sometimes it can be very hard to find a good dataset to start with. However, I still encourage you to find interesting datasets and build your own recommender. I found there are some good datasets on this page. Besides building a movie recommender, building a food or dating recommender can be very fun too. Just a thought! To build a movie recommender, I choose MovieLens Datasets. It contains 27,753,444 ratings and 1,108,997 tag applications across 58,098 movies. These data were created by 283,228 users between January 09, 1995 and September 26, 2018. The ratings are on a scale from 1 to 5. We will use only two files from MovieLens datasets: ratings.csvand movies.csv. Ratings data provides the ratings of movies given by users. There are three fields in each row: ['userId', 'movieId', 'rating']. Each row can be seen as a record of interaction between a user and a movie. Movies data provides a movie title and genres for each 'movieId' in Ratings data.
import osimport pandas as pd# configure file pathdata_path = os.path.join(os.environ['DATA_PATH'], 'MovieLens')movies_filename = 'movies.csv'ratings_filename = 'ratings.csv'# read datadf_movies = pd.read_csv( os.path.join(data_path, movies_filename), usecols=['movieId', 'title'], dtype={'movieId': 'int32', 'title': 'str'})df_ratings = pd.read_csv( os.path.join(data_path, ratings_filename), usecols=['userId', 'movieId', 'rating'], dtype={'userId': 'int32', 'movieId': 'int32', 'rating': 'float32'})
Let’s take a quick look at the two datasets: Movies and Ratings
In a real world setting, data collected from explicit feedbacks like movie ratings can be very sparse and data points are mostly collected from very popular items (movies) and highly engaged users. Large amount of less known items (movies) don’t have ratings at all. Let’s see plot the distribution of movie rating frequency.
If we zoom in or plot it on a log scale, we can find out that only about 13,500 out of 58,098 movies received ratings by more than 100 users and the majority rest are much less known with little or no user-interactions. These sparse ratings are less predictable for most users and highly sensitive to an individual person who loves the obscure movie, which makes the pattern very noisy.
Most models make recommendations based on user rating patterns. To remove noisy pattern and avoid “memory error” due to large datasets, we will filter our dataframe of ratings to only popular movies. After filtering, we are left with 13,500 movies in the Ratings data, which is enough for a recommendation model.
Collaborative filtering systems use the actions of users to recommend other movies. In general, they can either be user-based or item-based. Item based approach is usually preferred over user-based approach. User-based approach is often harder to scale because of the dynamic nature of users, whereas items usually don’t change much, and item based approach often can be computed offline and served without constantly re-training.
To implement an item based collaborative filtering, KNN is a perfect go-to model and also a very good baseline for recommender system development. But what is the KNN? KNN is a non-parametric, lazy learning method. It uses a database in which the data points are separated into several clusters to make inference for new samples.
KNN does not make any assumptions on the underlying data distribution but it relies on item feature similarity. When KNN makes inference about a movie, KNN will calculate the “distance” between the target movie and every other movie in its database, then it ranks its distances and returns the top K nearest neighbor movies as the most similar movie recommendations.
Wait, but how do we feed the dataframe of ratings into a KNN model? First, we need to transform the dataframe of ratings into a proper format that can be consumed by a KNN model. We want the data to be in an m x n array, where m is the number of movies and n is the number of users. To reshape dataframe of ratings, we’ll pivot the dataframe to the wide format with movies as rows and users as columns. Then we’ll fill the missing observations with 0s since we’re going to be performing linear algebra operations (calculating distances between vectors). Let’s call this new dataframe a “dataframe of movie features”.
Our dataframe of movie features is an extremely sparse matrix with a shape of 13,500 x 113,291. We definitely don't want to feed the entire data with mostly 0s in float32 datatype to KNN. For more efficient calculation and less memory footprint, we need to transform the values of the dataframe into a scipy sparse matrix.
from scipy.sparse import csr_matrix# pivot ratings into movie featuresdf_movie_features = df_ratings.pivot( index='movieId', columns='userId', values='rating').fillna(0)# convert dataframe of movie features to scipy sparse matrixmat_movie_features = csr_matrix(df_movie_features.values)
Now our training data has a very high dimensionality. KNN’s performance will suffer from curse of dimensionality if it uses “euclidean distance” in its objective function. Euclidean distance is unhelpful in high dimensions because all vectors are almost equidistant to the search query vector (target movie’s features). Instead, we will use cosine similarity for nearest neighbor search. There is also another popular approach to handle nearest neighbor search in high dimensional data, locality sensitive hashing, which we won’t cover in this post.
After we preprocessed the data and transformed the dataframe of ratings into a movie features scipy sparse matrix, we need to configure our KNN model with proper hyper-params:
from sklearn.neighbors import NearestNeighborsmodel_knn = NearestNeighbors(metric='cosine', algorithm='brute', n_neighbors=20, n_jobs=-1)
Finally we can make some movie recommendations for ourselves. Let’s implement a make_recommendations method in our KNN recommender.
This snippet demos our make_recommendations method in our recommender’s implementation. Please find the detailed source code for recommender application in my GitHub Repo.
If you go to my source code page, you see that I put together a KNN recommender system in a script as a small python application. I parameterized my recommender application and exposed two options, movie_name and top_n, for users to play around. Now I want to ask my recommender to propose top 10 most similar movies to “Iron Man”. So we can run below bash commend inside terminal (linux/mac): (instruction of commands can be found here)
python src/knn_recommender.py --movie_name "Iron Man" --top_n 10
Hooray!! Our recommender system actually works!! Now we have our own movie recommender.
At first glance, my recommender seems very impressive. I love all of its recommended movies. But if we really think about them, they were all very popular movies during the same time period as “Iron Man” in 2008. It’s very likely that people who watched “Iron Man” at that time probably also watched some of the recommended movies. This list of movies are not only popular during the same era but also share very similar genres and topics.
As a movie lover, I am probably looking for movies that I haven’t watched or movies with different topics. Recommending movies with diverse topics allow users to explore different tastes and keeps user engaged with the recommender product. On the other hand, lack of diversity will make users get bored and less engaged with the product. So we just effectively identify there are two shortcomings in item based collaborative filtering:
popularity bias: recommender is prone to recommender popular itemsitem cold-start problem: recommender fails to recommend new or less-known items because items have either none or very little interactions
popularity bias: recommender is prone to recommender popular items
item cold-start problem: recommender fails to recommend new or less-known items because items have either none or very little interactions
Recall the plot of distribution of movie rating frequency:
Only a very small fraction of movies have lots of user interactions while a “long-tail” of movies don’t have. In a business setting, high-frequency items tend to be relatively competitive items with little profit for the merchant. On the other hand, the lower frequency items have larger profit margins.
How do we improve our movie recommender system to solve above two shortcomings? We will cover a more sophisticated method to improve movie recommender in next post: Prototyping a Recommender System Step by Step Part 2: Alternating Least Square (ALS) Matrix Factorization in Collaborative Filtering
In this post, we briefly covered three approaches in recommender system: content-based, collaborative filtering, and hybrid. We learned about how to prototype an item based collaborative filtering in KNN with only a few steps! The Jupyter Notebook version for this blog post can be found here. If you want to play around my source code, you can find it here. In my next post, we will cover more advanced topics in recommender systems and leverage Spark to build a scalable recommender system. Stay tuned! Until then, have fun with machine learning and recommenders!
Like what you read? Checkout more data science / machine learning projects at my Github: Kevin’s Data Science Portfolio | [
{
"code": null,
"e": 95,
"s": 47,
"text": "Part 2 of recommender systems can be found here"
},
{
"code": null,
"e": 677,
"s": 95,
"text": "Most internet products we use today are powered by recommender systems. Youtube, Netflix, Amazon, Pinterest, and long list of other internet products all rely on recommender systems to filter millions of contents and make personalized recommendations to their users. Recommender systems are well-studied and proven to provide tremendous values to internet businesses and their consumers. In fact, I was shock at the news that Netflix awarded a $1 million prize to a developer team in 2009, for an algorithm that increased the accuracy of the company’s recommendation system by 10%."
},
{
"code": null,
"e": 1143,
"s": 677,
"text": "Although recommender systems are the secret source for those multi-billion businesses, prototyping a recommender system can be very low cost and doesn’t require a team of scientists. You can actually develop your own personalized recommender for yourself. It only takes some basic machine learning techniques and implementations in Python. In this post, we will start from scratch and walk through the process of how to prototype a minimum viable movie recommender."
},
{
"code": null,
"e": 1332,
"s": 1143,
"text": "Recommender systems can be loosely broken down into three categories: content based systems, collaborative filtering systems, and hybrid systems (which use a combination of the other two)."
},
{
"code": null,
"e": 1933,
"s": 1332,
"text": "Content based approach utilizes a series of discrete characteristics of an item in order to recommend additional items with similar properties. Collaborative filtering approach builds a model from a user’s past behaviors (items previously purchased or selected and/or numerical ratings given to those items) as well as similar decisions made by other users. This model is then used to predict items (or ratings for items) that the user may have an interest in. Hybrid approach combines the previous two approaches. Most businesses probably use hybrid approach in their production recommender systems."
},
{
"code": null,
"e": 2199,
"s": 1933,
"text": "In this post, we are going to start with the most common approach, collaborative filtering, with a simple vanilla version. In the future posts, we will develop more advanced and sophisticated methods to further improve our recommender’s performance and scalability."
},
{
"code": null,
"e": 2493,
"s": 2199,
"text": "I love watching movies so I decided to build a movie recommender. It will be so cool to see how well my recommender knows my movie preferences. We will go over our movie datasets, ML model choices, how to evaluate our recommender, and lastly I will give some pros and cons about this approach."
},
{
"code": null,
"e": 3457,
"s": 2493,
"text": "Sometimes it can be very hard to find a good dataset to start with. However, I still encourage you to find interesting datasets and build your own recommender. I found there are some good datasets on this page. Besides building a movie recommender, building a food or dating recommender can be very fun too. Just a thought! To build a movie recommender, I choose MovieLens Datasets. It contains 27,753,444 ratings and 1,108,997 tag applications across 58,098 movies. These data were created by 283,228 users between January 09, 1995 and September 26, 2018. The ratings are on a scale from 1 to 5. We will use only two files from MovieLens datasets: ratings.csvand movies.csv. Ratings data provides the ratings of movies given by users. There are three fields in each row: ['userId', 'movieId', 'rating']. Each row can be seen as a record of interaction between a user and a movie. Movies data provides a movie title and genres for each 'movieId' in Ratings data."
},
{
"code": null,
"e": 3977,
"s": 3457,
"text": "import osimport pandas as pd# configure file pathdata_path = os.path.join(os.environ['DATA_PATH'], 'MovieLens')movies_filename = 'movies.csv'ratings_filename = 'ratings.csv'# read datadf_movies = pd.read_csv( os.path.join(data_path, movies_filename), usecols=['movieId', 'title'], dtype={'movieId': 'int32', 'title': 'str'})df_ratings = pd.read_csv( os.path.join(data_path, ratings_filename), usecols=['userId', 'movieId', 'rating'], dtype={'userId': 'int32', 'movieId': 'int32', 'rating': 'float32'})"
},
{
"code": null,
"e": 4041,
"s": 3977,
"text": "Let’s take a quick look at the two datasets: Movies and Ratings"
},
{
"code": null,
"e": 4367,
"s": 4041,
"text": "In a real world setting, data collected from explicit feedbacks like movie ratings can be very sparse and data points are mostly collected from very popular items (movies) and highly engaged users. Large amount of less known items (movies) don’t have ratings at all. Let’s see plot the distribution of movie rating frequency."
},
{
"code": null,
"e": 4754,
"s": 4367,
"text": "If we zoom in or plot it on a log scale, we can find out that only about 13,500 out of 58,098 movies received ratings by more than 100 users and the majority rest are much less known with little or no user-interactions. These sparse ratings are less predictable for most users and highly sensitive to an individual person who loves the obscure movie, which makes the pattern very noisy."
},
{
"code": null,
"e": 5067,
"s": 4754,
"text": "Most models make recommendations based on user rating patterns. To remove noisy pattern and avoid “memory error” due to large datasets, we will filter our dataframe of ratings to only popular movies. After filtering, we are left with 13,500 movies in the Ratings data, which is enough for a recommendation model."
},
{
"code": null,
"e": 5498,
"s": 5067,
"text": "Collaborative filtering systems use the actions of users to recommend other movies. In general, they can either be user-based or item-based. Item based approach is usually preferred over user-based approach. User-based approach is often harder to scale because of the dynamic nature of users, whereas items usually don’t change much, and item based approach often can be computed offline and served without constantly re-training."
},
{
"code": null,
"e": 5828,
"s": 5498,
"text": "To implement an item based collaborative filtering, KNN is a perfect go-to model and also a very good baseline for recommender system development. But what is the KNN? KNN is a non-parametric, lazy learning method. It uses a database in which the data points are separated into several clusters to make inference for new samples."
},
{
"code": null,
"e": 6195,
"s": 5828,
"text": "KNN does not make any assumptions on the underlying data distribution but it relies on item feature similarity. When KNN makes inference about a movie, KNN will calculate the “distance” between the target movie and every other movie in its database, then it ranks its distances and returns the top K nearest neighbor movies as the most similar movie recommendations."
},
{
"code": null,
"e": 6812,
"s": 6195,
"text": "Wait, but how do we feed the dataframe of ratings into a KNN model? First, we need to transform the dataframe of ratings into a proper format that can be consumed by a KNN model. We want the data to be in an m x n array, where m is the number of movies and n is the number of users. To reshape dataframe of ratings, we’ll pivot the dataframe to the wide format with movies as rows and users as columns. Then we’ll fill the missing observations with 0s since we’re going to be performing linear algebra operations (calculating distances between vectors). Let’s call this new dataframe a “dataframe of movie features”."
},
{
"code": null,
"e": 7135,
"s": 6812,
"text": "Our dataframe of movie features is an extremely sparse matrix with a shape of 13,500 x 113,291. We definitely don't want to feed the entire data with mostly 0s in float32 datatype to KNN. For more efficient calculation and less memory footprint, we need to transform the values of the dataframe into a scipy sparse matrix."
},
{
"code": null,
"e": 7431,
"s": 7135,
"text": "from scipy.sparse import csr_matrix# pivot ratings into movie featuresdf_movie_features = df_ratings.pivot( index='movieId', columns='userId', values='rating').fillna(0)# convert dataframe of movie features to scipy sparse matrixmat_movie_features = csr_matrix(df_movie_features.values)"
},
{
"code": null,
"e": 7981,
"s": 7431,
"text": "Now our training data has a very high dimensionality. KNN’s performance will suffer from curse of dimensionality if it uses “euclidean distance” in its objective function. Euclidean distance is unhelpful in high dimensions because all vectors are almost equidistant to the search query vector (target movie’s features). Instead, we will use cosine similarity for nearest neighbor search. There is also another popular approach to handle nearest neighbor search in high dimensional data, locality sensitive hashing, which we won’t cover in this post."
},
{
"code": null,
"e": 8157,
"s": 7981,
"text": "After we preprocessed the data and transformed the dataframe of ratings into a movie features scipy sparse matrix, we need to configure our KNN model with proper hyper-params:"
},
{
"code": null,
"e": 8295,
"s": 8157,
"text": "from sklearn.neighbors import NearestNeighborsmodel_knn = NearestNeighbors(metric='cosine', algorithm='brute', n_neighbors=20, n_jobs=-1)"
},
{
"code": null,
"e": 8427,
"s": 8295,
"text": "Finally we can make some movie recommendations for ourselves. Let’s implement a make_recommendations method in our KNN recommender."
},
{
"code": null,
"e": 8599,
"s": 8427,
"text": "This snippet demos our make_recommendations method in our recommender’s implementation. Please find the detailed source code for recommender application in my GitHub Repo."
},
{
"code": null,
"e": 9037,
"s": 8599,
"text": "If you go to my source code page, you see that I put together a KNN recommender system in a script as a small python application. I parameterized my recommender application and exposed two options, movie_name and top_n, for users to play around. Now I want to ask my recommender to propose top 10 most similar movies to “Iron Man”. So we can run below bash commend inside terminal (linux/mac): (instruction of commands can be found here)"
},
{
"code": null,
"e": 9102,
"s": 9037,
"text": "python src/knn_recommender.py --movie_name \"Iron Man\" --top_n 10"
},
{
"code": null,
"e": 9190,
"s": 9102,
"text": "Hooray!! Our recommender system actually works!! Now we have our own movie recommender."
},
{
"code": null,
"e": 9630,
"s": 9190,
"text": "At first glance, my recommender seems very impressive. I love all of its recommended movies. But if we really think about them, they were all very popular movies during the same time period as “Iron Man” in 2008. It’s very likely that people who watched “Iron Man” at that time probably also watched some of the recommended movies. This list of movies are not only popular during the same era but also share very similar genres and topics."
},
{
"code": null,
"e": 10066,
"s": 9630,
"text": "As a movie lover, I am probably looking for movies that I haven’t watched or movies with different topics. Recommending movies with diverse topics allow users to explore different tastes and keeps user engaged with the recommender product. On the other hand, lack of diversity will make users get bored and less engaged with the product. So we just effectively identify there are two shortcomings in item based collaborative filtering:"
},
{
"code": null,
"e": 10271,
"s": 10066,
"text": "popularity bias: recommender is prone to recommender popular itemsitem cold-start problem: recommender fails to recommend new or less-known items because items have either none or very little interactions"
},
{
"code": null,
"e": 10338,
"s": 10271,
"text": "popularity bias: recommender is prone to recommender popular items"
},
{
"code": null,
"e": 10477,
"s": 10338,
"text": "item cold-start problem: recommender fails to recommend new or less-known items because items have either none or very little interactions"
},
{
"code": null,
"e": 10536,
"s": 10477,
"text": "Recall the plot of distribution of movie rating frequency:"
},
{
"code": null,
"e": 10840,
"s": 10536,
"text": "Only a very small fraction of movies have lots of user interactions while a “long-tail” of movies don’t have. In a business setting, high-frequency items tend to be relatively competitive items with little profit for the merchant. On the other hand, the lower frequency items have larger profit margins."
},
{
"code": null,
"e": 11138,
"s": 10840,
"text": "How do we improve our movie recommender system to solve above two shortcomings? We will cover a more sophisticated method to improve movie recommender in next post: Prototyping a Recommender System Step by Step Part 2: Alternating Least Square (ALS) Matrix Factorization in Collaborative Filtering"
},
{
"code": null,
"e": 11704,
"s": 11138,
"text": "In this post, we briefly covered three approaches in recommender system: content-based, collaborative filtering, and hybrid. We learned about how to prototype an item based collaborative filtering in KNN with only a few steps! The Jupyter Notebook version for this blog post can be found here. If you want to play around my source code, you can find it here. In my next post, we will cover more advanced topics in recommender systems and leverage Spark to build a scalable recommender system. Stay tuned! Until then, have fun with machine learning and recommenders!"
}
] |
What is the Mutex class in C#? | The Mutex class in C# is a synchronization primitive that can also be used for interprocess synchronization.
Let us see how to create a new Mutex.
private static Mutex m = new Mutex();
Let us now see how to initialize a new instance of the Mutex class with a Boolean value.
private static Mutex m = new Mutex(true);
Now let us see how to initialize a new instance of the Mutex class with a Boolean value and the name of the Mutex.
Live Demo
using System;
using System.Threading;
public class Demo {
public static void Main() {
Mutex mt = new Mutex(false, "NewMutex");
Console.WriteLine("Waiting for the Mutex.");
mt.WaitOne();
Console.WriteLine("Owner of the mutex. " + "ENTER is to be pressed to release the mutexand exit.");
Console.ReadLine();
mt.ReleaseMutex();
}
}
Waiting for the Mutex.
Owner of the mutex. ENTER is to be pressed to release the mutex and exit. | [
{
"code": null,
"e": 1171,
"s": 1062,
"text": "The Mutex class in C# is a synchronization primitive that can also be used for interprocess synchronization."
},
{
"code": null,
"e": 1209,
"s": 1171,
"text": "Let us see how to create a new Mutex."
},
{
"code": null,
"e": 1247,
"s": 1209,
"text": "private static Mutex m = new Mutex();"
},
{
"code": null,
"e": 1336,
"s": 1247,
"text": "Let us now see how to initialize a new instance of the Mutex class with a Boolean value."
},
{
"code": null,
"e": 1378,
"s": 1336,
"text": "private static Mutex m = new Mutex(true);"
},
{
"code": null,
"e": 1493,
"s": 1378,
"text": "Now let us see how to initialize a new instance of the Mutex class with a Boolean value and the name of the Mutex."
},
{
"code": null,
"e": 1504,
"s": 1493,
"text": " Live Demo"
},
{
"code": null,
"e": 1885,
"s": 1504,
"text": "using System;\nusing System.Threading;\n\npublic class Demo {\n public static void Main() {\n Mutex mt = new Mutex(false, \"NewMutex\");\n Console.WriteLine(\"Waiting for the Mutex.\");\n mt.WaitOne();\n Console.WriteLine(\"Owner of the mutex. \" + \"ENTER is to be pressed to release the mutexand exit.\");\n Console.ReadLine();\n mt.ReleaseMutex();\n }\n}"
},
{
"code": null,
"e": 1982,
"s": 1885,
"text": "Waiting for the Mutex.\nOwner of the mutex. ENTER is to be pressed to release the mutex and exit."
}
] |
Matrix Computation With NumPy | Towards Data Science | Performance is really an important aspect when we are solving problems using Machine Learning, especially Deep Learning. Using a neural network for calculating things can become a complex calculation because it involves matrix and vectors to it.
Suppose we want to calculate a 25 x 25 matrix that is being multiplied by 5. At the first time you are being introduced to programming, You will calculate vectors or matrices that look like this,
for i in range(25): for j in range(25): x[i][j] *= 5
If we use this method, it will make our computation longer and we will not get the result at the time that we desired. Thankfully, in Python, we have NumPy library to solve this matrix and vector calculation.
By using NumPy library, we can make that 3-lines of code become 1-line of code like this one below,
import numpy as np# Make it as NumPy array firstx = np.array(x)x = x * 5
And if we compare the time, for this case, the conventional way will take around 0.000224 and the NumPy method is just 0.000076. The NumPy is almost 3 times faster than the conventional one, but it also simplifies your code at the same time!
Just imagine when you want to calculate a bigger matrix than in this example here and imagine how much the time that will you save. This calculation is classified as vectorization where the calculation has occurred on a matrix or vector representation. Therefore, with that computation method, it will save your time for the same result.
How is that happen? What is the magic of NumPy so it can calculate the matrix simpler and faster? This article will introduce you to the concepts of Single Instruction Multiple Data (SIMD) and Broadcasting. Without further, let’s get to it.
What is Single Instruction Multiple Data (SIMD)? Basically, SIMD (pronounced as “sim-dee” not spell it by the alphabet) is a parallel computation method to make the data inside the computer can be calculated at the same time (concurrently) by the hardware.
For example, we have the 2-input vectors and we want to calculate the vector by each element arithmetically. The hardware will, so each data will be distributed to a different component of the hardware (i.e. the GPU-core) and calculate each element of both vectors at the same time. Because of that, the vectors can be calculated faster because of it.
In NumPy, the calculation works when meeting these requirements, they are:
The dimensions on both objects are the same, orOn of them have dimension’s value 1
The dimensions on both objects are the same, or
On of them have dimension’s value 1
If the objects do not meet with the requirements above, it cannot be calculated. If there some objects that met the 2nd requirement, therefore that object will be broadcasted.
Broadcasting is being used basically on vectors that have not the same shape on it. Recall the calculation above between the matrix and the scalar element, which is 5, the scalar will be broadcasted so the scalar will have the same shape as the matrix. Example, when you have these objects,
A 5 x 1 vectors in example 2 [1 2 3 4 5]
A 1 x 1 scalar in the example is 5
To make this happen, the scalar will have the same shape as the vector and the value will be broadcast across the new vector. So we can have [5 5 5 5 5] vector. With that matrix, we can calculate the vector and scalar that is being converted to a vector by using the principle of SIMD. Therefore, the result will be [5 10 15 20 25] as illustrated below,
In conclusion, the computation for machine learning is not separated from vectors and matrices. Understanding Linear Algebra will be useful if you want to develop some machine learning model from scratch, especially on the vectorization part. By doing so, we can make our computation more efficient and simpler thanks to the concepts of SIMD and Broadcasting.
[1] João M.P. Cardoso, José Gabriel F. Coutinho and Pedro C. Diniz, Embedded Computing for High Performance (2017), Elsevier Inc.[2] Stéfan van der Walt, S. Chris Colbert and Gaël Varoquaux. The NumPy Array: A Structure for Efficient Numerical Computation (2011), Computing in Science & Engineering, vol. 13, no. 2, pp. 22–30. | [
{
"code": null,
"e": 418,
"s": 172,
"text": "Performance is really an important aspect when we are solving problems using Machine Learning, especially Deep Learning. Using a neural network for calculating things can become a complex calculation because it involves matrix and vectors to it."
},
{
"code": null,
"e": 614,
"s": 418,
"text": "Suppose we want to calculate a 25 x 25 matrix that is being multiplied by 5. At the first time you are being introduced to programming, You will calculate vectors or matrices that look like this,"
},
{
"code": null,
"e": 677,
"s": 614,
"text": "for i in range(25): for j in range(25): x[i][j] *= 5"
},
{
"code": null,
"e": 886,
"s": 677,
"text": "If we use this method, it will make our computation longer and we will not get the result at the time that we desired. Thankfully, in Python, we have NumPy library to solve this matrix and vector calculation."
},
{
"code": null,
"e": 986,
"s": 886,
"text": "By using NumPy library, we can make that 3-lines of code become 1-line of code like this one below,"
},
{
"code": null,
"e": 1059,
"s": 986,
"text": "import numpy as np# Make it as NumPy array firstx = np.array(x)x = x * 5"
},
{
"code": null,
"e": 1301,
"s": 1059,
"text": "And if we compare the time, for this case, the conventional way will take around 0.000224 and the NumPy method is just 0.000076. The NumPy is almost 3 times faster than the conventional one, but it also simplifies your code at the same time!"
},
{
"code": null,
"e": 1639,
"s": 1301,
"text": "Just imagine when you want to calculate a bigger matrix than in this example here and imagine how much the time that will you save. This calculation is classified as vectorization where the calculation has occurred on a matrix or vector representation. Therefore, with that computation method, it will save your time for the same result."
},
{
"code": null,
"e": 1880,
"s": 1639,
"text": "How is that happen? What is the magic of NumPy so it can calculate the matrix simpler and faster? This article will introduce you to the concepts of Single Instruction Multiple Data (SIMD) and Broadcasting. Without further, let’s get to it."
},
{
"code": null,
"e": 2137,
"s": 1880,
"text": "What is Single Instruction Multiple Data (SIMD)? Basically, SIMD (pronounced as “sim-dee” not spell it by the alphabet) is a parallel computation method to make the data inside the computer can be calculated at the same time (concurrently) by the hardware."
},
{
"code": null,
"e": 2489,
"s": 2137,
"text": "For example, we have the 2-input vectors and we want to calculate the vector by each element arithmetically. The hardware will, so each data will be distributed to a different component of the hardware (i.e. the GPU-core) and calculate each element of both vectors at the same time. Because of that, the vectors can be calculated faster because of it."
},
{
"code": null,
"e": 2564,
"s": 2489,
"text": "In NumPy, the calculation works when meeting these requirements, they are:"
},
{
"code": null,
"e": 2647,
"s": 2564,
"text": "The dimensions on both objects are the same, orOn of them have dimension’s value 1"
},
{
"code": null,
"e": 2695,
"s": 2647,
"text": "The dimensions on both objects are the same, or"
},
{
"code": null,
"e": 2731,
"s": 2695,
"text": "On of them have dimension’s value 1"
},
{
"code": null,
"e": 2907,
"s": 2731,
"text": "If the objects do not meet with the requirements above, it cannot be calculated. If there some objects that met the 2nd requirement, therefore that object will be broadcasted."
},
{
"code": null,
"e": 3198,
"s": 2907,
"text": "Broadcasting is being used basically on vectors that have not the same shape on it. Recall the calculation above between the matrix and the scalar element, which is 5, the scalar will be broadcasted so the scalar will have the same shape as the matrix. Example, when you have these objects,"
},
{
"code": null,
"e": 3239,
"s": 3198,
"text": "A 5 x 1 vectors in example 2 [1 2 3 4 5]"
},
{
"code": null,
"e": 3274,
"s": 3239,
"text": "A 1 x 1 scalar in the example is 5"
},
{
"code": null,
"e": 3628,
"s": 3274,
"text": "To make this happen, the scalar will have the same shape as the vector and the value will be broadcast across the new vector. So we can have [5 5 5 5 5] vector. With that matrix, we can calculate the vector and scalar that is being converted to a vector by using the principle of SIMD. Therefore, the result will be [5 10 15 20 25] as illustrated below,"
},
{
"code": null,
"e": 3988,
"s": 3628,
"text": "In conclusion, the computation for machine learning is not separated from vectors and matrices. Understanding Linear Algebra will be useful if you want to develop some machine learning model from scratch, especially on the vectorization part. By doing so, we can make our computation more efficient and simpler thanks to the concepts of SIMD and Broadcasting."
}
] |
Xamarin - Permissions | In Android, by default, no application has permissions to perform any operations that would have an effect on the user or the operating system. In order for an App to perform a task, it must declare the permissions. The App cannot perform the task until the permission are granted by the Android system. This mechanism of permissions stops applications from doing as they wish without the user’s consent.
Permissions are to be recorded in AndroidManifest.xml file. To add permissions, we double-click on properties, then go to Android ManRequired permissions will appear. Check the appropriate permissions you wish to add.
Camera − It provides permission to access the device’s camera.
<uses-permission android:name="android.permission.CAMERA" />
Internet − It provides access to network resources.
<uses-permission android:name="android.permission.INTERNET" />
ReadContacts − It provides access to read the contacts on your device.
<uses-permission android:name="android.permission.READ_CONTACTS" />
ReadExternalStorage − It provides access to read and store data on an external storage.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Calendars − It allows an app access to the calendar on the user device and events. This permission can be dangerous, as it grants an app the ability to send emails to guests without the owner’s awareness. The syntax for adding this permission is as shown below −
<uses-permission android:name="android.permission-group.CALENADAR" />
SMS − An app with this permission has the ability to use the devices messaging services. It includes reading, writing, and editing SMS and MMS messages. Its syntax is as shown below.
<uses-permission android:name="android.permission-group.SMS" />
Location − An app with this permission can access the device’s location using the GPS network.
<uses-permission android:name="android.permission-group.LOCATION" />
Bluetooth − An app with this permission can exchange data files with other Bluetooth enabled devices wirelessly.
<uses-permission android:name="android.permission.BLUETOOTH" />
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2369,
"s": 1964,
"text": "In Android, by default, no application has permissions to perform any operations that would have an effect on the user or the operating system. In order for an App to perform a task, it must declare the permissions. The App cannot perform the task until the permission are granted by the Android system. This mechanism of permissions stops applications from doing as they wish without the user’s consent."
},
{
"code": null,
"e": 2587,
"s": 2369,
"text": "Permissions are to be recorded in AndroidManifest.xml file. To add permissions, we double-click on properties, then go to Android ManRequired permissions will appear. Check the appropriate permissions you wish to add."
},
{
"code": null,
"e": 2650,
"s": 2587,
"text": "Camera − It provides permission to access the device’s camera."
},
{
"code": null,
"e": 2712,
"s": 2650,
"text": "<uses-permission android:name=\"android.permission.CAMERA\" />\n"
},
{
"code": null,
"e": 2764,
"s": 2712,
"text": "Internet − It provides access to network resources."
},
{
"code": null,
"e": 2829,
"s": 2764,
"text": "<uses-permission android:name=\"android.permission.INTERNET\" /> \n"
},
{
"code": null,
"e": 2900,
"s": 2829,
"text": "ReadContacts − It provides access to read the contacts on your device."
},
{
"code": null,
"e": 2970,
"s": 2900,
"text": "<uses-permission android:name=\"android.permission.READ_CONTACTS\" /> \n"
},
{
"code": null,
"e": 3058,
"s": 2970,
"text": "ReadExternalStorage − It provides access to read and store data on an external storage."
},
{
"code": null,
"e": 3136,
"s": 3058,
"text": "<uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\" /> \n"
},
{
"code": null,
"e": 3399,
"s": 3136,
"text": "Calendars − It allows an app access to the calendar on the user device and events. This permission can be dangerous, as it grants an app the ability to send emails to guests without the owner’s awareness. The syntax for adding this permission is as shown below −"
},
{
"code": null,
"e": 3471,
"s": 3399,
"text": "<uses-permission android:name=\"android.permission-group.CALENADAR\" /> \n"
},
{
"code": null,
"e": 3654,
"s": 3471,
"text": "SMS − An app with this permission has the ability to use the devices messaging services. It includes reading, writing, and editing SMS and MMS messages. Its syntax is as shown below."
},
{
"code": null,
"e": 3719,
"s": 3654,
"text": "<uses-permission android:name=\"android.permission-group.SMS\" />\n"
},
{
"code": null,
"e": 3814,
"s": 3719,
"text": "Location − An app with this permission can access the device’s location using the GPS network."
},
{
"code": null,
"e": 3885,
"s": 3814,
"text": "<uses-permission android:name=\"android.permission-group.LOCATION\" /> \n"
},
{
"code": null,
"e": 3998,
"s": 3885,
"text": "Bluetooth − An app with this permission can exchange data files with other Bluetooth enabled devices wirelessly."
},
{
"code": null,
"e": 4063,
"s": 3998,
"text": "<uses-permission android:name=\"android.permission.BLUETOOTH\" />\n"
},
{
"code": null,
"e": 4070,
"s": 4063,
"text": " Print"
},
{
"code": null,
"e": 4081,
"s": 4070,
"text": " Add Notes"
}
] |
C# Program to Print the Current Assembly Name Using GetExecutingAssembly() Method - GeeksforGeeks | 16 Nov, 2021
In C#, GetExecutingAssembly() method is the method of Assembly class. This method returns the assembly that contains the code that is currently executing. To use this method we have to use System.Reflection in our program.
Syntax:
public static System.Reflection.Assembly GetExecutingAssembly ();
It will return the current program assembly, version, culture, and PublicKeyToken.
Example 1:
C#
// C# program to display the current assembly name using System;using System.Reflection; class GFG{ static void Main(string[] args){ Console.WriteLine("Current assembly contains:"); // Get the executing assembly // Using GetExecutingAssembly() method Console.WriteLine(Assembly.GetExecutingAssembly());}}
Output:
Current assembly contains:
main, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
Example 2:
C#
// C# program to display the current assembly name using System;using System.Reflection; class GFG{ static void Main(string[] args){ // Get the executing assembly // with FullName property // FullName property is use // to print the name of the assembly Console.WriteLine(Assembly.GetExecutingAssembly().FullName);}}
Output:
main, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to calculate Electricity Bill
Linked List Implementation in C#
C# | How to insert an element in an Array?
HashSet in C# with Examples
Lambda Expressions in C#
Convert String to Character Array in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
Socket Programming in C#
Program to find absolute value of a given number | [
{
"code": null,
"e": 23935,
"s": 23907,
"text": "\n16 Nov, 2021"
},
{
"code": null,
"e": 24158,
"s": 23935,
"text": "In C#, GetExecutingAssembly() method is the method of Assembly class. This method returns the assembly that contains the code that is currently executing. To use this method we have to use System.Reflection in our program."
},
{
"code": null,
"e": 24166,
"s": 24158,
"text": "Syntax:"
},
{
"code": null,
"e": 24232,
"s": 24166,
"text": "public static System.Reflection.Assembly GetExecutingAssembly ();"
},
{
"code": null,
"e": 24316,
"s": 24232,
"text": "It will return the current program assembly, version, culture, and PublicKeyToken. "
},
{
"code": null,
"e": 24327,
"s": 24316,
"text": "Example 1:"
},
{
"code": null,
"e": 24330,
"s": 24327,
"text": "C#"
},
{
"code": "// C# program to display the current assembly name using System;using System.Reflection; class GFG{ static void Main(string[] args){ Console.WriteLine(\"Current assembly contains:\"); // Get the executing assembly // Using GetExecutingAssembly() method Console.WriteLine(Assembly.GetExecutingAssembly());}}",
"e": 24657,
"s": 24330,
"text": null
},
{
"code": null,
"e": 24665,
"s": 24657,
"text": "Output:"
},
{
"code": null,
"e": 24752,
"s": 24665,
"text": "Current assembly contains:\nmain, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"
},
{
"code": null,
"e": 24763,
"s": 24752,
"text": "Example 2:"
},
{
"code": null,
"e": 24766,
"s": 24763,
"text": "C#"
},
{
"code": "// C# program to display the current assembly name using System;using System.Reflection; class GFG{ static void Main(string[] args){ // Get the executing assembly // with FullName property // FullName property is use // to print the name of the assembly Console.WriteLine(Assembly.GetExecutingAssembly().FullName);}}",
"e": 25112,
"s": 24766,
"text": null
},
{
"code": null,
"e": 25120,
"s": 25112,
"text": "Output:"
},
{
"code": null,
"e": 25180,
"s": 25120,
"text": "main, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"
},
{
"code": null,
"e": 25187,
"s": 25180,
"text": "Picked"
},
{
"code": null,
"e": 25190,
"s": 25187,
"text": "C#"
},
{
"code": null,
"e": 25202,
"s": 25190,
"text": "C# Programs"
},
{
"code": null,
"e": 25300,
"s": 25202,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25309,
"s": 25300,
"text": "Comments"
},
{
"code": null,
"e": 25322,
"s": 25309,
"text": "Old Comments"
},
{
"code": null,
"e": 25360,
"s": 25322,
"text": "Program to calculate Electricity Bill"
},
{
"code": null,
"e": 25393,
"s": 25360,
"text": "Linked List Implementation in C#"
},
{
"code": null,
"e": 25436,
"s": 25393,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 25464,
"s": 25436,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 25489,
"s": 25464,
"text": "Lambda Expressions in C#"
},
{
"code": null,
"e": 25529,
"s": 25489,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 25563,
"s": 25529,
"text": "Program to Print a New Line in C#"
},
{
"code": null,
"e": 25609,
"s": 25563,
"text": "Getting a Month Name Using Month Number in C#"
},
{
"code": null,
"e": 25634,
"s": 25609,
"text": "Socket Programming in C#"
}
] |
WebGL - Rotation | In this chapter, we will take an example to demonstrate how to rotate a triangle using WebGL.
The following program shows how to rotate a triangle using WebGL.
<!doctype html>
<html>
<body>
<canvas width = "400" height = "400" id = "my_Canvas"></canvas>
<script>
/*=================Creating a canvas=========================*/
var canvas = document.getElementById('my_Canvas');
gl = canvas.getContext('experimental-webgl');
/*===========Defining and storing the geometry==============*/
var vertices = [ -1,-1,-1, 1,-1,-1, 1, 1,-1 ];
var colors = [ 1,1,1, 1,1,1, 1,1,1 ];
var indices = [ 0,1,2 ];
//Create and store data into vertex buffer
var vertex_buffer = gl.createBuffer ();
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
//Create and store data into color buffer
var color_buffer = gl.createBuffer ();
gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
//Create and store data into index buffer
var index_buffer = gl.createBuffer ();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
/*==========================Shaders=========================*/
var vertCode = 'attribute vec3 position;'+
'uniform mat4 Pmatrix;'+
'uniform mat4 Vmatrix;'+
'uniform mat4 Mmatrix;'+
'attribute vec3 color;'+//the color of the point
'varying vec3 vColor;'+
'void main(void) { '+//pre-built function
'gl_Position = Pmatrix*Vmatrix*Mmatrix*vec4(position, 1.);'+
'vColor = color;'+
'}';
var fragCode = 'precision mediump float;'+
'varying vec3 vColor;'+
'void main(void) {'+
'gl_FragColor = vec4(vColor, 1.);'+
'}';
var vertShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertShader, vertCode);
gl.compileShader(vertShader);
var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragShader, fragCode);
gl.compileShader(fragShader);
var shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertShader);
gl.attachShader(shaderProgram, fragShader);
gl.linkProgram(shaderProgram);
/*===========associating attributes to vertex shader ============*/
var Pmatrix = gl.getUniformLocation(shaderProgram, "Pmatrix");
var Vmatrix = gl.getUniformLocation(shaderProgram, "Vmatrix");
var Mmatrix = gl.getUniformLocation(shaderProgram, "Mmatrix");
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
var position = gl.getAttribLocation(shaderProgram, "position");
gl.vertexAttribPointer(position, 3, gl.FLOAT, false,0,0) ; //position
gl.enableVertexAttribArray(position);
gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);
var color = gl.getAttribLocation(shaderProgram, "color");
gl.vertexAttribPointer(color, 3, gl.FLOAT, false,0,0) ; //color
gl.enableVertexAttribArray(color);
gl.useProgram(shaderProgram);
/*========================= MATRIX ========================= */
function get_projection(angle, a, zMin, zMax) {
var ang = Math.tan((angle*.5)*Math.PI/180);//angle*.5
return [
0.5/ang, 0 , 0, 0,
0, 0.5*a/ang, 0, 0,
0, 0, -(zMax+zMin)/(zMax-zMin), -1,
0, 0, (-2*zMax*zMin)/(zMax-zMin), 0
];
}
var proj_matrix = get_projection(40, canvas.width/canvas.height, 1, 100);
var mov_matrix = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1];
var view_matrix = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1];
//translating z
view_matrix[14] = view_matrix[14]-6; //zoom
/*=======================rotation========================*/
function rotateZ(m, angle) {
var c = Math.cos(angle);
var s = Math.sin(angle);
var mv0 = m[0], mv4 = m[4], mv8 = m[8];
m[0] = c*m[0]-s*m[1];
m[4] = c*m[4]-s*m[5];
m[8] = c*m[8]-s*m[9];
m[1] = c*m[1]+s*mv0;
m[5] = c*m[5]+s*mv4;
m[9] = c*m[9]+s*mv8;
}
/*=================Drawing===========================*/
var time_old = 0;
var animate = function(time) {
var dt = time-time_old;
rotateZ(mov_matrix, dt*0.002);
time_old = time;
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.clearColor(0.5, 0.5, 0.5, 0.9);
gl.clearDepth(1.0);
gl.viewport(0.0, 0.0, canvas.width, canvas.height);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.uniformMatrix4fv(Pmatrix, false, proj_matrix);
gl.uniformMatrix4fv(Vmatrix, false, view_matrix);
gl.uniformMatrix4fv(Mmatrix, false, mov_matrix);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);
gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);
window.requestAnimationFrame(animate);
}
animate(0);
</script>
</body>
</html>
If you run this example, it will produce the following output −
10 Lectures
1 hours
Frahaan Hussain
28 Lectures
4 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2141,
"s": 2047,
"text": "In this chapter, we will take an example to demonstrate how to rotate a triangle using WebGL."
},
{
"code": null,
"e": 2207,
"s": 2141,
"text": "The following program shows how to rotate a triangle using WebGL."
},
{
"code": null,
"e": 7626,
"s": 2207,
"text": "<!doctype html>\n<html>\n <body>\n <canvas width = \"400\" height = \"400\" id = \"my_Canvas\"></canvas>\n\n <script>\n /*=================Creating a canvas=========================*/\n var canvas = document.getElementById('my_Canvas');\n gl = canvas.getContext('experimental-webgl');\n\n /*===========Defining and storing the geometry==============*/\n\n var vertices = [ -1,-1,-1, 1,-1,-1, 1, 1,-1 ];\n var colors = [ 1,1,1, 1,1,1, 1,1,1 ];\n var indices = [ 0,1,2 ];\n\n //Create and store data into vertex buffer\n var vertex_buffer = gl.createBuffer ();\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);\n\n //Create and store data into color buffer\n var color_buffer = gl.createBuffer ();\n gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);\n\n //Create and store data into index buffer\n var index_buffer = gl.createBuffer ();\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);\n\n /*==========================Shaders=========================*/\n\n var vertCode = 'attribute vec3 position;'+\n 'uniform mat4 Pmatrix;'+\n 'uniform mat4 Vmatrix;'+\n 'uniform mat4 Mmatrix;'+\n 'attribute vec3 color;'+//the color of the point\n 'varying vec3 vColor;'+\n\n 'void main(void) { '+//pre-built function\n 'gl_Position = Pmatrix*Vmatrix*Mmatrix*vec4(position, 1.);'+\n 'vColor = color;'+\n '}';\n\n var fragCode = 'precision mediump float;'+\n 'varying vec3 vColor;'+\n 'void main(void) {'+\n 'gl_FragColor = vec4(vColor, 1.);'+\n '}';\n\n var vertShader = gl.createShader(gl.VERTEX_SHADER);\n gl.shaderSource(vertShader, vertCode);\n gl.compileShader(vertShader);\n\n var fragShader = gl.createShader(gl.FRAGMENT_SHADER);\n gl.shaderSource(fragShader, fragCode);\n gl.compileShader(fragShader);\n\n var shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertShader);\n gl.attachShader(shaderProgram, fragShader);\n gl.linkProgram(shaderProgram);\n\n /*===========associating attributes to vertex shader ============*/\n\n var Pmatrix = gl.getUniformLocation(shaderProgram, \"Pmatrix\");\n var Vmatrix = gl.getUniformLocation(shaderProgram, \"Vmatrix\");\n var Mmatrix = gl.getUniformLocation(shaderProgram, \"Mmatrix\");\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n\n var position = gl.getAttribLocation(shaderProgram, \"position\");\n gl.vertexAttribPointer(position, 3, gl.FLOAT, false,0,0) ; //position\n gl.enableVertexAttribArray(position);\n gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);\n\n var color = gl.getAttribLocation(shaderProgram, \"color\");\n gl.vertexAttribPointer(color, 3, gl.FLOAT, false,0,0) ; //color\n gl.enableVertexAttribArray(color);\n gl.useProgram(shaderProgram);\n\n /*========================= MATRIX ========================= */\n\n function get_projection(angle, a, zMin, zMax) {\n var ang = Math.tan((angle*.5)*Math.PI/180);//angle*.5\n return [\n 0.5/ang, 0 , 0, 0,\n 0, 0.5*a/ang, 0, 0,\n 0, 0, -(zMax+zMin)/(zMax-zMin), -1,\n 0, 0, (-2*zMax*zMin)/(zMax-zMin), 0\n ];\n }\n\n var proj_matrix = get_projection(40, canvas.width/canvas.height, 1, 100);\n var mov_matrix = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1];\n var view_matrix = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1];\n\n //translating z\n view_matrix[14] = view_matrix[14]-6; //zoom\n\n /*=======================rotation========================*/\n function rotateZ(m, angle) {\n var c = Math.cos(angle);\n var s = Math.sin(angle);\n var mv0 = m[0], mv4 = m[4], mv8 = m[8]; \n\n m[0] = c*m[0]-s*m[1];\n m[4] = c*m[4]-s*m[5];\n m[8] = c*m[8]-s*m[9];\n m[1] = c*m[1]+s*mv0;\n m[5] = c*m[5]+s*mv4;\n m[9] = c*m[9]+s*mv8;\n }\n\n /*=================Drawing===========================*/\n\n var time_old = 0;\n var animate = function(time) {\n var dt = time-time_old;\n rotateZ(mov_matrix, dt*0.002);\n time_old = time;\n\n gl.enable(gl.DEPTH_TEST);\n gl.depthFunc(gl.LEQUAL);\n gl.clearColor(0.5, 0.5, 0.5, 0.9);\n gl.clearDepth(1.0);\n gl.viewport(0.0, 0.0, canvas.width, canvas.height);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n\n gl.uniformMatrix4fv(Pmatrix, false, proj_matrix);\n gl.uniformMatrix4fv(Vmatrix, false, view_matrix);\n gl.uniformMatrix4fv(Mmatrix, false, mov_matrix);\n\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);\n gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);\n window.requestAnimationFrame(animate);\n }\n animate(0);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 7690,
"s": 7626,
"text": "If you run this example, it will produce the following output −"
},
{
"code": null,
"e": 7723,
"s": 7690,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7740,
"s": 7723,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7773,
"s": 7740,
"text": "\n 28 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7790,
"s": 7773,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7797,
"s": 7790,
"text": " Print"
},
{
"code": null,
"e": 7808,
"s": 7797,
"text": " Add Notes"
}
] |
How to declare Java array with array size dynamically? | To declare array size dynamically read the required integer value from the user using Scanner class and create an array using the given value:
import java.util.Arrays;
import java.util.Scanner;
public class PopulatingAnArray {
public static void main(String args[]) {
System.out.println("Enter the required size of the array :: ");
Scanner s = new Scanner(System.in);
int size = s.nextInt();
int myArray[] = new int [size];
System.out.println("Enter the elements of the array one by one ");
for(int i = 0; i<size; i++) {
myArray[i] = s.nextInt();
}
System.out.println("Contents of the array are: "+Arrays.toString(myArray));
}
}
Enter the required size of the array ::
5
Enter the elements of the array one by one
78
96
45
23
45
Contents of the array are: [78, 96, 45, 23, 45] | [
{
"code": null,
"e": 1205,
"s": 1062,
"text": "To declare array size dynamically read the required integer value from the user using Scanner class and create an array using the given value:"
},
{
"code": null,
"e": 1759,
"s": 1205,
"text": "import java.util.Arrays;\nimport java.util.Scanner;\n\npublic class PopulatingAnArray {\n public static void main(String args[]) {\n System.out.println(\"Enter the required size of the array :: \");\n Scanner s = new Scanner(System.in);\n int size = s.nextInt();\n int myArray[] = new int [size];\n System.out.println(\"Enter the elements of the array one by one \");\n \n for(int i = 0; i<size; i++) {\n myArray[i] = s.nextInt();\n }\n System.out.println(\"Contents of the array are: \"+Arrays.toString(myArray));\n }\n}"
},
{
"code": null,
"e": 1907,
"s": 1759,
"text": "Enter the required size of the array ::\n5\nEnter the elements of the array one by one\n78\n96\n45\n23\n45\nContents of the array are: [78, 96, 45, 23, 45]"
}
] |
How to input multiple values from user in one line in Python? | To read multiple variables in language C, we write something like −
//Read three variable in one line
scanf(“%d %d %d”, &x, &y, &z)
Currently python does not have an equivalent to scanf(). However, python provides regular expressions which are more powerful and verbose than scanf() format strings. In Python, to provide multiple values from user, we can use −
input() method: where the user can enter multiple values in one line, like −
>>> x, y, z = input(), input(), input()
40
30
10
>>> x
'40'
>>> y
'30'
>>> z
'10'
From above output, you can see, we are able to give values to three variables in one line.
To avoid using multiple input() methods(depends on how many values we are passing), we can use the list comprehension or map() function.
>>> x,y,z = [int(x) for x in input().split()]
9 12 15
>>> x
9
>>> y
12
>>> z
15
In above line of code, i have typecast the input values to integers. In case you don’t want that & your inputs are of mixed type, you can simply type −
>>> x,y,z = [x for x in input().split()]
40 10 "hello"
Another way to pass multiple values from user is to use map function.
>>> x,y,z = map(int, input().split())
40 54 90
>>> x
40
>>> y
54
>>> z
90 | [
{
"code": null,
"e": 1130,
"s": 1062,
"text": "To read multiple variables in language C, we write something like −"
},
{
"code": null,
"e": 1194,
"s": 1130,
"text": "//Read three variable in one line\nscanf(“%d %d %d”, &x, &y, &z)"
},
{
"code": null,
"e": 1423,
"s": 1194,
"text": "Currently python does not have an equivalent to scanf(). However, python provides regular expressions which are more powerful and verbose than scanf() format strings. In Python, to provide multiple values from user, we can use −"
},
{
"code": null,
"e": 1500,
"s": 1423,
"text": "input() method: where the user can enter multiple values in one line, like −"
},
{
"code": null,
"e": 1582,
"s": 1500,
"text": ">>> x, y, z = input(), input(), input()\n40\n30\n10\n>>> x\n'40'\n>>> y\n'30'\n>>> z\n'10'"
},
{
"code": null,
"e": 1673,
"s": 1582,
"text": "From above output, you can see, we are able to give values to three variables in one line."
},
{
"code": null,
"e": 1810,
"s": 1673,
"text": "To avoid using multiple input() methods(depends on how many values we are passing), we can use the list comprehension or map() function."
},
{
"code": null,
"e": 1890,
"s": 1810,
"text": ">>> x,y,z = [int(x) for x in input().split()]\n9 12 15\n>>> x\n9\n>>> y\n12\n>>> z\n15"
},
{
"code": null,
"e": 2042,
"s": 1890,
"text": "In above line of code, i have typecast the input values to integers. In case you don’t want that & your inputs are of mixed type, you can simply type −"
},
{
"code": null,
"e": 2097,
"s": 2042,
"text": ">>> x,y,z = [x for x in input().split()]\n40 10 \"hello\""
},
{
"code": null,
"e": 2167,
"s": 2097,
"text": "Another way to pass multiple values from user is to use map function."
},
{
"code": null,
"e": 2241,
"s": 2167,
"text": ">>> x,y,z = map(int, input().split())\n40 54 90\n>>> x\n40\n>>> y\n54\n>>> z\n90"
}
] |
A step-by-step introduction to Cohort Analysis in Python | by Eryk Lewinson | Towards Data Science | Cohort Analysis is a very useful and relatively simple technique that helps in getting valuable insights about the behavior of any business’ customers/users. For the analysis, we can focus on different metrics (dependent on the business model) — conversion, retention, generated revenue, etc.
In this article, I provide a brief theoretical introduction into the Cohort Analysis and show how to carry it out in Python.
Let’s start with the basics. A cohort is a group of people sharing something in common, such as the sign-up date to an app, the month of the first purchase, geographical location, acquisition channel (organic users, coming from performance marketing, etc.) and so on. In Cohort Analysis, we track these groups of users over time, to identify some common patterns or behaviors.
When carrying out the cohort analysis, it is crucial to consider the relationship between the metric we are tracking and the business model. Depending on the company’s goals, we can focus on user retention, conversion ratio (signing up to the paid version of the service), generated revenue, etc.
In this article, I cover the case of user retention. By understanding user retention, we can infer the stickiness/loyalty of the customers and evaluate the health of the business. It is important to remember that the expected retention values vary greatly between businesses, 3 purchases a year for one retailer might be a lot, while for another might be far too little.
Retaining customers is critical for any business, as it is far cheaper to keep the current customers (by using CRM tools, member discounts, etc.) than to acquire new ones.
Furthermore, cohort analysis can also help to observe the impact of changes to the product on the user behavior, be it design changes or entirely new features. By seeing how the groups behave over time, we can more or less observe if our efforts had some effects on the users.
This should be enough of theory for now, let’s move to the real-life example.
In this article, we will be using the following libraries:
We will use a dataset downloaded from the UCI Machine Learning Repository, which is a great source for different kinds of datasets. They are already labeled according to the area of machine learning which they can be used for:
supervised (regression/classification),
unsupervised (clustering).
You can find the dataset here. Alternatively, you can download the data directly from the Jupyter Notebook using the following line:
!wget https://archive.ics.uci.edu/ml/machine-learning-databases/00352/Online%20Retail.xlsx
The dataset can be briefly described as: “This is a transnational data set which contains all the transactions occurring between 01/12/2010 and 09/12/2011 for a UK-based and registered non-store online retail. The company mainly sells unique all-occasion gifts. Many customers of the company are wholesalers.”
Next, we load the data from the Excel file.
The loaded data looks as follows:
We also inspected the DataFrame using df.info() to see if there are missing values. As for the analysis, due to the fact that we need to have the customer IDs, we dropped all the rows without them.
df.dropna(subset=['CustomerID'], inplace=True)
For completeness’ sake, we also do a very quick EDA, with a focus on the users. EDA is always a very important step of any analysis, as we discover the specifics of the dataset we are working with.
We start by inspecting the distribution of the numeric variables — quantity and unit price.
df.describe().transpose()
From the table above, we can see that there are orders with negative quantity — most likely returns. In total, there are around 9 thousand purchases with a negative quantity. We remove them from the dataset. This introduces a kind of bias, as we include the initial orders and remove the return — this way the initial order is taken into account even though in theory it was not realized and did not generate revenue. However, for simplicity, we leave the initial order, as for metric such as retention (indicating the customers’ engagement) this should still be a valid assumption.
Then, we calculate an aggregate metric indicating how many orders were placed by each customer.
Using the code above, we can state that 65.57% of customers ordered more than once. This is already a valuable piece of information, as is seems that the customers are placing multiple orders. This means that there will be at least some retention. Given that the dataset has no sign-up/joined date, it would be problematic if the majority of the users only placed one order, but we will get back to it later.
Additionally, we look at the distribution of the number of orders per customer. For that, we can reuse the previously aggregated data (n_orders) and plot the data on a histogram.
Running the code generates the following plot:
There are some infrequent cases of customers, who ordered more than 50 times.
The dataset we are using for this example does not contain the customer sign-up date — the date when they registered with the retailer. That is why we assume that the cohort they belong to is based on the first purchase date. A possible downside of this approach is that the dataset does not contain the past data, and what we already see in this snapshot (between 01/12/2010 and 09/12/2011) includes recurring clients. In other words, the first purchase we see in this dataset might not be the actual first purchase of a given client. However, there is no way to account for this without having access to the entire historical dataset of the retailer.
As the first step, we keep only the relevant columns and drop duplicated values — one order (indicated by InvoiceNo) can contain multiple items (indicated by StockCode).
As the second step, we create the cohort and order_month variables. The first one indicates the monthly cohort based on the first purchase date (calculated per customer). The latter one is the truncated month of the purchase date.
Then, we aggregate the data per cohort and order_month and count the number of unique customers in each group. Additionally, we add the period_number, which indicates the number of periods between the cohort month and the month of the purchase.
The next step is to pivot the df_cohort table in a way that each row contains information about a given cohort and each column contains values for a certain period.
To obtain the retention matrix, we need to divide the values each row by the row's first value, which is actually the cohort size — all customers who made their first purchase in the given month.
Lastly, we plot the retention matrix as a heatmap. Additionally, we wanted to include extra information regarding the cohort size. That is why we in fact created two heatmaps, where the one indicating the cohort size is using a white only colormap — no coloring at all.
The end result is the following retention matrix:
In the image, we can see that there is a sharp drop-off in the second month (indexed as 1) already, on average around 80% of customers do not make any purchase in the second month. The first cohort (2010–12) seems to be an exception and performs surprisingly well as compared to the other ones. A year after the first purchase, there is a 50% retention. This might be a cohort of dedicated customers, who first joined the platform based on some already-existing connections with the retailer. However, from data alone, that is very hard to accurately explain.
Throughout the matrix, we can see fluctuations in retention over time. This might be caused by the characteristics of the business, where clients do periodic purchases, followed by periods of inactivity.
In this article, I showed how to carry out Cohort Analysis using Python’s pandas and seaborn. On the way, I have made some simplifying assumptions, but that was mostly due to the nature of the dataset. While working on a real-life scenario for a company, we would have more understanding of the business and could draw better and more meaningful conclusions from the analysis.
You can find the code used for this article on my GitHub. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments.
Liked the article? Become a Medium member to continue learning by reading without limits. If you use this link to become a member, you will support me at no extra cost to you. Thanks in advance and see you around!
I recently published a book on using Python for solving practical tasks in the financial domain. If you are interested, I posted an article introducing the contents of the book. You can get the book on Amazon or Packt’s website. | [
{
"code": null,
"e": 465,
"s": 172,
"text": "Cohort Analysis is a very useful and relatively simple technique that helps in getting valuable insights about the behavior of any business’ customers/users. For the analysis, we can focus on different metrics (dependent on the business model) — conversion, retention, generated revenue, etc."
},
{
"code": null,
"e": 590,
"s": 465,
"text": "In this article, I provide a brief theoretical introduction into the Cohort Analysis and show how to carry it out in Python."
},
{
"code": null,
"e": 967,
"s": 590,
"text": "Let’s start with the basics. A cohort is a group of people sharing something in common, such as the sign-up date to an app, the month of the first purchase, geographical location, acquisition channel (organic users, coming from performance marketing, etc.) and so on. In Cohort Analysis, we track these groups of users over time, to identify some common patterns or behaviors."
},
{
"code": null,
"e": 1264,
"s": 967,
"text": "When carrying out the cohort analysis, it is crucial to consider the relationship between the metric we are tracking and the business model. Depending on the company’s goals, we can focus on user retention, conversion ratio (signing up to the paid version of the service), generated revenue, etc."
},
{
"code": null,
"e": 1635,
"s": 1264,
"text": "In this article, I cover the case of user retention. By understanding user retention, we can infer the stickiness/loyalty of the customers and evaluate the health of the business. It is important to remember that the expected retention values vary greatly between businesses, 3 purchases a year for one retailer might be a lot, while for another might be far too little."
},
{
"code": null,
"e": 1807,
"s": 1635,
"text": "Retaining customers is critical for any business, as it is far cheaper to keep the current customers (by using CRM tools, member discounts, etc.) than to acquire new ones."
},
{
"code": null,
"e": 2084,
"s": 1807,
"text": "Furthermore, cohort analysis can also help to observe the impact of changes to the product on the user behavior, be it design changes or entirely new features. By seeing how the groups behave over time, we can more or less observe if our efforts had some effects on the users."
},
{
"code": null,
"e": 2162,
"s": 2084,
"text": "This should be enough of theory for now, let’s move to the real-life example."
},
{
"code": null,
"e": 2221,
"s": 2162,
"text": "In this article, we will be using the following libraries:"
},
{
"code": null,
"e": 2448,
"s": 2221,
"text": "We will use a dataset downloaded from the UCI Machine Learning Repository, which is a great source for different kinds of datasets. They are already labeled according to the area of machine learning which they can be used for:"
},
{
"code": null,
"e": 2488,
"s": 2448,
"text": "supervised (regression/classification),"
},
{
"code": null,
"e": 2515,
"s": 2488,
"text": "unsupervised (clustering)."
},
{
"code": null,
"e": 2648,
"s": 2515,
"text": "You can find the dataset here. Alternatively, you can download the data directly from the Jupyter Notebook using the following line:"
},
{
"code": null,
"e": 2739,
"s": 2648,
"text": "!wget https://archive.ics.uci.edu/ml/machine-learning-databases/00352/Online%20Retail.xlsx"
},
{
"code": null,
"e": 3049,
"s": 2739,
"text": "The dataset can be briefly described as: “This is a transnational data set which contains all the transactions occurring between 01/12/2010 and 09/12/2011 for a UK-based and registered non-store online retail. The company mainly sells unique all-occasion gifts. Many customers of the company are wholesalers.”"
},
{
"code": null,
"e": 3093,
"s": 3049,
"text": "Next, we load the data from the Excel file."
},
{
"code": null,
"e": 3127,
"s": 3093,
"text": "The loaded data looks as follows:"
},
{
"code": null,
"e": 3325,
"s": 3127,
"text": "We also inspected the DataFrame using df.info() to see if there are missing values. As for the analysis, due to the fact that we need to have the customer IDs, we dropped all the rows without them."
},
{
"code": null,
"e": 3372,
"s": 3325,
"text": "df.dropna(subset=['CustomerID'], inplace=True)"
},
{
"code": null,
"e": 3570,
"s": 3372,
"text": "For completeness’ sake, we also do a very quick EDA, with a focus on the users. EDA is always a very important step of any analysis, as we discover the specifics of the dataset we are working with."
},
{
"code": null,
"e": 3662,
"s": 3570,
"text": "We start by inspecting the distribution of the numeric variables — quantity and unit price."
},
{
"code": null,
"e": 3688,
"s": 3662,
"text": "df.describe().transpose()"
},
{
"code": null,
"e": 4271,
"s": 3688,
"text": "From the table above, we can see that there are orders with negative quantity — most likely returns. In total, there are around 9 thousand purchases with a negative quantity. We remove them from the dataset. This introduces a kind of bias, as we include the initial orders and remove the return — this way the initial order is taken into account even though in theory it was not realized and did not generate revenue. However, for simplicity, we leave the initial order, as for metric such as retention (indicating the customers’ engagement) this should still be a valid assumption."
},
{
"code": null,
"e": 4367,
"s": 4271,
"text": "Then, we calculate an aggregate metric indicating how many orders were placed by each customer."
},
{
"code": null,
"e": 4776,
"s": 4367,
"text": "Using the code above, we can state that 65.57% of customers ordered more than once. This is already a valuable piece of information, as is seems that the customers are placing multiple orders. This means that there will be at least some retention. Given that the dataset has no sign-up/joined date, it would be problematic if the majority of the users only placed one order, but we will get back to it later."
},
{
"code": null,
"e": 4955,
"s": 4776,
"text": "Additionally, we look at the distribution of the number of orders per customer. For that, we can reuse the previously aggregated data (n_orders) and plot the data on a histogram."
},
{
"code": null,
"e": 5002,
"s": 4955,
"text": "Running the code generates the following plot:"
},
{
"code": null,
"e": 5080,
"s": 5002,
"text": "There are some infrequent cases of customers, who ordered more than 50 times."
},
{
"code": null,
"e": 5733,
"s": 5080,
"text": "The dataset we are using for this example does not contain the customer sign-up date — the date when they registered with the retailer. That is why we assume that the cohort they belong to is based on the first purchase date. A possible downside of this approach is that the dataset does not contain the past data, and what we already see in this snapshot (between 01/12/2010 and 09/12/2011) includes recurring clients. In other words, the first purchase we see in this dataset might not be the actual first purchase of a given client. However, there is no way to account for this without having access to the entire historical dataset of the retailer."
},
{
"code": null,
"e": 5903,
"s": 5733,
"text": "As the first step, we keep only the relevant columns and drop duplicated values — one order (indicated by InvoiceNo) can contain multiple items (indicated by StockCode)."
},
{
"code": null,
"e": 6134,
"s": 5903,
"text": "As the second step, we create the cohort and order_month variables. The first one indicates the monthly cohort based on the first purchase date (calculated per customer). The latter one is the truncated month of the purchase date."
},
{
"code": null,
"e": 6379,
"s": 6134,
"text": "Then, we aggregate the data per cohort and order_month and count the number of unique customers in each group. Additionally, we add the period_number, which indicates the number of periods between the cohort month and the month of the purchase."
},
{
"code": null,
"e": 6544,
"s": 6379,
"text": "The next step is to pivot the df_cohort table in a way that each row contains information about a given cohort and each column contains values for a certain period."
},
{
"code": null,
"e": 6740,
"s": 6544,
"text": "To obtain the retention matrix, we need to divide the values each row by the row's first value, which is actually the cohort size — all customers who made their first purchase in the given month."
},
{
"code": null,
"e": 7010,
"s": 6740,
"text": "Lastly, we plot the retention matrix as a heatmap. Additionally, we wanted to include extra information regarding the cohort size. That is why we in fact created two heatmaps, where the one indicating the cohort size is using a white only colormap — no coloring at all."
},
{
"code": null,
"e": 7060,
"s": 7010,
"text": "The end result is the following retention matrix:"
},
{
"code": null,
"e": 7620,
"s": 7060,
"text": "In the image, we can see that there is a sharp drop-off in the second month (indexed as 1) already, on average around 80% of customers do not make any purchase in the second month. The first cohort (2010–12) seems to be an exception and performs surprisingly well as compared to the other ones. A year after the first purchase, there is a 50% retention. This might be a cohort of dedicated customers, who first joined the platform based on some already-existing connections with the retailer. However, from data alone, that is very hard to accurately explain."
},
{
"code": null,
"e": 7824,
"s": 7620,
"text": "Throughout the matrix, we can see fluctuations in retention over time. This might be caused by the characteristics of the business, where clients do periodic purchases, followed by periods of inactivity."
},
{
"code": null,
"e": 8201,
"s": 7824,
"text": "In this article, I showed how to carry out Cohort Analysis using Python’s pandas and seaborn. On the way, I have made some simplifying assumptions, but that was mostly due to the nature of the dataset. While working on a real-life scenario for a company, we would have more understanding of the business and could draw better and more meaningful conclusions from the analysis."
},
{
"code": null,
"e": 8363,
"s": 8201,
"text": "You can find the code used for this article on my GitHub. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments."
},
{
"code": null,
"e": 8577,
"s": 8363,
"text": "Liked the article? Become a Medium member to continue learning by reading without limits. If you use this link to become a member, you will support me at no extra cost to you. Thanks in advance and see you around!"
}
] |
Count occurrences of a substring recursively in Java | Given two strings str_1 and str_2. The goal is to count the number of occurrences of substring str2 in string str1 using a recursive process.
A recursive function is the one which has its own call inside it’s definition.
If str1 is “I know that you know that i know” str2=”know”
Count of occurences is − 3
Let us understand with examples.
For Example
str1 = "TPisTPareTPamTP", str2 = "TP";
Count of occurrences of a substring recursively are: 4
The substring TP occurs 4 times in str1.
str1 = "HiHOwAReyouHiHi" str2 = "Hi"
Count of occurrences of a substring recursively are: 3
The substring Hi occurs 3 times in str1.
Approach used in the below program is as follows −
In this approach we will search for occurrence of str2 in str1 using contains() method in java. It will return true if str2 exists in str1. In case true, remove that first occurrence from str1 by replacing it with “” using replaceFirst() method in java and add 1 to return value to increase count.
Take two strings as str1 and str2.
Take two strings as str1 and str2.
Recursive Method subsrting_rec(String str, String sub) takes string str and its substring sub and returns the count of occurrences of sub in str.
Recursive Method subsrting_rec(String str, String sub) takes string str and its substring sub and returns the count of occurrences of sub in str.
Check whether str.contains(sub) is true. ( str has sub )
Check whether str.contains(sub) is true. ( str has sub )
If true then replace the first occurrence of sub with “” using str.replaceFirst(sub,””).
If true then replace the first occurrence of sub with “” using str.replaceFirst(sub,””).
Do this inside a recursive call to subsrting_rec(String str, String sub).
Do this inside a recursive call to subsrting_rec(String str, String sub).
At the end of all recursions the sum of all return values is count.
At the end of all recursions the sum of all return values is count.
Print the result.
Print the result.
Live Demo
public class recursive{
public static void main(String args[]){
String str1 = "TPisTPareTPamTP", str2 = "TP";
System.out.println("Count of occurrences of a substring recursively are: "+subsrting_rec(str1, str2));
}
static int subsrting_rec(String str, String sub){
if (str.contains(sub)){
return 1 + subsrting_rec(str.replaceFirst(sub, ""), sub);
}
return 0;
}
}
If we run the above code it will generate the following output −
Count of occurrences of a substring recursively are: 4 | [
{
"code": null,
"e": 1204,
"s": 1062,
"text": "Given two strings str_1 and str_2. The goal is to count the number of occurrences of substring str2 in string str1 using a recursive process."
},
{
"code": null,
"e": 1283,
"s": 1204,
"text": "A recursive function is the one which has its own call inside it’s definition."
},
{
"code": null,
"e": 1341,
"s": 1283,
"text": "If str1 is “I know that you know that i know” str2=”know”"
},
{
"code": null,
"e": 1368,
"s": 1341,
"text": "Count of occurences is − 3"
},
{
"code": null,
"e": 1401,
"s": 1368,
"text": "Let us understand with examples."
},
{
"code": null,
"e": 1413,
"s": 1401,
"text": "For Example"
},
{
"code": null,
"e": 1452,
"s": 1413,
"text": "str1 = \"TPisTPareTPamTP\", str2 = \"TP\";"
},
{
"code": null,
"e": 1507,
"s": 1452,
"text": "Count of occurrences of a substring recursively are: 4"
},
{
"code": null,
"e": 1548,
"s": 1507,
"text": "The substring TP occurs 4 times in str1."
},
{
"code": null,
"e": 1585,
"s": 1548,
"text": "str1 = \"HiHOwAReyouHiHi\" str2 = \"Hi\""
},
{
"code": null,
"e": 1640,
"s": 1585,
"text": "Count of occurrences of a substring recursively are: 3"
},
{
"code": null,
"e": 1681,
"s": 1640,
"text": "The substring Hi occurs 3 times in str1."
},
{
"code": null,
"e": 1732,
"s": 1681,
"text": "Approach used in the below program is as follows −"
},
{
"code": null,
"e": 2030,
"s": 1732,
"text": "In this approach we will search for occurrence of str2 in str1 using contains() method in java. It will return true if str2 exists in str1. In case true, remove that first occurrence from str1 by replacing it with “” using replaceFirst() method in java and add 1 to return value to increase count."
},
{
"code": null,
"e": 2065,
"s": 2030,
"text": "Take two strings as str1 and str2."
},
{
"code": null,
"e": 2100,
"s": 2065,
"text": "Take two strings as str1 and str2."
},
{
"code": null,
"e": 2246,
"s": 2100,
"text": "Recursive Method subsrting_rec(String str, String sub) takes string str and its substring sub and returns the count of occurrences of sub in str."
},
{
"code": null,
"e": 2392,
"s": 2246,
"text": "Recursive Method subsrting_rec(String str, String sub) takes string str and its substring sub and returns the count of occurrences of sub in str."
},
{
"code": null,
"e": 2449,
"s": 2392,
"text": "Check whether str.contains(sub) is true. ( str has sub )"
},
{
"code": null,
"e": 2506,
"s": 2449,
"text": "Check whether str.contains(sub) is true. ( str has sub )"
},
{
"code": null,
"e": 2595,
"s": 2506,
"text": "If true then replace the first occurrence of sub with “” using str.replaceFirst(sub,””)."
},
{
"code": null,
"e": 2684,
"s": 2595,
"text": "If true then replace the first occurrence of sub with “” using str.replaceFirst(sub,””)."
},
{
"code": null,
"e": 2758,
"s": 2684,
"text": "Do this inside a recursive call to subsrting_rec(String str, String sub)."
},
{
"code": null,
"e": 2832,
"s": 2758,
"text": "Do this inside a recursive call to subsrting_rec(String str, String sub)."
},
{
"code": null,
"e": 2900,
"s": 2832,
"text": "At the end of all recursions the sum of all return values is count."
},
{
"code": null,
"e": 2968,
"s": 2900,
"text": "At the end of all recursions the sum of all return values is count."
},
{
"code": null,
"e": 2986,
"s": 2968,
"text": "Print the result."
},
{
"code": null,
"e": 3004,
"s": 2986,
"text": "Print the result."
},
{
"code": null,
"e": 3015,
"s": 3004,
"text": " Live Demo"
},
{
"code": null,
"e": 3429,
"s": 3015,
"text": "public class recursive{\n public static void main(String args[]){\n String str1 = \"TPisTPareTPamTP\", str2 = \"TP\";\n System.out.println(\"Count of occurrences of a substring recursively are: \"+subsrting_rec(str1, str2));\n }\n static int subsrting_rec(String str, String sub){\n if (str.contains(sub)){\n return 1 + subsrting_rec(str.replaceFirst(sub, \"\"), sub);\n }\n return 0;\n }\n}"
},
{
"code": null,
"e": 3494,
"s": 3429,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 3549,
"s": 3494,
"text": "Count of occurrences of a substring recursively are: 4"
}
] |
Pull to Refresh with RecyclerView in Android with Example - GeeksforGeeks | 01 Oct, 2021
The SwipeRefreshLayout widget is used for implementing a swipe-to-refresh user interface design pattern. Where the user uses the vertical swipe gesture to refresh the content of the views. The vertical swipe is detected by the SwipeRefreshLayout widget and it displays a distinct progress bar and triggers the callback methods in the app. In order to use this behavior, we need to use the SwipeRefreshLayout widget as the parent of a ListView or GridView. These Material Design UI Patterns are seen in applications like Gmail, Youtube, Facebook, Instagram, etc. It allows the user to refresh the application manually. SwipeRefreshLayout class contains a listener called OnRefreshListener. The classes which want to use this listener should implement SwipeRefreshLayout.OnRefreshListener interface. On vertical swipe-down gesture, this listener is triggered and onRefresh() method is called and can be overridden according to the needs.
In this example, we would store data into the ArrayList which is used for populating the RecyclerView. Whenever onRefresh() method is called the ArrayList data gets rearranged. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Adding dependencies
We are going to use RecyclerView and SwipeRefreshLayout. So, we need to add dependencies for them. For adding these dependencies Go to Gradle Scripts > build.gradle(Module: app) and add the following dependencies. After adding these dependencies you need to click on Sync Now.
dependencies {
implementation “androidx.recyclerview:recyclerview:1.1.0”
implementation “androidx.swiperefreshlayout:swiperefreshlayout:1.1.0”
}
Before moving further let’s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes.
XML
<resources> <color name="colorPrimary">#0F9D58</color> <color name="colorPrimaryDark">#16E37F</color> <color name="colorAccent">#03DAC5</color></resources>
Step 3: Working with the activity_main.xml file
In this step, we will create SwipeRefreshLayout and Add RecyclerView to it. Go to app > res > layout > activity_main.xml and add the following code snippet.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.swiperefreshlayout.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/swipeRefreshLayout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" /> </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
Step 4: Create a new layout file list_item.xml for the list items of RecyclerView.
Go to the app > res > layout > right-click > New > Layout Resource File and name it as list_item. list_item.xml layout file contains an ImageView and a TextView which is used for populating the rows of RecyclerView.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:orientation="horizontal" android:padding="10dp"> <!--For image src we have used ic_launcher and for text "GeeksForGeeks they are used only for reference how it will looks"--> <ImageView android:id="@+id/imageView" android:layout_width="120dp" android:layout_height="120dp" android:scaleType="fitXY" android:src="@mipmap/ic_launcher" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:paddingStart="10dp" android:text="GeeksForGeeks" /> </LinearLayout>
Step 5: Creating Adapter class for RecyclerView
Now, we will create an Adapter.java class that will extend the RecyclerView.Adapter with ViewHolder. Go to the app > java > package > right-click and create a new java class and name it as Adapter. In Adapter class we will override the onCreateViewHolder() method which will inflate the list_item.xml layout and pass it to View Holder. Then onBindViewHolder() method where we set data to the Views with the help of View Holder. Below is the code snippet for Adapter.java class.
Java
import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import java.util.ArrayList; // Extends the Adapter class to RecyclerView.Adapter// and implement the unimplemented methodspublic class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> { ArrayList images, text; Context context; // Constructor for initialization public Adapter(Context context, ArrayList images, ArrayList text) { this.context = context; this.images = images; this.text = text; } @NonNull @Override public Adapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // Inflating the Layout(Instantiates list_item.xml layout file into View object) View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false); // Passing view to ViewHolder Adapter.ViewHolder viewHolder = new Adapter.ViewHolder(view); return viewHolder; } // Binding data to the into specified position @Override public void onBindViewHolder(@NonNull Adapter.ViewHolder holder, int position) { // TypeCast Object to int type int res = (int) images.get(position); holder.images.setImageResource(res); holder.text.setText((CharSequence) text.get(position)); } @Override public int getItemCount() { // Returns number of items currently available in Adapter return text.size(); } // Initializing the Views public class ViewHolder extends RecyclerView.ViewHolder { ImageView images; TextView text; public ViewHolder(View view) { super(view); images = (ImageView) view.findViewById(R.id.imageView); text = (TextView) view.findViewById(R.id.textView); } }}
Step 6: Working with MainActivity.java file
In MainActivity.java class we create two ArrayList for storing images and text. These images are placed in the drawable folder(app > res > drawable). You can use any images in place of this. And then we get the reference of SwipeRefreshLayout and RecyclerView and set the LayoutManager and Adapter to show items in RecyclerView and implement onRefreshListener. Below is the code for the MainActivity.java file.
Java
import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Random; public class MainActivity extends AppCompatActivity { SwipeRefreshLayout swipeRefreshLayout; RecyclerView recyclerView; // Using ArrayList to store images and text data ArrayList images = new ArrayList<>(Arrays.asList(R.drawable.facebook, R.drawable.twitter, R.drawable.instagram, R.drawable.linkedin, R.drawable.youtube, R.drawable.whatsapp)); ArrayList text = new ArrayList<>(Arrays.asList("Facebook", "Twitter", "Instagram", "LinkedIn", "Youtube", "Whatsapp")); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Getting reference of swipeRefreshLayout and recyclerView swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout); recyclerView = (RecyclerView) findViewById(R.id.recyclerView); // Setting the layout as Linear for vertical orientation to have swipe behavior LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(linearLayoutManager); // Sending reference and data to Adapter Adapter adapter = new Adapter(MainActivity.this, images, text); // Setting Adapter to RecyclerView recyclerView.setAdapter(adapter); // SetOnRefreshListener on SwipeRefreshLayout swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { swipeRefreshLayout.setRefreshing(false); RearrangeItems(); } }); } public void RearrangeItems() { // Shuffling the data of ArrayList using system time Collections.shuffle(images, new Random(System.currentTimeMillis())); Collections.shuffle(text, new Random(System.currentTimeMillis())); Adapter adapter = new Adapter(MainActivity.this, images, text); recyclerView.setAdapter(adapter); }}
Media error: Format(s) not supported or source(s) not found
sweetyty
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Broadcast Receiver in Android With Example
How to Create and Add Data to SQLite Database in Android?
Content Providers in Android with Example
Android RecyclerView in Kotlin
Navigation Drawer in Android
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java | [
{
"code": null,
"e": 25038,
"s": 25010,
"text": "\n01 Oct, 2021"
},
{
"code": null,
"e": 25975,
"s": 25038,
"text": "The SwipeRefreshLayout widget is used for implementing a swipe-to-refresh user interface design pattern. Where the user uses the vertical swipe gesture to refresh the content of the views. The vertical swipe is detected by the SwipeRefreshLayout widget and it displays a distinct progress bar and triggers the callback methods in the app. In order to use this behavior, we need to use the SwipeRefreshLayout widget as the parent of a ListView or GridView. These Material Design UI Patterns are seen in applications like Gmail, Youtube, Facebook, Instagram, etc. It allows the user to refresh the application manually. SwipeRefreshLayout class contains a listener called OnRefreshListener. The classes which want to use this listener should implement SwipeRefreshLayout.OnRefreshListener interface. On vertical swipe-down gesture, this listener is triggered and onRefresh() method is called and can be overridden according to the needs. "
},
{
"code": null,
"e": 26317,
"s": 25975,
"text": "In this example, we would store data into the ArrayList which is used for populating the RecyclerView. Whenever onRefresh() method is called the ArrayList data gets rearranged. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 26346,
"s": 26317,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 26508,
"s": 26346,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 26536,
"s": 26508,
"text": "Step 2: Adding dependencies"
},
{
"code": null,
"e": 26813,
"s": 26536,
"text": "We are going to use RecyclerView and SwipeRefreshLayout. So, we need to add dependencies for them. For adding these dependencies Go to Gradle Scripts > build.gradle(Module: app) and add the following dependencies. After adding these dependencies you need to click on Sync Now."
},
{
"code": null,
"e": 26828,
"s": 26813,
"text": "dependencies {"
},
{
"code": null,
"e": 26889,
"s": 26828,
"text": " implementation “androidx.recyclerview:recyclerview:1.1.0”"
},
{
"code": null,
"e": 26962,
"s": 26889,
"text": " implementation “androidx.swiperefreshlayout:swiperefreshlayout:1.1.0”"
},
{
"code": null,
"e": 26964,
"s": 26962,
"text": "}"
},
{
"code": null,
"e": 27130,
"s": 26964,
"text": "Before moving further let’s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes. "
},
{
"code": null,
"e": 27134,
"s": 27130,
"text": "XML"
},
{
"code": "<resources> <color name=\"colorPrimary\">#0F9D58</color> <color name=\"colorPrimaryDark\">#16E37F</color> <color name=\"colorAccent\">#03DAC5</color></resources>",
"e": 27299,
"s": 27134,
"text": null
},
{
"code": null,
"e": 27347,
"s": 27299,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 27504,
"s": 27347,
"text": "In this step, we will create SwipeRefreshLayout and Add RecyclerView to it. Go to app > res > layout > activity_main.xml and add the following code snippet."
},
{
"code": null,
"e": 27508,
"s": 27504,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.swiperefreshlayout.widget.SwipeRefreshLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/swipeRefreshLayout\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/recyclerView\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /> </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>",
"e": 28099,
"s": 27508,
"text": null
},
{
"code": null,
"e": 28186,
"s": 28103,
"text": "Step 4: Create a new layout file list_item.xml for the list items of RecyclerView."
},
{
"code": null,
"e": 28404,
"s": 28188,
"text": "Go to the app > res > layout > right-click > New > Layout Resource File and name it as list_item. list_item.xml layout file contains an ImageView and a TextView which is used for populating the rows of RecyclerView."
},
{
"code": null,
"e": 28410,
"s": 28406,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:orientation=\"horizontal\" android:padding=\"10dp\"> <!--For image src we have used ic_launcher and for text \"GeeksForGeeks they are used only for reference how it will looks\"--> <ImageView android:id=\"@+id/imageView\" android:layout_width=\"120dp\" android:layout_height=\"120dp\" android:scaleType=\"fitXY\" android:src=\"@mipmap/ic_launcher\" /> <TextView android:id=\"@+id/textView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_vertical\" android:paddingStart=\"10dp\" android:text=\"GeeksForGeeks\" /> </LinearLayout>",
"e": 29314,
"s": 28410,
"text": null
},
{
"code": null,
"e": 29366,
"s": 29318,
"text": "Step 5: Creating Adapter class for RecyclerView"
},
{
"code": null,
"e": 29846,
"s": 29368,
"text": "Now, we will create an Adapter.java class that will extend the RecyclerView.Adapter with ViewHolder. Go to the app > java > package > right-click and create a new java class and name it as Adapter. In Adapter class we will override the onCreateViewHolder() method which will inflate the list_item.xml layout and pass it to View Holder. Then onBindViewHolder() method where we set data to the Views with the help of View Holder. Below is the code snippet for Adapter.java class."
},
{
"code": null,
"e": 29853,
"s": 29848,
"text": "Java"
},
{
"code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import java.util.ArrayList; // Extends the Adapter class to RecyclerView.Adapter// and implement the unimplemented methodspublic class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> { ArrayList images, text; Context context; // Constructor for initialization public Adapter(Context context, ArrayList images, ArrayList text) { this.context = context; this.images = images; this.text = text; } @NonNull @Override public Adapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // Inflating the Layout(Instantiates list_item.xml layout file into View object) View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false); // Passing view to ViewHolder Adapter.ViewHolder viewHolder = new Adapter.ViewHolder(view); return viewHolder; } // Binding data to the into specified position @Override public void onBindViewHolder(@NonNull Adapter.ViewHolder holder, int position) { // TypeCast Object to int type int res = (int) images.get(position); holder.images.setImageResource(res); holder.text.setText((CharSequence) text.get(position)); } @Override public int getItemCount() { // Returns number of items currently available in Adapter return text.size(); } // Initializing the Views public class ViewHolder extends RecyclerView.ViewHolder { ImageView images; TextView text; public ViewHolder(View view) { super(view); images = (ImageView) view.findViewById(R.id.imageView); text = (TextView) view.findViewById(R.id.textView); } }}",
"e": 31847,
"s": 29853,
"text": null
},
{
"code": null,
"e": 31895,
"s": 31851,
"text": "Step 6: Working with MainActivity.java file"
},
{
"code": null,
"e": 32308,
"s": 31897,
"text": "In MainActivity.java class we create two ArrayList for storing images and text. These images are placed in the drawable folder(app > res > drawable). You can use any images in place of this. And then we get the reference of SwipeRefreshLayout and RecyclerView and set the LayoutManager and Adapter to show items in RecyclerView and implement onRefreshListener. Below is the code for the MainActivity.java file."
},
{
"code": null,
"e": 32315,
"s": 32310,
"text": "Java"
},
{
"code": "import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Random; public class MainActivity extends AppCompatActivity { SwipeRefreshLayout swipeRefreshLayout; RecyclerView recyclerView; // Using ArrayList to store images and text data ArrayList images = new ArrayList<>(Arrays.asList(R.drawable.facebook, R.drawable.twitter, R.drawable.instagram, R.drawable.linkedin, R.drawable.youtube, R.drawable.whatsapp)); ArrayList text = new ArrayList<>(Arrays.asList(\"Facebook\", \"Twitter\", \"Instagram\", \"LinkedIn\", \"Youtube\", \"Whatsapp\")); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Getting reference of swipeRefreshLayout and recyclerView swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout); recyclerView = (RecyclerView) findViewById(R.id.recyclerView); // Setting the layout as Linear for vertical orientation to have swipe behavior LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(linearLayoutManager); // Sending reference and data to Adapter Adapter adapter = new Adapter(MainActivity.this, images, text); // Setting Adapter to RecyclerView recyclerView.setAdapter(adapter); // SetOnRefreshListener on SwipeRefreshLayout swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { swipeRefreshLayout.setRefreshing(false); RearrangeItems(); } }); } public void RearrangeItems() { // Shuffling the data of ArrayList using system time Collections.shuffle(images, new Random(System.currentTimeMillis())); Collections.shuffle(text, new Random(System.currentTimeMillis())); Adapter adapter = new Adapter(MainActivity.this, images, text); recyclerView.setAdapter(adapter); }}",
"e": 34716,
"s": 32315,
"text": null
},
{
"code": null,
"e": 34779,
"s": 34719,
"text": "Media error: Format(s) not supported or source(s) not found"
},
{
"code": null,
"e": 34790,
"s": 34781,
"text": "sweetyty"
},
{
"code": null,
"e": 34798,
"s": 34790,
"text": "android"
},
{
"code": null,
"e": 34822,
"s": 34798,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 34830,
"s": 34822,
"text": "Android"
},
{
"code": null,
"e": 34835,
"s": 34830,
"text": "Java"
},
{
"code": null,
"e": 34854,
"s": 34835,
"text": "Technical Scripter"
},
{
"code": null,
"e": 34859,
"s": 34854,
"text": "Java"
},
{
"code": null,
"e": 34867,
"s": 34859,
"text": "Android"
},
{
"code": null,
"e": 34965,
"s": 34867,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34974,
"s": 34965,
"text": "Comments"
},
{
"code": null,
"e": 34987,
"s": 34974,
"text": "Old Comments"
},
{
"code": null,
"e": 35030,
"s": 34987,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 35088,
"s": 35030,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 35130,
"s": 35088,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 35161,
"s": 35130,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 35190,
"s": 35161,
"text": "Navigation Drawer in Android"
},
{
"code": null,
"e": 35205,
"s": 35190,
"text": "Arrays in Java"
},
{
"code": null,
"e": 35249,
"s": 35205,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 35271,
"s": 35249,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 35307,
"s": 35271,
"text": "Arrays.sort() in Java with examples"
}
] |
D3.js selection.merge() Function - GeeksforGeeks | 23 Aug, 2020
The selection.merge() function in d3.js is used to merge the two given selections into one and return the new selection after merging them. The selection which is returned has the same number of groups and the same parents as this selection.
Syntax:
selection.merge(other);
Parameters: This function accepts single parameter other that describe selection is to be merged.
Return Values: This function returns a selection.
Example 1:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0"> <script src="https://d3js.org/d3.v4.min.js"> </script> <script src= "https://d3js.org/d3-selection.v1.min.js"> </script></head> <body> <div> <h3>1. This text is in bold</h3> <h3>2. This text is also in bold</h3> <h3>3. Geeks</h3> <h3>4. Geeks</h3> <h3>5. Geeks for geeks</h3> </div> <script> // Filtering odd children const odd = d3.selectAll("h3") .select(function (d, i) { return i & 1 ? this : null; }); // Filtering even children const even = d3.selectAll("h3") .select(function (d, i) { return i & 1 ? null : this; }); // Merging both selections const merged = odd.merge(even).nodes(); // Printing text content console.log("Collection after merging odd and even is:") merged.forEach((e) => { console.log(e.textContent); }); </script></body> </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0"> <script src="https://d3js.org/d3.v4.min.js"> </script> <script src= "https://d3js.org/d3-selection.v1.min.js"> </script></head> <body> <div> <h5>1. This is odd</h5> <h5>2. This is even</h5> <h5>3. This is odd</h5> <h5>4. This is even</h5> <h5>5. This is odd</h5> </div> <script> // Filtering odd children var even = d3.selectAll("h5") .select(function (d, i) { return i & 1 ? this : null }); // Filtering even children var odd = d3.selectAll("h5") .select(function (d, i) { return i & 1 ? null : this }); // Merging both selections const merged = odd.merge(even).nodes(); even = even.nodes(); odd = odd.nodes(); console.log("Odd selection: ") odd.forEach((e) => { console.log(e.textContent); }); console.log("Even selection: ") even.forEach((e) => { console.log(e.textContent); }); // Printing text content console.log("Collection after merging odd and even is:") merged.forEach((e) => { console.log(e.textContent); }); </script></body> </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to filter object array based on attributes?
How to get selected value in dropdown list using JavaScript ?
How to remove duplicate elements from JavaScript Array ?
Installation of Node.js on Linux
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25220,
"s": 25192,
"text": "\n23 Aug, 2020"
},
{
"code": null,
"e": 25462,
"s": 25220,
"text": "The selection.merge() function in d3.js is used to merge the two given selections into one and return the new selection after merging them. The selection which is returned has the same number of groups and the same parents as this selection."
},
{
"code": null,
"e": 25470,
"s": 25462,
"text": "Syntax:"
},
{
"code": null,
"e": 25494,
"s": 25470,
"text": "selection.merge(other);"
},
{
"code": null,
"e": 25592,
"s": 25494,
"text": "Parameters: This function accepts single parameter other that describe selection is to be merged."
},
{
"code": null,
"e": 25642,
"s": 25592,
"text": "Return Values: This function returns a selection."
},
{
"code": null,
"e": 25653,
"s": 25642,
"text": "Example 1:"
},
{
"code": null,
"e": 25658,
"s": 25653,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" path1tent=\"width=device-width, initial-scale=1.0\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <script src= \"https://d3js.org/d3-selection.v1.min.js\"> </script></head> <body> <div> <h3>1. This text is in bold</h3> <h3>2. This text is also in bold</h3> <h3>3. Geeks</h3> <h3>4. Geeks</h3> <h3>5. Geeks for geeks</h3> </div> <script> // Filtering odd children const odd = d3.selectAll(\"h3\") .select(function (d, i) { return i & 1 ? this : null; }); // Filtering even children const even = d3.selectAll(\"h3\") .select(function (d, i) { return i & 1 ? null : this; }); // Merging both selections const merged = odd.merge(even).nodes(); // Printing text content console.log(\"Collection after merging odd and even is:\") merged.forEach((e) => { console.log(e.textContent); }); </script></body> </html>",
"e": 26817,
"s": 25658,
"text": null
},
{
"code": null,
"e": 26825,
"s": 26817,
"text": "Output:"
},
{
"code": null,
"e": 26836,
"s": 26825,
"text": "Example 2:"
},
{
"code": null,
"e": 26841,
"s": 26836,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" path1tent=\"width=device-width, initial-scale=1.0\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <script src= \"https://d3js.org/d3-selection.v1.min.js\"> </script></head> <body> <div> <h5>1. This is odd</h5> <h5>2. This is even</h5> <h5>3. This is odd</h5> <h5>4. This is even</h5> <h5>5. This is odd</h5> </div> <script> // Filtering odd children var even = d3.selectAll(\"h5\") .select(function (d, i) { return i & 1 ? this : null }); // Filtering even children var odd = d3.selectAll(\"h5\") .select(function (d, i) { return i & 1 ? null : this }); // Merging both selections const merged = odd.merge(even).nodes(); even = even.nodes(); odd = odd.nodes(); console.log(\"Odd selection: \") odd.forEach((e) => { console.log(e.textContent); }); console.log(\"Even selection: \") even.forEach((e) => { console.log(e.textContent); }); // Printing text content console.log(\"Collection after merging odd and even is:\") merged.forEach((e) => { console.log(e.textContent); }); </script></body> </html>",
"e": 28257,
"s": 26841,
"text": null
},
{
"code": null,
"e": 28265,
"s": 28257,
"text": "Output:"
},
{
"code": null,
"e": 28271,
"s": 28265,
"text": "D3.js"
},
{
"code": null,
"e": 28282,
"s": 28271,
"text": "JavaScript"
},
{
"code": null,
"e": 28299,
"s": 28282,
"text": "Web Technologies"
},
{
"code": null,
"e": 28397,
"s": 28299,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28406,
"s": 28397,
"text": "Comments"
},
{
"code": null,
"e": 28419,
"s": 28406,
"text": "Old Comments"
},
{
"code": null,
"e": 28480,
"s": 28419,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28521,
"s": 28480,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28569,
"s": 28521,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 28631,
"s": 28569,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 28688,
"s": 28631,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 28721,
"s": 28688,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28763,
"s": 28721,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28806,
"s": 28763,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28868,
"s": 28806,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Comprehensions in Python | We can create new sequences using a given python sequence. This is called comprehension. It basically a way of writing a concise code block to generate a sequence which can be a list, dictionary, set or a generator by using another sequence. It may involve multiple steps of conversion between different types of sequences.
In this method, we create a new list by manipulating the values of an existing list. In the below example we take a list and create a new list by adding 3 to each element of the given list.
given_list = [x for x in range(5)]
print(given_list)
new_list = [var+3 for var in given_list]
print(new_list)
Running the above code gives us the following result −
[0, 1, 2, 3, 4]
[3, 4, 5, 6, 7]
Similar to the above we can take in a list and create a dictionary from it.
given_list = [x for x in range(5)]
print(given_list)
#new_list = [var+3 for var in given_list]
new_dict = {var:var + 3 for var in given_list }
print(new_dict)
Running the above code gives us the following result −
[0, 1, 2, 3, 4]
{0: 3, 1: 4, 2: 5, 3: 6, 4: 7}
We can also take in two lists and create a new dictionary out of it.
list1 = [x for x in range(5)]
list2 = ['Mon','Tue','Wed','Thu','Fri']
print(list1)
print(list2)
new_dict ={key:value for (key, value) in zip(list1, list2)}
print(new_dict)
Running the above code gives us the following result −
[0, 1, 2, 3, 4]
['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
{0: 'Mon', 1: 'Tue', 2: 'Wed', 3: 'Thu', 4: 'Fri'}
We can take a similar approach as above and create new set from existing set or list. In the below example we create a new set by adding 3 to the elements of the existing set.
given_set = {x for x in range(5)}
print(given_set)
new_set = {var+3 for var in given_set}
print(new_set)
Running the above code gives us the following result −
{0, 1, 2, 3, 4}
{3, 4, 5, 6, 7}
New generators can be created from the existing list. These generators are memory efficient as they allocate memory as the items are generated instead of allocating it at the beginning.
given_list = [x for x in range(5)]
print(given_list)
new_set = (var+3 for var in given_list)
for var1 in new_set:
print(var1, end=" ")
Running the above code gives us the following result −
[0, 1, 2, 3, 4]
3 4 5 6 7 | [
{
"code": null,
"e": 1386,
"s": 1062,
"text": "We can create new sequences using a given python sequence. This is called comprehension. It basically a way of writing a concise code block to generate a sequence which can be a list, dictionary, set or a generator by using another sequence. It may involve multiple steps of conversion between different types of sequences."
},
{
"code": null,
"e": 1576,
"s": 1386,
"text": "In this method, we create a new list by manipulating the values of an existing list. In the below example we take a list and create a new list by adding 3 to each element of the given list."
},
{
"code": null,
"e": 1688,
"s": 1576,
"text": "given_list = [x for x in range(5)]\nprint(given_list)\n\nnew_list = [var+3 for var in given_list]\n\nprint(new_list)"
},
{
"code": null,
"e": 1743,
"s": 1688,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1775,
"s": 1743,
"text": "[0, 1, 2, 3, 4]\n[3, 4, 5, 6, 7]"
},
{
"code": null,
"e": 1851,
"s": 1775,
"text": "Similar to the above we can take in a list and create a dictionary from it."
},
{
"code": null,
"e": 2012,
"s": 1851,
"text": "given_list = [x for x in range(5)]\nprint(given_list)\n\n#new_list = [var+3 for var in given_list]\nnew_dict = {var:var + 3 for var in given_list }\n\nprint(new_dict)"
},
{
"code": null,
"e": 2067,
"s": 2012,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2114,
"s": 2067,
"text": "[0, 1, 2, 3, 4]\n{0: 3, 1: 4, 2: 5, 3: 6, 4: 7}"
},
{
"code": null,
"e": 2183,
"s": 2114,
"text": "We can also take in two lists and create a new dictionary out of it."
},
{
"code": null,
"e": 2357,
"s": 2183,
"text": "list1 = [x for x in range(5)]\nlist2 = ['Mon','Tue','Wed','Thu','Fri']\nprint(list1)\nprint(list2)\n\nnew_dict ={key:value for (key, value) in zip(list1, list2)}\n\nprint(new_dict)"
},
{
"code": null,
"e": 2412,
"s": 2357,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2515,
"s": 2412,
"text": "[0, 1, 2, 3, 4]\n['Mon', 'Tue', 'Wed', 'Thu', 'Fri']\n{0: 'Mon', 1: 'Tue', 2: 'Wed', 3: 'Thu', 4: 'Fri'}"
},
{
"code": null,
"e": 2691,
"s": 2515,
"text": "We can take a similar approach as above and create new set from existing set or list. In the below example we create a new set by adding 3 to the elements of the existing set."
},
{
"code": null,
"e": 2798,
"s": 2691,
"text": "given_set = {x for x in range(5)}\nprint(given_set)\n\nnew_set = {var+3 for var in given_set}\n\nprint(new_set)"
},
{
"code": null,
"e": 2853,
"s": 2798,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2885,
"s": 2853,
"text": "{0, 1, 2, 3, 4}\n{3, 4, 5, 6, 7}"
},
{
"code": null,
"e": 3071,
"s": 2885,
"text": "New generators can be created from the existing list. These generators are memory efficient as they allocate memory as the items are generated instead of allocating it at the beginning."
},
{
"code": null,
"e": 3211,
"s": 3071,
"text": "given_list = [x for x in range(5)]\nprint(given_list)\n\nnew_set = (var+3 for var in given_list)\n\nfor var1 in new_set:\n print(var1, end=\" \")"
},
{
"code": null,
"e": 3266,
"s": 3211,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 3292,
"s": 3266,
"text": "[0, 1, 2, 3, 4]\n3 4 5 6 7"
}
] |
TypeScript Arrays - GeeksforGeeks | 11 Jun, 2021
An array is a user-defined data type. An array is a homogeneous collection of similar types of elements that have a contiguous memory location and which can store multiple values of different data types.An array is a type of data structure that stores the elements of similar data type and consider it as an object too. We can store only a fixed set of elements and can’t expand its size, once its size is declared.The array follows Index based storage i.e)the first element of an array is stored at index 0 or at index ‘i’ and the remaining elements are stored at the location ‘i+1’.Features of an Array
Same data type of elements is stored in an array.
Array elements are always stored in contiguous memory locations.
Storage of 2-D array elements are rowed by row in a contiguous memory location.
The Starting element of address is represented by the array name.
The size of an array should be declared at the time of initialization.
The remaining elements of an array can be retrieved by using the starting index of an Array.
Typescript supports array just like that in JavaScript. There are two ways to declare an array in typescript:1. Using square brackets.
let array_name[:datatype] = [val1, val2, valn..]
Example:
javascript
let fruits: string[] = ['Apple', 'Orange', 'Banana'];
2. Using a generic array type. TypeScript array can contain elements of different data types, as shown below.
let array_name: Array = [val1, val2, valn..]
Example: Multi Type Array
javascript
var values: (string | number)[] = ['Apple', 2, 'Orange', 3, 4, 'Banana'];// orvar values: Array = ['Apple', 2, 'Orange', 3, 4, 'Banana'];
Example: Access Array Elements
Array elements access on the basis of index i.e.)ArrayName[index].
javascript
let fruits: string[] = ['Apple', 'Orange', 'Banana'];fruits[0]; // returns Applefruits[1]; // returns Orangefruits[2]; // returns Bananafruits[3]; // returns undefined
We can access the array elements by using the ‘FOR’ loop:
javascript
let fruits: string[] = ['Apple', 'Orange', 'Banana']; for(var index in fruits){ console.log(fruits[index]); // output: Apple Orange Banana} for(var i = 0; i < fruits.length; i++){ console.log(fruits[i]); // output: Apple Orange Banana}
Advantages Code Optimization: We can retrieve or sort the array data more efficiently. Random access: We can randomly access the array data using the location pointer.Disadvantages Size Limit: The size of an Array is fixed i.e.)static. We cannot increase the array size once it has been declared.
There are two types of an array: 1.Single-Dimensional Array 2.Multi-Dimensional Array
Single-Dimensional Array It is the simplest form of an array that contains only one row for storing data. It contains single set of the square bracket (“[]”). Syntax:
let array_name[:datatype];
Initialization:
array_name = [val1, val2, valn..]
Example:
javascript
let arr:number[]; arr = [1, 2, 3, 4] console.log("Array[0]: " +arr[0]); console.log("Array[1]: " +arr[1]);
Output:
Array[0]: 1
Array[1]: 2
Multi-Dimensional Array The data is stored in rows and columns (also known as matrix form) in a Multi-dimensional array.TypeScript Arrays Syntax:
let arr_name:datatype[][] = [ [a1, a2, a3], [b1, b2, b3] ];
Initialization:
let arr_name:datatype[initial_array_index][referenced_array_index] = [ [val1, val2, val 3], [v1, v2, v3]];
Example:
javascript
var mArray:number[][] = [[10, 20, 30], [50, 60, 70]] ; console.log(mArray[0][0]); console.log(mArray[0][1]); console.log(mArray[0][2]); console.log(); console.log(mArray[1][0]); console.log(mArray[1][1]); console.log(mArray[1][2]);
OUTPUT:
10
20
30
50
60
70
Array ObjectWe can create an Array by using or initializing the Array Object. The Array constructor is used to pass the following arguments to create an Array:
With the numeric value which represents the size of an array.
A list of comma separated values.
Syntax:
1.let arr_name:datatype[] = new Array(values);
Example:
javascript
// Initializing an Array by using the Array object. let arr:string[] = new Array("GEEKSFORGEEKS", "2200", "Java", "Abhishek"); for(var i = 0;i<arr.length;i++) { console.log(arr[i]);
Output:
GEEKSFORGEEKS
2200
Java
Abhishek
Passing an Array to a Function We can pass an Array to a function by specifying the Array name without an index. Example:
javascript
let arr:string[] = new Array("GEEKSFORGEEKS", "2300", "Java", "Abhishek"); // Passing an Array in a function function display(arr_values:string[]) { for(let i = 0;i<arr_values.length;i++) { console.log(arr[i]); } } // Calling an Array in a function display(arr);
Output
GEEKSFORGEEKS
2300
Java
Abhishek
Using TypeScript ‘Spread’ operator The spread operator can be used to initialize arrays and objects from another array or object. It can also be used for object destructuring. It is a part of ECMAScript 6 version.
javascript
let arr1 = [ 1, 2, 3]; let arr2 = [ 4, 5, 6]; //Create new array from existing array let copyArray = [...arr1]; console.log("CopiedArray: " +copyArray); //Create new array from existing array with more elements let newArray = [...arr1, 7, 8]; console.log("NewArray: " +newArray); //Create array by merging two arrays let mergedArray = [...arr1, ...arr2]; console.log("MergedArray: " +mergedArray);
Output:
CopiedArray: 1, 2, 3
NewArray: 1, 2, 3, 7, 8
MergedArray: 1, 2, 3, 4, 5, 6
ruhelaa48
TypeScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Convert a string to an integer in JavaScript
File uploading in React.js
How to set input type date in dd-mm-yyyy format using HTML ?
How to redirect to another page in ReactJS ? | [
{
"code": null,
"e": 24073,
"s": 24045,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 24680,
"s": 24073,
"text": "An array is a user-defined data type. An array is a homogeneous collection of similar types of elements that have a contiguous memory location and which can store multiple values of different data types.An array is a type of data structure that stores the elements of similar data type and consider it as an object too. We can store only a fixed set of elements and can’t expand its size, once its size is declared.The array follows Index based storage i.e)the first element of an array is stored at index 0 or at index ‘i’ and the remaining elements are stored at the location ‘i+1’.Features of an Array "
},
{
"code": null,
"e": 24730,
"s": 24680,
"text": "Same data type of elements is stored in an array."
},
{
"code": null,
"e": 24797,
"s": 24732,
"text": "Array elements are always stored in contiguous memory locations."
},
{
"code": null,
"e": 24879,
"s": 24799,
"text": "Storage of 2-D array elements are rowed by row in a contiguous memory location."
},
{
"code": null,
"e": 24947,
"s": 24881,
"text": "The Starting element of address is represented by the array name."
},
{
"code": null,
"e": 25020,
"s": 24949,
"text": "The size of an array should be declared at the time of initialization."
},
{
"code": null,
"e": 25115,
"s": 25022,
"text": "The remaining elements of an array can be retrieved by using the starting index of an Array."
},
{
"code": null,
"e": 25252,
"s": 25115,
"text": "Typescript supports array just like that in JavaScript. There are two ways to declare an array in typescript:1. Using square brackets. "
},
{
"code": null,
"e": 25303,
"s": 25252,
"text": "let array_name[:datatype] = [val1, val2, valn..] "
},
{
"code": null,
"e": 25314,
"s": 25303,
"text": "Example: "
},
{
"code": null,
"e": 25325,
"s": 25314,
"text": "javascript"
},
{
"code": "let fruits: string[] = ['Apple', 'Orange', 'Banana'];",
"e": 25379,
"s": 25325,
"text": null
},
{
"code": null,
"e": 25491,
"s": 25379,
"text": "2. Using a generic array type. TypeScript array can contain elements of different data types, as shown below. "
},
{
"code": null,
"e": 25538,
"s": 25491,
"text": "let array_name: Array = [val1, val2, valn..] "
},
{
"code": null,
"e": 25566,
"s": 25538,
"text": "Example: Multi Type Array "
},
{
"code": null,
"e": 25577,
"s": 25566,
"text": "javascript"
},
{
"code": "var values: (string | number)[] = ['Apple', 2, 'Orange', 3, 4, 'Banana'];// orvar values: Array = ['Apple', 2, 'Orange', 3, 4, 'Banana'];",
"e": 25715,
"s": 25577,
"text": null
},
{
"code": null,
"e": 25748,
"s": 25715,
"text": "Example: Access Array Elements "
},
{
"code": null,
"e": 25815,
"s": 25748,
"text": "Array elements access on the basis of index i.e.)ArrayName[index]."
},
{
"code": null,
"e": 25828,
"s": 25817,
"text": "javascript"
},
{
"code": "let fruits: string[] = ['Apple', 'Orange', 'Banana'];fruits[0]; // returns Applefruits[1]; // returns Orangefruits[2]; // returns Bananafruits[3]; // returns undefined",
"e": 25996,
"s": 25828,
"text": null
},
{
"code": null,
"e": 26054,
"s": 25996,
"text": "We can access the array elements by using the ‘FOR’ loop:"
},
{
"code": null,
"e": 26065,
"s": 26054,
"text": "javascript"
},
{
"code": "let fruits: string[] = ['Apple', 'Orange', 'Banana']; for(var index in fruits){ console.log(fruits[index]); // output: Apple Orange Banana} for(var i = 0; i < fruits.length; i++){ console.log(fruits[i]); // output: Apple Orange Banana}",
"e": 26308,
"s": 26065,
"text": null
},
{
"code": null,
"e": 26605,
"s": 26308,
"text": "Advantages Code Optimization: We can retrieve or sort the array data more efficiently. Random access: We can randomly access the array data using the location pointer.Disadvantages Size Limit: The size of an Array is fixed i.e.)static. We cannot increase the array size once it has been declared."
},
{
"code": null,
"e": 26692,
"s": 26605,
"text": "There are two types of an array: 1.Single-Dimensional Array 2.Multi-Dimensional Array "
},
{
"code": null,
"e": 26861,
"s": 26692,
"text": "Single-Dimensional Array It is the simplest form of an array that contains only one row for storing data. It contains single set of the square bracket (“[]”). Syntax: "
},
{
"code": null,
"e": 26889,
"s": 26861,
"text": "let array_name[:datatype]; "
},
{
"code": null,
"e": 26907,
"s": 26889,
"text": "Initialization: "
},
{
"code": null,
"e": 26941,
"s": 26907,
"text": "array_name = [val1, val2, valn..]"
},
{
"code": null,
"e": 26951,
"s": 26941,
"text": "Example: "
},
{
"code": null,
"e": 26962,
"s": 26951,
"text": "javascript"
},
{
"code": "let arr:number[]; arr = [1, 2, 3, 4] console.log(\"Array[0]: \" +arr[0]); console.log(\"Array[1]: \" +arr[1]); ",
"e": 27073,
"s": 26962,
"text": null
},
{
"code": null,
"e": 27083,
"s": 27073,
"text": "Output: "
},
{
"code": null,
"e": 27107,
"s": 27083,
"text": "Array[0]: 1\nArray[1]: 2"
},
{
"code": null,
"e": 27255,
"s": 27107,
"text": "Multi-Dimensional Array The data is stored in rows and columns (also known as matrix form) in a Multi-dimensional array.TypeScript Arrays Syntax: "
},
{
"code": null,
"e": 27317,
"s": 27255,
"text": "let arr_name:datatype[][] = [ [a1, a2, a3], [b1, b2, b3] ]; "
},
{
"code": null,
"e": 27335,
"s": 27317,
"text": "Initialization: "
},
{
"code": null,
"e": 27444,
"s": 27335,
"text": "let arr_name:datatype[initial_array_index][referenced_array_index] = [ [val1, val2, val 3], [v1, v2, v3]]; "
},
{
"code": null,
"e": 27454,
"s": 27444,
"text": "Example: "
},
{
"code": null,
"e": 27465,
"s": 27454,
"text": "javascript"
},
{
"code": "var mArray:number[][] = [[10, 20, 30], [50, 60, 70]] ; console.log(mArray[0][0]); console.log(mArray[0][1]); console.log(mArray[0][2]); console.log(); console.log(mArray[1][0]); console.log(mArray[1][1]); console.log(mArray[1][2]); ",
"e": 27698,
"s": 27465,
"text": null
},
{
"code": null,
"e": 27708,
"s": 27698,
"text": "OUTPUT: "
},
{
"code": null,
"e": 27727,
"s": 27708,
"text": "10\n20\n30\n\n50\n60\n70"
},
{
"code": null,
"e": 27889,
"s": 27727,
"text": "Array ObjectWe can create an Array by using or initializing the Array Object. The Array constructor is used to pass the following arguments to create an Array: "
},
{
"code": null,
"e": 27951,
"s": 27889,
"text": "With the numeric value which represents the size of an array."
},
{
"code": null,
"e": 27987,
"s": 27953,
"text": "A list of comma separated values."
},
{
"code": null,
"e": 27997,
"s": 27987,
"text": "Syntax: "
},
{
"code": null,
"e": 28046,
"s": 27997,
"text": "1.let arr_name:datatype[] = new Array(values); "
},
{
"code": null,
"e": 28057,
"s": 28046,
"text": "Example: "
},
{
"code": null,
"e": 28068,
"s": 28057,
"text": "javascript"
},
{
"code": "// Initializing an Array by using the Array object. let arr:string[] = new Array(\"GEEKSFORGEEKS\", \"2200\", \"Java\", \"Abhishek\"); for(var i = 0;i<arr.length;i++) { console.log(arr[i]); ",
"e": 28255,
"s": 28068,
"text": null
},
{
"code": null,
"e": 28265,
"s": 28255,
"text": "Output: "
},
{
"code": null,
"e": 28298,
"s": 28265,
"text": "GEEKSFORGEEKS\n2200\nJava\nAbhishek"
},
{
"code": null,
"e": 28422,
"s": 28298,
"text": "Passing an Array to a Function We can pass an Array to a function by specifying the Array name without an index. Example: "
},
{
"code": null,
"e": 28433,
"s": 28422,
"text": "javascript"
},
{
"code": "let arr:string[] = new Array(\"GEEKSFORGEEKS\", \"2300\", \"Java\", \"Abhishek\"); // Passing an Array in a function function display(arr_values:string[]) { for(let i = 0;i<arr_values.length;i++) { console.log(arr[i]); } } // Calling an Array in a function display(arr);",
"e": 28712,
"s": 28433,
"text": null
},
{
"code": null,
"e": 28721,
"s": 28712,
"text": "Output "
},
{
"code": null,
"e": 28755,
"s": 28721,
"text": "GEEKSFORGEEKS\n2300\nJava\nAbhishek "
},
{
"code": null,
"e": 28970,
"s": 28755,
"text": "Using TypeScript ‘Spread’ operator The spread operator can be used to initialize arrays and objects from another array or object. It can also be used for object destructuring. It is a part of ECMAScript 6 version. "
},
{
"code": null,
"e": 28981,
"s": 28970,
"text": "javascript"
},
{
"code": "let arr1 = [ 1, 2, 3]; let arr2 = [ 4, 5, 6]; //Create new array from existing array let copyArray = [...arr1]; console.log(\"CopiedArray: \" +copyArray); //Create new array from existing array with more elements let newArray = [...arr1, 7, 8]; console.log(\"NewArray: \" +newArray); //Create array by merging two arrays let mergedArray = [...arr1, ...arr2]; console.log(\"MergedArray: \" +mergedArray);",
"e": 29382,
"s": 28981,
"text": null
},
{
"code": null,
"e": 29391,
"s": 29382,
"text": "Output: "
},
{
"code": null,
"e": 29466,
"s": 29391,
"text": "CopiedArray: 1, 2, 3\nNewArray: 1, 2, 3, 7, 8\nMergedArray: 1, 2, 3, 4, 5, 6"
},
{
"code": null,
"e": 29478,
"s": 29468,
"text": "ruhelaa48"
},
{
"code": null,
"e": 29489,
"s": 29478,
"text": "TypeScript"
},
{
"code": null,
"e": 29506,
"s": 29489,
"text": "Web Technologies"
},
{
"code": null,
"e": 29604,
"s": 29506,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29613,
"s": 29604,
"text": "Comments"
},
{
"code": null,
"e": 29626,
"s": 29613,
"text": "Old Comments"
},
{
"code": null,
"e": 29663,
"s": 29626,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 29706,
"s": 29663,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29767,
"s": 29706,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29839,
"s": 29767,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29889,
"s": 29839,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 29913,
"s": 29889,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 29958,
"s": 29913,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29985,
"s": 29958,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 30046,
"s": 29985,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Image Stitching Using OpenCV. As you know, the Google photos app has... | by Vagdevi Kommineni | Towards Data Science | As you know, the Google photos app has stunning automatic features like video making, panorama stitching, collage making, sorting out pic based on the presence of the person in the photo, and many more. I always wondered how come all these are possible. But one day, I felt extremely cool about making panorama stitching on my own.
I felt really excited when I gotta do a project on image stitching. That was a eureka moment when I finally managed to build my own image stitcher:). I did it in Python — my all-time favorite language and using OpenCV 3.1.0.
Albeit many resources are available on the Internet for this, today I would like to present my work along with the code. The following code and explanation are all for stitching up 2 images together.
Firstly, let us import the necessary modules.
import cv2import numpy as npimport matplotlib.pyplot as pltfrom random import randrange
As we know that we are stitching 2 images, let’s go read them.
img_ = cv2.imread(‘right.JPG’)img1 = cv2.cvtColor(img_,cv2.COLOR_BGR2GRAY)img = cv2.imread(‘left.JPG’)img2 = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
The cv2.cvtColor converts the input RGB image into its grayscale form.
For image stitching, we have the following major steps to follow:
Compute the sift-keypoints and descriptors for both the images.Compute distances between every descriptor in one image and every descriptor in the other image.Select the top ‘m’ matches for each descriptor of an image.Run RANSAC to estimate homographyWarp to align for stitchingNow stitch them together
Compute the sift-keypoints and descriptors for both the images.
Compute distances between every descriptor in one image and every descriptor in the other image.
Select the top ‘m’ matches for each descriptor of an image.
Run RANSAC to estimate homography
Warp to align for stitching
Now stitch them together
Eloborately... ,
Firstly, we have to find out the features matching in both the images. These best matched features act as the basis for stitching. We extract the key points and sift descriptors for both the images as follows:
sift = cv2.xfeatures2d.SIFT_create()# find the keypoints and descriptors with SIFTkp1, des1 = sift.detectAndCompute(img1,None)kp2, des2 = sift.detectAndCompute(img2,None)
kp1 and kp2 are keypoints, des1 and des2 are the descriptors of the respective images.
Now, the obtained descriptors in one image are to be recognized in the image too. We do that as follows:
bf = cv2.BFMatcher()matches = bf.knnMatch(des1,des2, k=2)
The BFMatcher() matches the features which are more similar. When we set parameter k=2, we are asking the knnMatcher to give out 2 best matches for each descriptor.
‘matches’ is a list of list, where each sub-list consists of ‘k’ objects. To understand this and follow the coming parts better, please go through this.
Often in images, there are tremendous chances where the features may be existing in many places of the image. This may mislead us to use trivial features for our experiment. So we filter out through all the matches to obtain the best ones. So we apply ratio test using the top 2 matches obtained above. We consider a match if the ratio defined below is predominantly greater than the specified ratio.
# Apply ratio testgood = []for m in matches:if m[0].distance < 0.5*m[1].distance:good.append(m)matches = np.asarray(good)
It’s time to align the images now. As you know that a homography matrix is needed to perform the transformation, and the homography matrix requires at least 4 matches, we do the following. Find more here.
if len(matches[:,0]) >= 4:src = np.float32([ kp1[m.queryIdx].pt for m in matches[:,0] ]).reshape(-1,1,2)dst = np.float32([ kp2[m.trainIdx].pt for m in matches[:,0] ]).reshape(-1,1,2)H, masked = cv2.findHomography(src, dst, cv2.RANSAC, 5.0)#print Helse:raise AssertionError(“Can’t find enough keypoints.”)
And finally comes the last part, stitching of the images. Now that we found the homography for transformation, we can now proceed to warp and stitch them together:
dst = cv2.warpPerspective(img_,H,(img.shape[1] + img_.shape[1], img.shape[0]))plt.subplot(122),plt.imshow(dst),plt.title(‘Warped Image’)plt.show()plt.figure()dst[0:img.shape[0], 0:img.shape[1]] = imgcv2.imwrite(‘output.jpg’,dst)plt.imshow(dst)plt.show()
We get warped image plotted using matplotlib to well visualize the warping.
The resultant is as follows: | [
{
"code": null,
"e": 504,
"s": 172,
"text": "As you know, the Google photos app has stunning automatic features like video making, panorama stitching, collage making, sorting out pic based on the presence of the person in the photo, and many more. I always wondered how come all these are possible. But one day, I felt extremely cool about making panorama stitching on my own."
},
{
"code": null,
"e": 729,
"s": 504,
"text": "I felt really excited when I gotta do a project on image stitching. That was a eureka moment when I finally managed to build my own image stitcher:). I did it in Python — my all-time favorite language and using OpenCV 3.1.0."
},
{
"code": null,
"e": 929,
"s": 729,
"text": "Albeit many resources are available on the Internet for this, today I would like to present my work along with the code. The following code and explanation are all for stitching up 2 images together."
},
{
"code": null,
"e": 975,
"s": 929,
"text": "Firstly, let us import the necessary modules."
},
{
"code": null,
"e": 1063,
"s": 975,
"text": "import cv2import numpy as npimport matplotlib.pyplot as pltfrom random import randrange"
},
{
"code": null,
"e": 1126,
"s": 1063,
"text": "As we know that we are stitching 2 images, let’s go read them."
},
{
"code": null,
"e": 1272,
"s": 1126,
"text": "img_ = cv2.imread(‘right.JPG’)img1 = cv2.cvtColor(img_,cv2.COLOR_BGR2GRAY)img = cv2.imread(‘left.JPG’)img2 = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)"
},
{
"code": null,
"e": 1343,
"s": 1272,
"text": "The cv2.cvtColor converts the input RGB image into its grayscale form."
},
{
"code": null,
"e": 1409,
"s": 1343,
"text": "For image stitching, we have the following major steps to follow:"
},
{
"code": null,
"e": 1712,
"s": 1409,
"text": "Compute the sift-keypoints and descriptors for both the images.Compute distances between every descriptor in one image and every descriptor in the other image.Select the top ‘m’ matches for each descriptor of an image.Run RANSAC to estimate homographyWarp to align for stitchingNow stitch them together"
},
{
"code": null,
"e": 1776,
"s": 1712,
"text": "Compute the sift-keypoints and descriptors for both the images."
},
{
"code": null,
"e": 1873,
"s": 1776,
"text": "Compute distances between every descriptor in one image and every descriptor in the other image."
},
{
"code": null,
"e": 1933,
"s": 1873,
"text": "Select the top ‘m’ matches for each descriptor of an image."
},
{
"code": null,
"e": 1967,
"s": 1933,
"text": "Run RANSAC to estimate homography"
},
{
"code": null,
"e": 1995,
"s": 1967,
"text": "Warp to align for stitching"
},
{
"code": null,
"e": 2020,
"s": 1995,
"text": "Now stitch them together"
},
{
"code": null,
"e": 2037,
"s": 2020,
"text": "Eloborately... ,"
},
{
"code": null,
"e": 2247,
"s": 2037,
"text": "Firstly, we have to find out the features matching in both the images. These best matched features act as the basis for stitching. We extract the key points and sift descriptors for both the images as follows:"
},
{
"code": null,
"e": 2418,
"s": 2247,
"text": "sift = cv2.xfeatures2d.SIFT_create()# find the keypoints and descriptors with SIFTkp1, des1 = sift.detectAndCompute(img1,None)kp2, des2 = sift.detectAndCompute(img2,None)"
},
{
"code": null,
"e": 2505,
"s": 2418,
"text": "kp1 and kp2 are keypoints, des1 and des2 are the descriptors of the respective images."
},
{
"code": null,
"e": 2610,
"s": 2505,
"text": "Now, the obtained descriptors in one image are to be recognized in the image too. We do that as follows:"
},
{
"code": null,
"e": 2668,
"s": 2610,
"text": "bf = cv2.BFMatcher()matches = bf.knnMatch(des1,des2, k=2)"
},
{
"code": null,
"e": 2833,
"s": 2668,
"text": "The BFMatcher() matches the features which are more similar. When we set parameter k=2, we are asking the knnMatcher to give out 2 best matches for each descriptor."
},
{
"code": null,
"e": 2986,
"s": 2833,
"text": "‘matches’ is a list of list, where each sub-list consists of ‘k’ objects. To understand this and follow the coming parts better, please go through this."
},
{
"code": null,
"e": 3387,
"s": 2986,
"text": "Often in images, there are tremendous chances where the features may be existing in many places of the image. This may mislead us to use trivial features for our experiment. So we filter out through all the matches to obtain the best ones. So we apply ratio test using the top 2 matches obtained above. We consider a match if the ratio defined below is predominantly greater than the specified ratio."
},
{
"code": null,
"e": 3509,
"s": 3387,
"text": "# Apply ratio testgood = []for m in matches:if m[0].distance < 0.5*m[1].distance:good.append(m)matches = np.asarray(good)"
},
{
"code": null,
"e": 3714,
"s": 3509,
"text": "It’s time to align the images now. As you know that a homography matrix is needed to perform the transformation, and the homography matrix requires at least 4 matches, we do the following. Find more here."
},
{
"code": null,
"e": 4019,
"s": 3714,
"text": "if len(matches[:,0]) >= 4:src = np.float32([ kp1[m.queryIdx].pt for m in matches[:,0] ]).reshape(-1,1,2)dst = np.float32([ kp2[m.trainIdx].pt for m in matches[:,0] ]).reshape(-1,1,2)H, masked = cv2.findHomography(src, dst, cv2.RANSAC, 5.0)#print Helse:raise AssertionError(“Can’t find enough keypoints.”)"
},
{
"code": null,
"e": 4183,
"s": 4019,
"text": "And finally comes the last part, stitching of the images. Now that we found the homography for transformation, we can now proceed to warp and stitch them together:"
},
{
"code": null,
"e": 4437,
"s": 4183,
"text": "dst = cv2.warpPerspective(img_,H,(img.shape[1] + img_.shape[1], img.shape[0]))plt.subplot(122),plt.imshow(dst),plt.title(‘Warped Image’)plt.show()plt.figure()dst[0:img.shape[0], 0:img.shape[1]] = imgcv2.imwrite(‘output.jpg’,dst)plt.imshow(dst)plt.show()"
},
{
"code": null,
"e": 4513,
"s": 4437,
"text": "We get warped image plotted using matplotlib to well visualize the warping."
}
] |
How to get max(id) of row data in MySQL? | To get max(id), use MAX() method in MySQL. Following is the syntax −
select MAX(yourColumnName) AS anyAliasName from yourTableName;
Let us first create a table −
mysql> create table DemoTable710 (Id int);
Query OK, 0 rows affected (0.53 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable710 values(1001);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable710 values(2001);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable710 values(1998);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable710 values(1789);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable710 values(1678);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable710 values(9087);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable710 values(1908);
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable710;
This will produce the following output -
+------+
| Id |
+------+
| 1001 |
| 2001 |
| 1998 |
| 1789 |
| 1678 |
| 9087 |
| 1908 |
+------+
7 rows in set (0.00 sec)
Following is the query to get max(id) of row data in MySQL −
mysql> select MAX(Id) AS Max_Id from DemoTable710;
This will produce the following output -
+--------+
| Max_Id |
+--------+
| 9087 |
+--------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1131,
"s": 1062,
"text": "To get max(id), use MAX() method in MySQL. Following is the syntax −"
},
{
"code": null,
"e": 1194,
"s": 1131,
"text": "select MAX(yourColumnName) AS anyAliasName from yourTableName;"
},
{
"code": null,
"e": 1224,
"s": 1194,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1304,
"s": 1224,
"text": "mysql> create table DemoTable710 (Id int);\nQuery OK, 0 rows affected (0.53 sec)"
},
{
"code": null,
"e": 1360,
"s": 1304,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1934,
"s": 1360,
"text": "mysql> insert into DemoTable710 values(1001);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable710 values(2001);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable710 values(1998);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable710 values(1789);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable710 values(1678);\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable710 values(9087);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable710 values(1908);\nQuery OK, 1 row affected (0.17 sec)"
},
{
"code": null,
"e": 1994,
"s": 1934,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2028,
"s": 1994,
"text": "mysql> select *from DemoTable710;"
},
{
"code": null,
"e": 2069,
"s": 2028,
"text": "This will produce the following output -"
},
{
"code": null,
"e": 2193,
"s": 2069,
"text": "+------+\n| Id |\n+------+\n| 1001 |\n| 2001 |\n| 1998 |\n| 1789 |\n| 1678 |\n| 9087 |\n| 1908 |\n+------+\n7 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2254,
"s": 2193,
"text": "Following is the query to get max(id) of row data in MySQL −"
},
{
"code": null,
"e": 2305,
"s": 2254,
"text": "mysql> select MAX(Id) AS Max_Id from DemoTable710;"
},
{
"code": null,
"e": 2346,
"s": 2305,
"text": "This will produce the following output -"
},
{
"code": null,
"e": 2425,
"s": 2346,
"text": "+--------+\n| Max_Id |\n+--------+\n| 9087 |\n+--------+\n1 row in set (0.00 sec)"
}
] |
Different ways to traverse an Array in Java? | In general, arrays are the containers that store multiple variables of the same datatype. These are of fixed size and the size is determined at the time of creation. Each element in an array is positioned by a number starting from 0.
You can access the elements of an array using name and position as −
System.out.println(myArray[3]);
//Which is 1457
In Java, arrays are treated as referenced types you can create an array using the new keyword similar to objects and populate it using the indices as −
int myArray[] = new int[7];
myArray[0] = 1254;
myArray[1] = 1458;
myArray[2] = 5687;
myArray[3] = 1457;
myArray[4] = 4554;
myArray[5] = 5445;
myArray[6] = 7524;
Or, you can directly assign values with in flower braces separating them with commas (,) as −
int myArray = { 1254, 1458, 5687, 1457, 4554, 5445, 7524};
You can traverse through an array using for loop or forEach loop.
Using the for loop − Instead on printing element by element, you can iterate the index using for loop starting from 0 to length of the array (ArrayName.length) and access elements at each index.
public class IteratingArray {
public static void main(String args[]) {
//Creating an array
int myArray[] = new int[7];
//Populating the array
myArray[0] = 1254;
myArray[1] = 1458;
myArray[2] = 5687;
myArray[3] = 1457;
myArray[4] = 4554;
myArray[5] = 5445;
myArray[6] = 7524;
//Printing Contents using for loop
System.out.println("Contents of the array: ");
for(int i=0; i<myArray.length; i++) {
System.out.println(myArray[i]);
}
}
}
Contents of the array:
1254
1458
5687
1457
4554
5445
7524
Using the for each loop − Since JDK 1.5, Java introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable. You can traverse through the array with less effort using this.
import java.util.Arrays;
public class IteratingArray {
public static void main(String args[]) {
//Creating an array
int myArray[] = new int[7];
//Populating the array
myArray[0] = 1254;
myArray[1] = 1458;
myArray[2] = 5687;
myArray[3] = 1457;
myArray[4] = 4554;
myArray[5] = 5445;
myArray[6] = 7524;
//Printing Contents using for each loop
System.out.println("Contents of the array: ");
for (int element: myArray) {
System.out.println(element);
}
}
}
Contents of the array:
[1254, 1458, 5687, 1457, 4554, 5445, 7524] | [
{
"code": null,
"e": 1296,
"s": 1062,
"text": "In general, arrays are the containers that store multiple variables of the same datatype. These are of fixed size and the size is determined at the time of creation. Each element in an array is positioned by a number starting from 0."
},
{
"code": null,
"e": 1365,
"s": 1296,
"text": "You can access the elements of an array using name and position as −"
},
{
"code": null,
"e": 1413,
"s": 1365,
"text": "System.out.println(myArray[3]);\n//Which is 1457"
},
{
"code": null,
"e": 1565,
"s": 1413,
"text": "In Java, arrays are treated as referenced types you can create an array using the new keyword similar to objects and populate it using the indices as −"
},
{
"code": null,
"e": 1726,
"s": 1565,
"text": "int myArray[] = new int[7];\nmyArray[0] = 1254;\nmyArray[1] = 1458;\nmyArray[2] = 5687;\nmyArray[3] = 1457;\nmyArray[4] = 4554;\nmyArray[5] = 5445;\nmyArray[6] = 7524;"
},
{
"code": null,
"e": 1820,
"s": 1726,
"text": "Or, you can directly assign values with in flower braces separating them with commas (,) as −"
},
{
"code": null,
"e": 1879,
"s": 1820,
"text": "int myArray = { 1254, 1458, 5687, 1457, 4554, 5445, 7524};"
},
{
"code": null,
"e": 1945,
"s": 1879,
"text": "You can traverse through an array using for loop or forEach loop."
},
{
"code": null,
"e": 2140,
"s": 1945,
"text": "Using the for loop − Instead on printing element by element, you can iterate the index using for loop starting from 0 to length of the array (ArrayName.length) and access elements at each index."
},
{
"code": null,
"e": 2672,
"s": 2140,
"text": "public class IteratingArray {\n public static void main(String args[]) {\n //Creating an array\n int myArray[] = new int[7];\n //Populating the array\n myArray[0] = 1254;\n myArray[1] = 1458;\n myArray[2] = 5687;\n myArray[3] = 1457;\n myArray[4] = 4554;\n myArray[5] = 5445;\n myArray[6] = 7524;\n //Printing Contents using for loop\n System.out.println(\"Contents of the array: \");\n for(int i=0; i<myArray.length; i++) {\n System.out.println(myArray[i]);\n }\n }\n}"
},
{
"code": null,
"e": 2730,
"s": 2672,
"text": "Contents of the array:\n1254\n1458\n5687\n1457\n4554\n5445\n7524"
},
{
"code": null,
"e": 3005,
"s": 2730,
"text": "Using the for each loop − Since JDK 1.5, Java introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable. You can traverse through the array with less effort using this."
},
{
"code": null,
"e": 3555,
"s": 3005,
"text": "import java.util.Arrays;\npublic class IteratingArray {\n public static void main(String args[]) {\n //Creating an array\n int myArray[] = new int[7];\n //Populating the array\n myArray[0] = 1254;\n myArray[1] = 1458;\n myArray[2] = 5687;\n myArray[3] = 1457;\n myArray[4] = 4554;\n myArray[5] = 5445;\n myArray[6] = 7524;\n //Printing Contents using for each loop\n System.out.println(\"Contents of the array: \");\n for (int element: myArray) {\n System.out.println(element);\n }\n }\n}"
},
{
"code": null,
"e": 3621,
"s": 3555,
"text": "Contents of the array:\n[1254, 1458, 5687, 1457, 4554, 5445, 7524]"
}
] |
Java Examples - Getting connected to Server | How to get connected with web server ?
Following example demonstrates how to get connected with web server by using sock.getInetAddress() method of net.Socket class.
import java.net.InetAddress;
import java.net.Socket;
public class WebPing {
public static void main(String[] args) {
try {
InetAddress addr;
Socket sock = new Socket("www.javatutorial.com", 80);
addr = sock.getInetAddress();
System.out.println("Connected to " + addr);
sock.close();
} catch (java.io.IOException e) {
System.out.println("Can't connect to " + args[0]);
System.out.println(e);
}
}
}
The above code sample will produce the following result.
Connected to www.javatutorial.com/69.172.201.153
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2107,
"s": 2068,
"text": "How to get connected with web server ?"
},
{
"code": null,
"e": 2234,
"s": 2107,
"text": "Following example demonstrates how to get connected with web server by using sock.getInetAddress() method of net.Socket class."
},
{
"code": null,
"e": 2719,
"s": 2234,
"text": "import java.net.InetAddress;\nimport java.net.Socket;\n\npublic class WebPing {\n public static void main(String[] args) {\n try {\n InetAddress addr;\n Socket sock = new Socket(\"www.javatutorial.com\", 80);\n addr = sock.getInetAddress();\n System.out.println(\"Connected to \" + addr);\n sock.close();\n } catch (java.io.IOException e) {\n System.out.println(\"Can't connect to \" + args[0]);\n System.out.println(e);\n }\n }\n}"
},
{
"code": null,
"e": 2776,
"s": 2719,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 2826,
"s": 2776,
"text": "Connected to www.javatutorial.com/69.172.201.153\n"
},
{
"code": null,
"e": 2833,
"s": 2826,
"text": " Print"
},
{
"code": null,
"e": 2844,
"s": 2833,
"text": " Add Notes"
}
] |
Compare popular AutoML frameworks on 10 tabular Kaggle competitions | by Piotr Płoński | Towards Data Science | Have you ever lost your evening juggling different many Machine Learning algorithms and packages, switching hyperparameters values and trying different preprocessing methods? Building a good Machine Learning pipeline requires a lot of try-and-error work. Thus, it’s very time-consuming and can be exhausting.
The Automated Machine Learning (AutoML) frameworks aim to help.
I started to work on AutoML systems in 2016. I was a Ph.D. student working on many ML projects from different domains: high-energy physics, medicine, and bioinformatics. I needed elegant software that I can use to swap my code with lots of tuning and validation loops. This is how I started to work on the project that I called the MLJAR. The name comes from ML + JAR, but the JAR here has the second meaning (I was studying in Warsaw, Poland):
JAR is an informal term used for incoming residents of Warsaw. The term is derived from jars which are used by many students and workers for carrying food from their parent’s house when visiting during the weekend.
You can read more about JARs in this article. It has a rather negative meaning. I thought that I will use it to name my new project. I will make the project successful to show that it is a mistake to treat newcomers badly.
The MLJAR AutoML engine is available as an open-source with code available on GitHub: https://github.com/mljar/mljar-supervised
The MLJAR AutoML works with tabular datasets.
The biggest advantage of the MLJAR AutoML is its transparency. There is no black-box magic in it. You can check the details of every step of the AutoML training. All information about trained models is saved in the hard drive (auto-save is switched on, always). Each model has its own README.md file. So you can easily check details (for example in GitHub, VS Code, or Jupyter Notebook). Below the example of a Markdown README.md report from the model training:
In the past, AutoML was only for hyper-parameters optimization. It is the simplest thing that can be automated in the ML pipeline. Today, AutoML can serve many purposes. The MLJAR AutoML can work in three modes:
Explain — It is fast. Takes only a few minutes. Should be used to get you familiar with a new dataset. It does Exploratory Data Analysis. It trains only a few models with default hyper-parameters (no tuning!). For each model, a full set of explanations are produced: feature importance, SHAP dependency plots, decision plots, learning curves, and more.
Compete — The highly-tuned ML pipeline. Should be used for building high-accuracy models. The training can take long, easily more than 4 hours (depending on the dataset). It is using advanced feature engineering, ensembling, and stacking.
Perform — The mode for training production-ready ML models. The balance between speed of training and final accuracy.
Selection of the training mode is as simple as setting on parameter:
# initialization of AutoML with Compete mode# mode can be: Explain, Compete, Performautoml = AutoML(mode="Compete")
Feature engineering is very important for the performance of the Machine Learning pipeline. The MLJAR AutoML provides advanced feature engineering methods. It can generate new features with K-Means or Golden Features Search. There is also a Feature Selection procedure that can work with any Machine Learning algorithm.
Let’s check the AutoML performance on the most challenging datasets. The Kaggle platform hosts Data Science competitions with real-life data problems. I’ve used 10 tabular datasets from Kaggle that represent various Machine Learning tasks:
binary classification
multi-class classification
regression
Datasets selection is the same as in the article: N. Erickson, et al.: AutoGluon-Tabular: Robust and Accurate AutoML for Structured Data (Except House Prices Adv. Regression, because in the article there were no results from Private Leaderboard, the competition was still ongoing).
There were evaluated following frameworks:
AutoWeka
Auto-Sklearn
TPOT
H2O
Google Cloud AutoML Tables
AutoGluon
MLJAR
The frameworks were trained on m5.24xlarge EC2 machines (96CPU, 384 GB RAM). The training time was set to 4 hours. (Except GCP-Tables which was using its own machine types)
The final results presented below are presented as Percentile Rank in the Private Leaderboard (evaluated internally by Kaggle). The higher the value, the better. The 1st place solution in the Kaggle competition will get Percentile Rank equal 1.0. The last place in the solution in the competition will give 0 value. The results for AutoMLs other than MLJAR are from AutoGluon paper.
You can see that some AutoML frameworks jump into the Top-10% of the competition (without any human help)! The MLJAR AutoML without any human intervention was 5 times in the Top-25% out of the 10 Kaggle competitions. What is more, it was 3 times in the Top-10%.
Nowadays AutoML is a multi-purpose tool. Can be used by:
software engineers that need to apply ML in the application but don't know details how to tweak ML algorithms
citizen data scientists to build ML pipeline in a low-code environment
data scientists and engineers to speed-up their work
I hope that many people will benefit from my AutoML system. I put a lot of effort into it. I’m very interested in your opinion and feedback about MLJAR AutoML, and AutoML in general.
You can find MLJAR AutoML at GitHub: https://github.com/mljar/mljar-supervised | [
{
"code": null,
"e": 481,
"s": 172,
"text": "Have you ever lost your evening juggling different many Machine Learning algorithms and packages, switching hyperparameters values and trying different preprocessing methods? Building a good Machine Learning pipeline requires a lot of try-and-error work. Thus, it’s very time-consuming and can be exhausting."
},
{
"code": null,
"e": 545,
"s": 481,
"text": "The Automated Machine Learning (AutoML) frameworks aim to help."
},
{
"code": null,
"e": 990,
"s": 545,
"text": "I started to work on AutoML systems in 2016. I was a Ph.D. student working on many ML projects from different domains: high-energy physics, medicine, and bioinformatics. I needed elegant software that I can use to swap my code with lots of tuning and validation loops. This is how I started to work on the project that I called the MLJAR. The name comes from ML + JAR, but the JAR here has the second meaning (I was studying in Warsaw, Poland):"
},
{
"code": null,
"e": 1205,
"s": 990,
"text": "JAR is an informal term used for incoming residents of Warsaw. The term is derived from jars which are used by many students and workers for carrying food from their parent’s house when visiting during the weekend."
},
{
"code": null,
"e": 1428,
"s": 1205,
"text": "You can read more about JARs in this article. It has a rather negative meaning. I thought that I will use it to name my new project. I will make the project successful to show that it is a mistake to treat newcomers badly."
},
{
"code": null,
"e": 1556,
"s": 1428,
"text": "The MLJAR AutoML engine is available as an open-source with code available on GitHub: https://github.com/mljar/mljar-supervised"
},
{
"code": null,
"e": 1602,
"s": 1556,
"text": "The MLJAR AutoML works with tabular datasets."
},
{
"code": null,
"e": 2064,
"s": 1602,
"text": "The biggest advantage of the MLJAR AutoML is its transparency. There is no black-box magic in it. You can check the details of every step of the AutoML training. All information about trained models is saved in the hard drive (auto-save is switched on, always). Each model has its own README.md file. So you can easily check details (for example in GitHub, VS Code, or Jupyter Notebook). Below the example of a Markdown README.md report from the model training:"
},
{
"code": null,
"e": 2276,
"s": 2064,
"text": "In the past, AutoML was only for hyper-parameters optimization. It is the simplest thing that can be automated in the ML pipeline. Today, AutoML can serve many purposes. The MLJAR AutoML can work in three modes:"
},
{
"code": null,
"e": 2629,
"s": 2276,
"text": "Explain — It is fast. Takes only a few minutes. Should be used to get you familiar with a new dataset. It does Exploratory Data Analysis. It trains only a few models with default hyper-parameters (no tuning!). For each model, a full set of explanations are produced: feature importance, SHAP dependency plots, decision plots, learning curves, and more."
},
{
"code": null,
"e": 2868,
"s": 2629,
"text": "Compete — The highly-tuned ML pipeline. Should be used for building high-accuracy models. The training can take long, easily more than 4 hours (depending on the dataset). It is using advanced feature engineering, ensembling, and stacking."
},
{
"code": null,
"e": 2986,
"s": 2868,
"text": "Perform — The mode for training production-ready ML models. The balance between speed of training and final accuracy."
},
{
"code": null,
"e": 3055,
"s": 2986,
"text": "Selection of the training mode is as simple as setting on parameter:"
},
{
"code": null,
"e": 3171,
"s": 3055,
"text": "# initialization of AutoML with Compete mode# mode can be: Explain, Compete, Performautoml = AutoML(mode=\"Compete\")"
},
{
"code": null,
"e": 3491,
"s": 3171,
"text": "Feature engineering is very important for the performance of the Machine Learning pipeline. The MLJAR AutoML provides advanced feature engineering methods. It can generate new features with K-Means or Golden Features Search. There is also a Feature Selection procedure that can work with any Machine Learning algorithm."
},
{
"code": null,
"e": 3731,
"s": 3491,
"text": "Let’s check the AutoML performance on the most challenging datasets. The Kaggle platform hosts Data Science competitions with real-life data problems. I’ve used 10 tabular datasets from Kaggle that represent various Machine Learning tasks:"
},
{
"code": null,
"e": 3753,
"s": 3731,
"text": "binary classification"
},
{
"code": null,
"e": 3780,
"s": 3753,
"text": "multi-class classification"
},
{
"code": null,
"e": 3791,
"s": 3780,
"text": "regression"
},
{
"code": null,
"e": 4073,
"s": 3791,
"text": "Datasets selection is the same as in the article: N. Erickson, et al.: AutoGluon-Tabular: Robust and Accurate AutoML for Structured Data (Except House Prices Adv. Regression, because in the article there were no results from Private Leaderboard, the competition was still ongoing)."
},
{
"code": null,
"e": 4116,
"s": 4073,
"text": "There were evaluated following frameworks:"
},
{
"code": null,
"e": 4125,
"s": 4116,
"text": "AutoWeka"
},
{
"code": null,
"e": 4138,
"s": 4125,
"text": "Auto-Sklearn"
},
{
"code": null,
"e": 4143,
"s": 4138,
"text": "TPOT"
},
{
"code": null,
"e": 4147,
"s": 4143,
"text": "H2O"
},
{
"code": null,
"e": 4174,
"s": 4147,
"text": "Google Cloud AutoML Tables"
},
{
"code": null,
"e": 4184,
"s": 4174,
"text": "AutoGluon"
},
{
"code": null,
"e": 4190,
"s": 4184,
"text": "MLJAR"
},
{
"code": null,
"e": 4363,
"s": 4190,
"text": "The frameworks were trained on m5.24xlarge EC2 machines (96CPU, 384 GB RAM). The training time was set to 4 hours. (Except GCP-Tables which was using its own machine types)"
},
{
"code": null,
"e": 4746,
"s": 4363,
"text": "The final results presented below are presented as Percentile Rank in the Private Leaderboard (evaluated internally by Kaggle). The higher the value, the better. The 1st place solution in the Kaggle competition will get Percentile Rank equal 1.0. The last place in the solution in the competition will give 0 value. The results for AutoMLs other than MLJAR are from AutoGluon paper."
},
{
"code": null,
"e": 5008,
"s": 4746,
"text": "You can see that some AutoML frameworks jump into the Top-10% of the competition (without any human help)! The MLJAR AutoML without any human intervention was 5 times in the Top-25% out of the 10 Kaggle competitions. What is more, it was 3 times in the Top-10%."
},
{
"code": null,
"e": 5065,
"s": 5008,
"text": "Nowadays AutoML is a multi-purpose tool. Can be used by:"
},
{
"code": null,
"e": 5175,
"s": 5065,
"text": "software engineers that need to apply ML in the application but don't know details how to tweak ML algorithms"
},
{
"code": null,
"e": 5246,
"s": 5175,
"text": "citizen data scientists to build ML pipeline in a low-code environment"
},
{
"code": null,
"e": 5299,
"s": 5246,
"text": "data scientists and engineers to speed-up their work"
},
{
"code": null,
"e": 5482,
"s": 5299,
"text": "I hope that many people will benefit from my AutoML system. I put a lot of effort into it. I’m very interested in your opinion and feedback about MLJAR AutoML, and AutoML in general."
}
] |
Machine Learning Model Regularization in Practice: an example with Keras and TensorFlow 2.0 | by B. Chen | Towards Data Science | In this article, we will focus on incorporating regularization into our machine learning model and look at an example of how we do this in practice with Keras and TensorFlow 2.0.
Turns out many people are afraid of Maths, especially beginners and people changing career paths to data science.
Let’s avoid Maths and try to explain regularization in a more gentle way. If you are looking for a complete explanation (with a lot of math expressions) of regularisation, you might find the following articles useful:
Regularization in Machine Learning
Regularization: an important concept in Machine Learning
Regularization is a technique to combat the overfitting issue in machine learning. Overfitting, also known as High Variance, refers to a model that learns the training data too well but fail to generalize to new data. For example, the green line below is an overfitted model and the black line represents a regularized model.
Overfitting can be diagnosed by plotting training and validation loss. For example, in the below graph, training error is shown in blue, validation error in red, both as a function of the number of training epochs. If the validation error increases while the training error steadily decreases, then a situation of overfitting may have occurred.
Once overfitting is diagnosed, it is time to try different regularization techniques and parameters to see if they help. The most widely used regularization techniques are:
L1 regularization adds “absolute value of magnitude” as penalty term to the loss function. Some people say L1 can help with compressing the model. But in practice, L1 regularization makes your model sparse, helps only a little bit. L2 regularization is just used much more often.
L2 regularization (also known as weight decay) adds “squared magnitude” as penalty term to the loss function and it is used much more often than L1.
Dropout is widely used regularization technique in deep learning. It randomly shuts down some neurons in each iteration.
Data Augmentation adds extra fake training data. More training also helps with reducing overfitting.
Early Stopping is another widely used regularization technique in deep learning. It stops training when generalization error increases.
In the following article, we are going to incorporate L2 regularization and Dropout to reduce overfitting of a neural network model.
In order to run this tutorial, you need to install
TensorFlow 2, numpy, pandas, sklean, matplotlib
They can all be installed directly vis PyPI and I strongly recommend to create a new Virtual Environment. For a tutorial on creating a Python virtual environment
Create Virtual Environment using “virtualenv” and add it to Jupyter Notebook
Create Virtual Environment using “conda” and add it to Jupyter Notebook
This is a step by step tutorial and all instructions are in this article. For source code, please check out my Github machine learning repo.
This tutorial uses the Anderson Iris flower (iris) dataset for demonstration. The dataset contains a set of 150 records under five attributes: sepal length, sepal width, petal length, petal width, and class (known as target from sklearn datasets).
First, let’s import the libraries and obtain iris dataset from scikit-learn library. You can also download it from the UCI Iris dataset.
import tensorflow as tfimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.datasets import load_irisfrom sklearn.model_selection import train_test_splitiris = load_iris()
For the purpose of exploring data, let’s load data into a DataFrame
# Load data into a DataFramedf = pd.DataFrame(iris.data, columns=iris.feature_names)# Convert datatype to floatdf = df.astype(float)# append "target" and name it "label"df['label'] = iris.target# Use string label insteaddf['label'] = df.label.replace(dict(enumerate(iris.target_names)))
And the df should look like below:
We notice the label column is a categorical feature and will need to convert it to one-hot encoding. Otherwise, our machine learning algorithm won’t be able to directly take in that as input.
# label -> one-hot encodinglabel = pd.get_dummies(df['label'], prefix='label')df = pd.concat([df, label], axis=1)# drop old labeldf.drop(['label'], axis=1, inplace=True)
Now, the df should look like:
Next, let’s create X and y. Keras and TensorFlow 2.0 only take in Numpy array as inputs, so we will have to convert DataFrame back to Numpy array.
# Creating X and yX = df[['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']]# Convert DataFrame into np arrayX = np.asarray(X)y = df[['label_setosa', 'label_versicolor', 'label_virginica']]# Convert DataFrame into np arrayy = np.asarray(y)
Finally, let’s split the dataset into a training set (80%)and a test set (20%) using train_test_split() from sklearn library.
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.20)
Great! our data is ready for building a Machine Learning model.
Before applying regularization, let’s build a neural network without regularization and take a look at the overfitting issue.
There are 3 ways to create a machine learning model with Keras and Tensorflow 2. Since we are building a simple fully connected Neural Network and for simplicity, let’s use the easiest way: Sequential Model with Sequential().
Let’s go ahead and create a function called create_model() to return a Sequential model.
from tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Densedef create_model(): model = Sequential([ Dense(64, activation='relu', input_shape=(4,)), Dense(128, activation='relu'), Dense(128, activation='relu'), Dense(128, activation='relu'), Dense(64, activation='relu'), Dense(64, activation='relu'), Dense(64, activation='relu'), Dense(3, activation='softmax') ]) return model
Notices that
The first layer (also known as the input layer) has the input_shape to set the input size (4,)
The input layer has 64 units, followed by 3 dense layers, each with 128 units. Then there are further 3 dense layers, each with 64 units. All these layers use the ReLU activation function.
The output Dense layer has 3 units and the softmax activation function.
By running
model = create_model()model.summary()
Should print out the model summary.
In order to train a model, we first have to configure our model using compile() and pass the following arguments:
Use Adam (adam) optimization algorithm as the optimizer
Use categorical cross-entropy loss function (categorical_crossentropy) for our multiple-class classification problem
For simplicity, use accuracy as our evaluation metrics to evaluate the model during training and testing.
model.compile( optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
After that, we can call model.fit() to fit our model to the training data.
history = model.fit( X_train, y_train, epochs=200, validation_split=0.25, batch_size=40, verbose=2)
If all runs smoothly, we should get an output like below
Train on 90 samples, validate on 30 samplesEpoch 1/20090/90 - 1s - loss: 1.0939 - accuracy: 0.4333 - val_loss: 1.0675 - val_accuracy: 0.5333Epoch 2/20090/90 - 0s - loss: 1.0553 - accuracy: 0.6556 - val_loss: 1.0160 - val_accuracy: 0.7000............Epoch 200/20090/90 - 0s - loss: 0.0624 - accuracy: 0.9778 - val_loss: 0.1874 - val_accuracy: 0.9333
Once training is complete, it’s time to see if the model is any good with Model Evaluation. The Model Evaluation typically involves
Plot the progress on loss and accuracy metricsTest our model against data that has never been used for training. This is where the test dataset X_test that we set aside earlier come to play.
Plot the progress on loss and accuracy metrics
Test our model against data that has never been used for training. This is where the test dataset X_test that we set aside earlier come to play.
Let’s create a function plot_metric() for plotting metrics.
%matplotlib inline%config InlineBackend.figure_format = 'svg'def plot_metric(history, metric): train_metrics = history.history[metric] val_metrics = history.history['val_'+metric] epochs = range(1, len(train_metrics) + 1) plt.plot(epochs, train_metrics) plt.plot(epochs, val_metrics) plt.title('Training and validation '+ metric) plt.xlabel("Epochs") plt.ylabel(metric) plt.legend(["train_"+metric, 'val_'+metric]) plt.show()
By running plot_metric(history, 'accuracy') to plot the progress on accuracy.
By running plot_metric(history, 'loss') to plot the progress on loss.
From the above graph, we can see that the model has overfitted the training data, so it outperforms the validation set.
To evaluate the model on the test set
# Evaluate the model on the test setmodel.evaluate(X_test, y_test, verbose=2)
And we should get an output like below
30/1 - 0s - loss: 0.0137 - accuracy: 1.0000[0.01365612167865038, 1.0]
First, let’s import Dropout and L2 regularization from TensorFlow Keras package
from tensorflow.keras.layers import Dropoutfrom tensorflow.keras.regularizers import l2
Then, we create a function called create_regularized_model() and it will return a model similar to the one we built before. But, this time we will add L2 regularization and Dropout layers, so this function takes 2 arguments: a L2 regularization factor and a Dropout rate.
Let’s add L2 regularization in all layers except the output layer [1].
Let’s add Dropout layer between every two dense layers.
def create_regularized_model(factor, rate): model = Sequential([ Dense(64, kernel_regularizer=l2(factor), activation="relu", input_shape=(4,)), Dropout(rate), Dense(128, kernel_regularizer=l2(factor), activation="relu"), Dropout(rate), Dense(128, kernel_regularizer=l2(factor), activation="relu"), Dropout(rate), Dense(128, kernel_regularizer=l2(factor), activation="relu"), Dropout(rate), Dense(64, kernel_regularizer=l2(factor), activation="relu"), Dropout(rate), Dense(64, kernel_regularizer=l2(factor), activation="relu"), Dropout(rate), Dense(64, kernel_regularizer=l2(factor), activation="relu"), Dropout(rate), Dense(3, activation='softmax') ]) return model
Let’s create the model with arguments L2 factor 0.0001 and Dropout rate 0.3
model = create_regularized_model(1e-5, 0.3)model.summary()
The regularized model can be trained just like the first model we built.
# First configure model using model.compile()model.compile( optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])# Then, train the model with fit()history = model.fit( X_train, y_train, epochs=200, validation_split=0.25, batch_size=40, verbose=2)
If all runs smoothly, we should get an output like below
Train on 90 samples, validate on 30 samplesEpoch 1/20090/90 - 2s - loss: 1.0855 - accuracy: 0.3333 - val_loss: 1.0873 - val_accuracy: 0.3000Epoch 2/20090/90 - 0s - loss: 1.0499 - accuracy: 0.3778 - val_loss: 1.0773 - val_accuracy: 0.3000............Epoch 200/20090/90 - 0s - loss: 0.1073 - accuracy: 0.9556 - val_loss: 0.1766 - val_accuracy: 0.9000
Now, let’s plot the progress on loss
plot_metric(history, 'loss')
From the graph, we can see that the overfitting it not completely fixed, but there is a significant improvement when we compare it to the unregularized model.
And finally, to evaluate the model on the test set
model.evaluate(X_test, y_test, verbose=2)
Should output something like
30/1 - 0s - loss: 0.0602 - accuracy: 0.9667[0.06016349419951439, 0.96666664]
Thanks for reading.
Please checkout the notebook on my Github for the source code.
Stay tuned if you are interested in the practical aspect of machine learning.
[1] Keras Layer weight regularizers | [
{
"code": null,
"e": 350,
"s": 171,
"text": "In this article, we will focus on incorporating regularization into our machine learning model and look at an example of how we do this in practice with Keras and TensorFlow 2.0."
},
{
"code": null,
"e": 464,
"s": 350,
"text": "Turns out many people are afraid of Maths, especially beginners and people changing career paths to data science."
},
{
"code": null,
"e": 682,
"s": 464,
"text": "Let’s avoid Maths and try to explain regularization in a more gentle way. If you are looking for a complete explanation (with a lot of math expressions) of regularisation, you might find the following articles useful:"
},
{
"code": null,
"e": 717,
"s": 682,
"text": "Regularization in Machine Learning"
},
{
"code": null,
"e": 774,
"s": 717,
"text": "Regularization: an important concept in Machine Learning"
},
{
"code": null,
"e": 1100,
"s": 774,
"text": "Regularization is a technique to combat the overfitting issue in machine learning. Overfitting, also known as High Variance, refers to a model that learns the training data too well but fail to generalize to new data. For example, the green line below is an overfitted model and the black line represents a regularized model."
},
{
"code": null,
"e": 1445,
"s": 1100,
"text": "Overfitting can be diagnosed by plotting training and validation loss. For example, in the below graph, training error is shown in blue, validation error in red, both as a function of the number of training epochs. If the validation error increases while the training error steadily decreases, then a situation of overfitting may have occurred."
},
{
"code": null,
"e": 1618,
"s": 1445,
"text": "Once overfitting is diagnosed, it is time to try different regularization techniques and parameters to see if they help. The most widely used regularization techniques are:"
},
{
"code": null,
"e": 1898,
"s": 1618,
"text": "L1 regularization adds “absolute value of magnitude” as penalty term to the loss function. Some people say L1 can help with compressing the model. But in practice, L1 regularization makes your model sparse, helps only a little bit. L2 regularization is just used much more often."
},
{
"code": null,
"e": 2047,
"s": 1898,
"text": "L2 regularization (also known as weight decay) adds “squared magnitude” as penalty term to the loss function and it is used much more often than L1."
},
{
"code": null,
"e": 2168,
"s": 2047,
"text": "Dropout is widely used regularization technique in deep learning. It randomly shuts down some neurons in each iteration."
},
{
"code": null,
"e": 2269,
"s": 2168,
"text": "Data Augmentation adds extra fake training data. More training also helps with reducing overfitting."
},
{
"code": null,
"e": 2405,
"s": 2269,
"text": "Early Stopping is another widely used regularization technique in deep learning. It stops training when generalization error increases."
},
{
"code": null,
"e": 2538,
"s": 2405,
"text": "In the following article, we are going to incorporate L2 regularization and Dropout to reduce overfitting of a neural network model."
},
{
"code": null,
"e": 2589,
"s": 2538,
"text": "In order to run this tutorial, you need to install"
},
{
"code": null,
"e": 2637,
"s": 2589,
"text": "TensorFlow 2, numpy, pandas, sklean, matplotlib"
},
{
"code": null,
"e": 2799,
"s": 2637,
"text": "They can all be installed directly vis PyPI and I strongly recommend to create a new Virtual Environment. For a tutorial on creating a Python virtual environment"
},
{
"code": null,
"e": 2876,
"s": 2799,
"text": "Create Virtual Environment using “virtualenv” and add it to Jupyter Notebook"
},
{
"code": null,
"e": 2948,
"s": 2876,
"text": "Create Virtual Environment using “conda” and add it to Jupyter Notebook"
},
{
"code": null,
"e": 3089,
"s": 2948,
"text": "This is a step by step tutorial and all instructions are in this article. For source code, please check out my Github machine learning repo."
},
{
"code": null,
"e": 3337,
"s": 3089,
"text": "This tutorial uses the Anderson Iris flower (iris) dataset for demonstration. The dataset contains a set of 150 records under five attributes: sepal length, sepal width, petal length, petal width, and class (known as target from sklearn datasets)."
},
{
"code": null,
"e": 3474,
"s": 3337,
"text": "First, let’s import the libraries and obtain iris dataset from scikit-learn library. You can also download it from the UCI Iris dataset."
},
{
"code": null,
"e": 3674,
"s": 3474,
"text": "import tensorflow as tfimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.datasets import load_irisfrom sklearn.model_selection import train_test_splitiris = load_iris()"
},
{
"code": null,
"e": 3742,
"s": 3674,
"text": "For the purpose of exploring data, let’s load data into a DataFrame"
},
{
"code": null,
"e": 4029,
"s": 3742,
"text": "# Load data into a DataFramedf = pd.DataFrame(iris.data, columns=iris.feature_names)# Convert datatype to floatdf = df.astype(float)# append \"target\" and name it \"label\"df['label'] = iris.target# Use string label insteaddf['label'] = df.label.replace(dict(enumerate(iris.target_names)))"
},
{
"code": null,
"e": 4064,
"s": 4029,
"text": "And the df should look like below:"
},
{
"code": null,
"e": 4256,
"s": 4064,
"text": "We notice the label column is a categorical feature and will need to convert it to one-hot encoding. Otherwise, our machine learning algorithm won’t be able to directly take in that as input."
},
{
"code": null,
"e": 4426,
"s": 4256,
"text": "# label -> one-hot encodinglabel = pd.get_dummies(df['label'], prefix='label')df = pd.concat([df, label], axis=1)# drop old labeldf.drop(['label'], axis=1, inplace=True)"
},
{
"code": null,
"e": 4456,
"s": 4426,
"text": "Now, the df should look like:"
},
{
"code": null,
"e": 4603,
"s": 4456,
"text": "Next, let’s create X and y. Keras and TensorFlow 2.0 only take in Numpy array as inputs, so we will have to convert DataFrame back to Numpy array."
},
{
"code": null,
"e": 4875,
"s": 4603,
"text": "# Creating X and yX = df[['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']]# Convert DataFrame into np arrayX = np.asarray(X)y = df[['label_setosa', 'label_versicolor', 'label_virginica']]# Convert DataFrame into np arrayy = np.asarray(y)"
},
{
"code": null,
"e": 5001,
"s": 4875,
"text": "Finally, let’s split the dataset into a training set (80%)and a test set (20%) using train_test_split() from sklearn library."
},
{
"code": null,
"e": 5079,
"s": 5001,
"text": "X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.20)"
},
{
"code": null,
"e": 5143,
"s": 5079,
"text": "Great! our data is ready for building a Machine Learning model."
},
{
"code": null,
"e": 5269,
"s": 5143,
"text": "Before applying regularization, let’s build a neural network without regularization and take a look at the overfitting issue."
},
{
"code": null,
"e": 5495,
"s": 5269,
"text": "There are 3 ways to create a machine learning model with Keras and Tensorflow 2. Since we are building a simple fully connected Neural Network and for simplicity, let’s use the easiest way: Sequential Model with Sequential()."
},
{
"code": null,
"e": 5584,
"s": 5495,
"text": "Let’s go ahead and create a function called create_model() to return a Sequential model."
},
{
"code": null,
"e": 6056,
"s": 5584,
"text": "from tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Densedef create_model(): model = Sequential([ Dense(64, activation='relu', input_shape=(4,)), Dense(128, activation='relu'), Dense(128, activation='relu'), Dense(128, activation='relu'), Dense(64, activation='relu'), Dense(64, activation='relu'), Dense(64, activation='relu'), Dense(3, activation='softmax') ]) return model"
},
{
"code": null,
"e": 6069,
"s": 6056,
"text": "Notices that"
},
{
"code": null,
"e": 6164,
"s": 6069,
"text": "The first layer (also known as the input layer) has the input_shape to set the input size (4,)"
},
{
"code": null,
"e": 6353,
"s": 6164,
"text": "The input layer has 64 units, followed by 3 dense layers, each with 128 units. Then there are further 3 dense layers, each with 64 units. All these layers use the ReLU activation function."
},
{
"code": null,
"e": 6425,
"s": 6353,
"text": "The output Dense layer has 3 units and the softmax activation function."
},
{
"code": null,
"e": 6436,
"s": 6425,
"text": "By running"
},
{
"code": null,
"e": 6474,
"s": 6436,
"text": "model = create_model()model.summary()"
},
{
"code": null,
"e": 6510,
"s": 6474,
"text": "Should print out the model summary."
},
{
"code": null,
"e": 6624,
"s": 6510,
"text": "In order to train a model, we first have to configure our model using compile() and pass the following arguments:"
},
{
"code": null,
"e": 6680,
"s": 6624,
"text": "Use Adam (adam) optimization algorithm as the optimizer"
},
{
"code": null,
"e": 6797,
"s": 6680,
"text": "Use categorical cross-entropy loss function (categorical_crossentropy) for our multiple-class classification problem"
},
{
"code": null,
"e": 6903,
"s": 6797,
"text": "For simplicity, use accuracy as our evaluation metrics to evaluate the model during training and testing."
},
{
"code": null,
"e": 7002,
"s": 6903,
"text": "model.compile( optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])"
},
{
"code": null,
"e": 7077,
"s": 7002,
"text": "After that, we can call model.fit() to fit our model to the training data."
},
{
"code": null,
"e": 7200,
"s": 7077,
"text": "history = model.fit( X_train, y_train, epochs=200, validation_split=0.25, batch_size=40, verbose=2)"
},
{
"code": null,
"e": 7257,
"s": 7200,
"text": "If all runs smoothly, we should get an output like below"
},
{
"code": null,
"e": 7606,
"s": 7257,
"text": "Train on 90 samples, validate on 30 samplesEpoch 1/20090/90 - 1s - loss: 1.0939 - accuracy: 0.4333 - val_loss: 1.0675 - val_accuracy: 0.5333Epoch 2/20090/90 - 0s - loss: 1.0553 - accuracy: 0.6556 - val_loss: 1.0160 - val_accuracy: 0.7000............Epoch 200/20090/90 - 0s - loss: 0.0624 - accuracy: 0.9778 - val_loss: 0.1874 - val_accuracy: 0.9333"
},
{
"code": null,
"e": 7738,
"s": 7606,
"text": "Once training is complete, it’s time to see if the model is any good with Model Evaluation. The Model Evaluation typically involves"
},
{
"code": null,
"e": 7929,
"s": 7738,
"text": "Plot the progress on loss and accuracy metricsTest our model against data that has never been used for training. This is where the test dataset X_test that we set aside earlier come to play."
},
{
"code": null,
"e": 7976,
"s": 7929,
"text": "Plot the progress on loss and accuracy metrics"
},
{
"code": null,
"e": 8121,
"s": 7976,
"text": "Test our model against data that has never been used for training. This is where the test dataset X_test that we set aside earlier come to play."
},
{
"code": null,
"e": 8181,
"s": 8121,
"text": "Let’s create a function plot_metric() for plotting metrics."
},
{
"code": null,
"e": 8637,
"s": 8181,
"text": "%matplotlib inline%config InlineBackend.figure_format = 'svg'def plot_metric(history, metric): train_metrics = history.history[metric] val_metrics = history.history['val_'+metric] epochs = range(1, len(train_metrics) + 1) plt.plot(epochs, train_metrics) plt.plot(epochs, val_metrics) plt.title('Training and validation '+ metric) plt.xlabel(\"Epochs\") plt.ylabel(metric) plt.legend([\"train_\"+metric, 'val_'+metric]) plt.show()"
},
{
"code": null,
"e": 8715,
"s": 8637,
"text": "By running plot_metric(history, 'accuracy') to plot the progress on accuracy."
},
{
"code": null,
"e": 8785,
"s": 8715,
"text": "By running plot_metric(history, 'loss') to plot the progress on loss."
},
{
"code": null,
"e": 8905,
"s": 8785,
"text": "From the above graph, we can see that the model has overfitted the training data, so it outperforms the validation set."
},
{
"code": null,
"e": 8943,
"s": 8905,
"text": "To evaluate the model on the test set"
},
{
"code": null,
"e": 9021,
"s": 8943,
"text": "# Evaluate the model on the test setmodel.evaluate(X_test, y_test, verbose=2)"
},
{
"code": null,
"e": 9060,
"s": 9021,
"text": "And we should get an output like below"
},
{
"code": null,
"e": 9130,
"s": 9060,
"text": "30/1 - 0s - loss: 0.0137 - accuracy: 1.0000[0.01365612167865038, 1.0]"
},
{
"code": null,
"e": 9210,
"s": 9130,
"text": "First, let’s import Dropout and L2 regularization from TensorFlow Keras package"
},
{
"code": null,
"e": 9298,
"s": 9210,
"text": "from tensorflow.keras.layers import Dropoutfrom tensorflow.keras.regularizers import l2"
},
{
"code": null,
"e": 9570,
"s": 9298,
"text": "Then, we create a function called create_regularized_model() and it will return a model similar to the one we built before. But, this time we will add L2 regularization and Dropout layers, so this function takes 2 arguments: a L2 regularization factor and a Dropout rate."
},
{
"code": null,
"e": 9641,
"s": 9570,
"text": "Let’s add L2 regularization in all layers except the output layer [1]."
},
{
"code": null,
"e": 9697,
"s": 9641,
"text": "Let’s add Dropout layer between every two dense layers."
},
{
"code": null,
"e": 10476,
"s": 9697,
"text": "def create_regularized_model(factor, rate): model = Sequential([ Dense(64, kernel_regularizer=l2(factor), activation=\"relu\", input_shape=(4,)), Dropout(rate), Dense(128, kernel_regularizer=l2(factor), activation=\"relu\"), Dropout(rate), Dense(128, kernel_regularizer=l2(factor), activation=\"relu\"), Dropout(rate), Dense(128, kernel_regularizer=l2(factor), activation=\"relu\"), Dropout(rate), Dense(64, kernel_regularizer=l2(factor), activation=\"relu\"), Dropout(rate), Dense(64, kernel_regularizer=l2(factor), activation=\"relu\"), Dropout(rate), Dense(64, kernel_regularizer=l2(factor), activation=\"relu\"), Dropout(rate), Dense(3, activation='softmax') ]) return model"
},
{
"code": null,
"e": 10552,
"s": 10476,
"text": "Let’s create the model with arguments L2 factor 0.0001 and Dropout rate 0.3"
},
{
"code": null,
"e": 10611,
"s": 10552,
"text": "model = create_regularized_model(1e-5, 0.3)model.summary()"
},
{
"code": null,
"e": 10684,
"s": 10611,
"text": "The regularized model can be trained just like the first model we built."
},
{
"code": null,
"e": 10984,
"s": 10684,
"text": "# First configure model using model.compile()model.compile( optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])# Then, train the model with fit()history = model.fit( X_train, y_train, epochs=200, validation_split=0.25, batch_size=40, verbose=2)"
},
{
"code": null,
"e": 11041,
"s": 10984,
"text": "If all runs smoothly, we should get an output like below"
},
{
"code": null,
"e": 11390,
"s": 11041,
"text": "Train on 90 samples, validate on 30 samplesEpoch 1/20090/90 - 2s - loss: 1.0855 - accuracy: 0.3333 - val_loss: 1.0873 - val_accuracy: 0.3000Epoch 2/20090/90 - 0s - loss: 1.0499 - accuracy: 0.3778 - val_loss: 1.0773 - val_accuracy: 0.3000............Epoch 200/20090/90 - 0s - loss: 0.1073 - accuracy: 0.9556 - val_loss: 0.1766 - val_accuracy: 0.9000"
},
{
"code": null,
"e": 11427,
"s": 11390,
"text": "Now, let’s plot the progress on loss"
},
{
"code": null,
"e": 11456,
"s": 11427,
"text": "plot_metric(history, 'loss')"
},
{
"code": null,
"e": 11615,
"s": 11456,
"text": "From the graph, we can see that the overfitting it not completely fixed, but there is a significant improvement when we compare it to the unregularized model."
},
{
"code": null,
"e": 11666,
"s": 11615,
"text": "And finally, to evaluate the model on the test set"
},
{
"code": null,
"e": 11708,
"s": 11666,
"text": "model.evaluate(X_test, y_test, verbose=2)"
},
{
"code": null,
"e": 11737,
"s": 11708,
"text": "Should output something like"
},
{
"code": null,
"e": 11814,
"s": 11737,
"text": "30/1 - 0s - loss: 0.0602 - accuracy: 0.9667[0.06016349419951439, 0.96666664]"
},
{
"code": null,
"e": 11834,
"s": 11814,
"text": "Thanks for reading."
},
{
"code": null,
"e": 11897,
"s": 11834,
"text": "Please checkout the notebook on my Github for the source code."
},
{
"code": null,
"e": 11975,
"s": 11897,
"text": "Stay tuned if you are interested in the practical aspect of machine learning."
}
] |
Dart Programming - Loops | At times, certain instructions require repeated execution. Loops are an ideal way to do the same. A loop represents a set of instructions that must be repeated. In a loop’s context, a repetition is termed as an iteration.
The following figure illustrates the classification of loops −
Let’s start the discussion with Definite Loops. A loop whose number of iterations are definite/fixed is termed as a definite loop.
The for loop is an implementation of a definite loop. The for loop executes the code block for a specified number of times. It can be used to iterate over a fixed set of values, such as an array
The for...in loop is used to loop through an object's properties.
Moving on, let’s now discuss the indefinite loops. An indefinite loop is used when the number of iterations in a loop is indeterminate or unknown. Indefinite loops can be implemented using −
The while loop executes the instructions each time the condition specified evaluates to true. In other words, the loop evaluates the condition before the block of code is executed.
The do...while loop is similar to the while loop except that the do...while loop doesn’t evaluate the condition for the first time the loop executes.
Let us now move on and discuss the Loop Control Statements of Dart.
The break statement is used to take the control out of a construct. Using break in a loop causes the program to exit the loop. Following is an example of the break statement.
The continue statement skips the subsequent statements in the current iteration and takes the control back to the beginning of the loop.
A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. A label can be used with break and continue to control the flow more precisely.
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 an associated loop.
void main() {
outerloop: // This is the label name
for (var i = 0; i < 5; i++) {
print("Innerloop: ${i}");
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
print("Innerloop: ${j}");
}
}
}
The following output is displayed on successful execution of the above code.
Innerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Innerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Innerloop: 2
Innerloop: 3
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Innerloop: 4
void main() {
outerloop: // This is the label name
for (var i = 0; i < 3; i++) {
print("Outerloop:${i}");
for (var j = 0; j < 5; j++) {
if (j == 3){
continue outerloop;
}
print("Innerloop:${j}");
}
}
}
The following output is displayed on successful execution of the above code.
Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 2
Innerloop: 0
Innerloop: 1
Innerloop: 2
44 Lectures
4.5 hours
Sriyank Siddhartha
34 Lectures
4 hours
Sriyank Siddhartha
69 Lectures
4 hours
Frahaan Hussain
117 Lectures
10 hours
Frahaan Hussain
22 Lectures
1.5 hours
Pranjal Srivastava
34 Lectures
3 hours
Pranjal Srivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2747,
"s": 2525,
"text": "At times, certain instructions require repeated execution. Loops are an ideal way to do the same. A loop represents a set of instructions that must be repeated. In a loop’s context, a repetition is termed as an iteration."
},
{
"code": null,
"e": 2810,
"s": 2747,
"text": "The following figure illustrates the classification of loops −"
},
{
"code": null,
"e": 2941,
"s": 2810,
"text": "Let’s start the discussion with Definite Loops. A loop whose number of iterations are definite/fixed is termed as a definite loop."
},
{
"code": null,
"e": 3136,
"s": 2941,
"text": "The for loop is an implementation of a definite loop. The for loop executes the code block for a specified number of times. It can be used to iterate over a fixed set of values, such as an array"
},
{
"code": null,
"e": 3202,
"s": 3136,
"text": "The for...in loop is used to loop through an object's properties."
},
{
"code": null,
"e": 3393,
"s": 3202,
"text": "Moving on, let’s now discuss the indefinite loops. An indefinite loop is used when the number of iterations in a loop is indeterminate or unknown. Indefinite loops can be implemented using −"
},
{
"code": null,
"e": 3574,
"s": 3393,
"text": "The while loop executes the instructions each time the condition specified evaluates to true. In other words, the loop evaluates the condition before the block of code is executed."
},
{
"code": null,
"e": 3724,
"s": 3574,
"text": "The do...while loop is similar to the while loop except that the do...while loop doesn’t evaluate the condition for the first time the loop executes."
},
{
"code": null,
"e": 3792,
"s": 3724,
"text": "Let us now move on and discuss the Loop Control Statements of Dart."
},
{
"code": null,
"e": 3967,
"s": 3792,
"text": "The break statement is used to take the control out of a construct. Using break in a loop causes the program to exit the loop. Following is an example of the break statement."
},
{
"code": null,
"e": 4104,
"s": 3967,
"text": "The continue statement skips the subsequent statements in the current iteration and takes the control back to the beginning of the loop."
},
{
"code": null,
"e": 4291,
"s": 4104,
"text": "A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. A label can be used with break and continue to control the flow more precisely."
},
{
"code": null,
"e": 4477,
"s": 4291,
"text": "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 an associated loop."
},
{
"code": null,
"e": 4958,
"s": 4477,
"text": "void main() { \n outerloop: // This is the label name \n \n for (var i = 0; i < 5; i++) { \n print(\"Innerloop: ${i}\"); \n innerloop: \n \n for (var j = 0; j < 5; j++) { \n if (j > 3 ) break ; \n \n // Quit the innermost loop \n if (i == 2) break innerloop; \n \n // Do the same thing \n if (i == 4) break outerloop; \n \n // Quit the outer loop \n print(\"Innerloop: ${j}\"); \n } \n } \n}"
},
{
"code": null,
"e": 5035,
"s": 4958,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 5257,
"s": 5035,
"text": "Innerloop: 0\nInnerloop: 0\nInnerloop: 1\nInnerloop: 2\nInnerloop: 3\nInnerloop: 1\nInnerloop: 0\nInnerloop: 1\nInnerloop: 2\nInnerloop: 3\nInnerloop: 2\nInnerloop: 3\nInnerloop: 0\nInnerloop: 1\nInnerloop: 2\nInnerloop: 3\nInnerloop: 4\n"
},
{
"code": null,
"e": 5547,
"s": 5257,
"text": "void main() { \n outerloop: // This is the label name \n \n for (var i = 0; i < 3; i++) { \n print(\"Outerloop:${i}\"); \n \n for (var j = 0; j < 5; j++) { \n if (j == 3){ \n continue outerloop; \n } \n print(\"Innerloop:${j}\"); \n } \n } \n}"
},
{
"code": null,
"e": 5624,
"s": 5547,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 5795,
"s": 5624,
"text": "Outerloop: 0 \nInnerloop: 0 \nInnerloop: 1 \nInnerloop: 2 \n\nOuterloop: 1 \nInnerloop: 0 \nInnerloop: 1 \nInnerloop: 2 \n\nOuterloop: 2 \nInnerloop: 0 \nInnerloop: 1 \nInnerloop: 2 \n"
},
{
"code": null,
"e": 5830,
"s": 5795,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5850,
"s": 5830,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 5883,
"s": 5850,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5903,
"s": 5883,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 5936,
"s": 5903,
"text": "\n 69 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5953,
"s": 5936,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5988,
"s": 5953,
"text": "\n 117 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 6005,
"s": 5988,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6040,
"s": 6005,
"text": "\n 22 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6060,
"s": 6040,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 6093,
"s": 6060,
"text": "\n 34 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6113,
"s": 6093,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 6120,
"s": 6113,
"text": " Print"
},
{
"code": null,
"e": 6131,
"s": 6120,
"text": " Add Notes"
}
] |
Java.util.concurrent.Phaser class in Java with Examples | 19 Feb, 2021
Phaser’s primary purpose is to enable synchronization of threads that represent one or more phases of activity. It lets us define a synchronization object that waits until a specific phase has been completed. It then advances to the next phase until that phase concludes. It can also be used to synchronize a single phase, and in that regard, it acts much like a CyclicBarrier.
Class Hierarchy
java.lang.Object
? java.util.concurrent
? Class Phaser
Syntax
public class Phaser
extends Object
Constructors:
Phaser() – This creates a phaser with initially zero registered parties. A thread can only use this phaser after registering for it.
public Phaser()
Phaser(int parties) – This creates a phaser that requires parties number of threads to advance to the next phase.
public Phaser(int parties)
throws IllegalArgumentException
Phaser(Phaser parent) – This specifies a parent phaser for the new object. The number of registered parties is set to zero.
public Phaser(Phaser parent)
Phaser(Phaser parent, int parties) – This specifies a parent phaser for the newly created object and the number of parties required to advance to the next phase.
public Phaser(Phaser parent, int parties)
throws IllegalArgumentException
Example1:
Note: Output may vary with each run.
Java
// Java program to show Phaser Class import java.util.concurrent.Phaser; // A thread of execution that uses a phaser.class MyThread implements Runnable { Phaser phaser; String title; public MyThread(Phaser phaser, String title) { this.phaser = phaser; this.title = title; phaser.register(); new Thread(this).start(); } @Override public void run() { System.out.println("Thread: " + title + " Phase Zero Started"); phaser.arriveAndAwaitAdvance(); // Stop execution to prevent jumbled output try { Thread.sleep(10); } catch (InterruptedException e) { System.out.println(e); } System.out.println("Thread: " + title + " Phase One Started"); phaser.arriveAndAwaitAdvance(); // Stop execution to prevent jumbled output try { Thread.sleep(10); } catch (InterruptedException e) { System.out.println(e); } System.out.println("Thread: " + title + " Phase Two Started"); phaser.arriveAndDeregister(); }} public class PhaserExample { public static void main(String[] args) { Phaser phaser = new Phaser(); phaser.register(); int currentPhase; System.out.println("Starting"); new MyThread(phaser, "A"); new MyThread(phaser, "B"); new MyThread(phaser, "C"); // Wait for all threads to complete phase Zero. currentPhase = phaser.getPhase(); phaser.arriveAndAwaitAdvance(); System.out.println("Phase " + currentPhase + " Complete"); System.out.println("Phase Zero Ended"); // Wait for all threads to complete phase One. currentPhase = phaser.getPhase(); phaser.arriveAndAwaitAdvance(); System.out.println("Phase " + currentPhase + " Complete"); System.out.println("Phase One Ended"); currentPhase = phaser.getPhase(); phaser.arriveAndAwaitAdvance(); System.out.println("Phase " + currentPhase + " Complete"); System.out.println("Phase Two Ended"); // Deregister the main thread. phaser.arriveAndDeregister(); if (phaser.isTerminated()) { System.out.println("Phaser is terminated"); } }}
Starting
Thread: B Phase Zero Started
Thread: A Phase Zero Started
Thread: C Phase Zero Started
Thread: A Phase One Started
Thread: B Phase One Started
Thread: C Phase One Started
Phase 0 Complete
Phase Zero Ended
Phase 1 Complete
Phase One Ended
Thread: C Phase Two Started
Thread: A Phase Two Started
Thread: B Phase Two Started
Phase 2 Complete
Phase Two Ended
Phaser is terminated
Example2:
Java
// Java program to show Phaser Class import java.util.concurrent.Phaser; // A thread of execution that uses a phaser.class MyThread implements Runnable { Phaser phaser; String title; public MyThread(Phaser phaser, String title) { this.phaser = phaser; this.title = title; phaser.register(); new Thread(this).start(); } @Override public void run() { System.out.println("Thread: " + title + " Phase Zero Started"); phaser.arriveAndAwaitAdvance(); // Stop execution to prevent jumbled output try { Thread.sleep(10); } catch (InterruptedException e) { System.out.println(e); } System.out.println("Thread: " + title + " Phase One Started"); phaser.arriveAndAwaitAdvance(); // Stop execution to prevent jumbled output try { Thread.sleep(10); } catch (InterruptedException e) { System.out.println(e); } System.out.println("Thread: " + title + " Phase Two Started"); phaser.arriveAndDeregister(); }} public class PhaserExample { public static void main(String[] args) { Phaser phaser = new Phaser(); phaser.register(); int currentPhase; System.out.println("Starting"); new MyThread(phaser, "A"); new MyThread(phaser, "B"); new MyThread(phaser, "C"); // Wait for all threads to complete phase Zero. currentPhase = phaser.getPhase(); phaser.arriveAndAwaitAdvance(); System.out.println("Phase " + currentPhase + " Complete"); System.out.println("Phase Zero Ended"); // Wait for all threads to complete phase One. currentPhase = phaser.getPhase(); phaser.arriveAndAwaitAdvance(); System.out.println("Phase " + currentPhase + " Complete"); System.out.println("Phase One Ended"); currentPhase = phaser.getPhase(); phaser.arriveAndAwaitAdvance(); System.out.println("Phase " + currentPhase + " Complete"); System.out.println("Phase Two Ended"); // Deregister the main thread. phaser.arriveAndDeregister(); if (phaser.isTerminated()) { System.out.println("Phaser is terminated"); } }}
Starting
Thread: C Phase Zero Started
Thread: A Phase Zero Started
Thread: B Phase Zero Started
Thread: B Phase One Started
Thread: C Phase One Started
Thread: A Phase One Started
Phase 0 Complete
Phase Zero Ended
Phase 1 Complete
Phase One Ended
Thread: A Phase Two Started
Thread: C Phase Two Started
Thread: B Phase Two Started
Phase 2 Complete
Phase Two Ended
Phaser is terminated
Methods:
int register() – This method is used to register parties after a phaser has been constructed. It returns the phase number of the phase to which it is registered.
public int register()
throws IllegalArgumentException
int arrive() – This method signals that a thread has completed some portion of the task. It does not suspend the execution of the calling thread. It returns the current phase number or a negative value if the phaser has been terminated.
public int arrive()
throws IllegalStateException
int arriveAndDeregister() – This method enables a thread to arrive at a phase and deregister itself, without waiting for other threads to arrive. It returns the current phase number or a negative value if the phaser has been terminated.
public int arriveAndDeregister()
throws IllegalStateException
int arriveAndAwaitAdvance() – This method suspends the execution of the thread at a phase, to wait for other threads. It returns the current phase number or a negative value if the phaser has been terminated.
public int arriveAndAwaitAdvance()
throws IllegalStateException
final int getPhase() – This method returns the current phase number. A negative value is returned if the invoking phasers terminated.
public final int getPhase()
boolean onAdvance(int phase, int parties) – This method helps in defining how a phase advancement should occur. To do this, the user must override this method. To terminate the phaser, onAdvance() method returns true, otherwise, it returns false;
protected boolean onAdvance(int phase, int parties)
Example to demonstrate the methods of Phaser class – where the method is overridden so that the phaser executes only a specified number of phases.
Java
// Java program to demonstrate// the methods of Phaser class import java.util.concurrent.Phaser; // Extend MyPhaser and override onAdvance()// so that only specific number of phases// are executedclass MyPhaser extends Phaser { int numPhases; MyPhaser(int parties, int phaseCount) { super(parties); numPhases = phaseCount - 1; } @Override protected boolean onAdvance(int phase, int registeredParties) { System.out.println("Phase " + phase + " completed.\n"); // If all phases have completed, return true. if (phase == numPhases || registeredParties == 0) { return true; } // otherwise, return false return false; }} // A thread of execution that uses a phaserclass ModifiedThread implements Runnable { Phaser phsr; String name; ModifiedThread(Phaser p, String n) { phsr = p; name = n; phsr.register(); new Thread(this).start(); } @Override public void run() { while (!phsr.isTerminated()) { System.out.println("Thread " + name + " Beginning Phase " + phsr.getPhase()); phsr.arriveAndAwaitAdvance(); try { Thread.sleep(10); } catch (InterruptedException e) { System.out.println(e); } } }} public class PhaserExample2 { public static void main(String[] args) { MyPhaser phsr = new MyPhaser(1, 4); System.out.println("Starting"); new ModifiedThread(phsr, "A"); new ModifiedThread(phsr, "B"); new ModifiedThread(phsr, "C"); while (!phsr.isTerminated()) { phsr.arriveAndAwaitAdvance(); } System.out.println("The phaser is terminated\n"); }}
Starting
Thread B Beginning Phase 0
Thread C Beginning Phase 0
Thread A Beginning Phase 0
Phase 0 completed.
Thread A Beginning Phase 1
Thread B Beginning Phase 1
Thread C Beginning Phase 1
Phase 1 completed.
Thread C Beginning Phase 2
Thread A Beginning Phase 2
Thread B Beginning Phase 2
Phase 2 completed.
Thread A Beginning Phase 3
Thread B Beginning Phase 3
Thread C Beginning Phase 3
Phase 3 completed.
The phaser is terminated
Reference: https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/Phaser.html
ramandeepm007
Java - util package
Java-concurrent-package
Java-Functions
Java-Phaser
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
List Interface in Java with Examples
Strings in Java
Different ways of Reading a text file in Java
Reverse an array in Java
How to remove an element from ArrayList in Java?
Checked vs Unchecked Exceptions in Java
ArrayList get(index) Method in Java with Examples
ArrayList to Array Conversion in Java : toArray() Methods
Comparator Interface in Java with Examples
Exceptions in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 430,
"s": 52,
"text": "Phaser’s primary purpose is to enable synchronization of threads that represent one or more phases of activity. It lets us define a synchronization object that waits until a specific phase has been completed. It then advances to the next phase until that phase concludes. It can also be used to synchronize a single phase, and in that regard, it acts much like a CyclicBarrier."
},
{
"code": null,
"e": 448,
"s": 430,
"text": "Class Hierarchy "
},
{
"code": null,
"e": 510,
"s": 448,
"text": "java.lang.Object\n ? java.util.concurrent\n ? Class Phaser "
},
{
"code": null,
"e": 519,
"s": 510,
"text": "Syntax "
},
{
"code": null,
"e": 556,
"s": 519,
"text": "public class Phaser\n extends Object"
},
{
"code": null,
"e": 571,
"s": 556,
"text": "Constructors: "
},
{
"code": null,
"e": 704,
"s": 571,
"text": "Phaser() – This creates a phaser with initially zero registered parties. A thread can only use this phaser after registering for it."
},
{
"code": null,
"e": 720,
"s": 704,
"text": "public Phaser()"
},
{
"code": null,
"e": 834,
"s": 720,
"text": "Phaser(int parties) – This creates a phaser that requires parties number of threads to advance to the next phase."
},
{
"code": null,
"e": 893,
"s": 834,
"text": "public Phaser(int parties)\nthrows IllegalArgumentException"
},
{
"code": null,
"e": 1017,
"s": 893,
"text": "Phaser(Phaser parent) – This specifies a parent phaser for the new object. The number of registered parties is set to zero."
},
{
"code": null,
"e": 1046,
"s": 1017,
"text": "public Phaser(Phaser parent)"
},
{
"code": null,
"e": 1208,
"s": 1046,
"text": "Phaser(Phaser parent, int parties) – This specifies a parent phaser for the newly created object and the number of parties required to advance to the next phase."
},
{
"code": null,
"e": 1282,
"s": 1208,
"text": "public Phaser(Phaser parent, int parties)\nthrows IllegalArgumentException"
},
{
"code": null,
"e": 1293,
"s": 1282,
"text": "Example1: "
},
{
"code": null,
"e": 1332,
"s": 1293,
"text": "Note: Output may vary with each run. "
},
{
"code": null,
"e": 1337,
"s": 1332,
"text": "Java"
},
{
"code": "// Java program to show Phaser Class import java.util.concurrent.Phaser; // A thread of execution that uses a phaser.class MyThread implements Runnable { Phaser phaser; String title; public MyThread(Phaser phaser, String title) { this.phaser = phaser; this.title = title; phaser.register(); new Thread(this).start(); } @Override public void run() { System.out.println(\"Thread: \" + title + \" Phase Zero Started\"); phaser.arriveAndAwaitAdvance(); // Stop execution to prevent jumbled output try { Thread.sleep(10); } catch (InterruptedException e) { System.out.println(e); } System.out.println(\"Thread: \" + title + \" Phase One Started\"); phaser.arriveAndAwaitAdvance(); // Stop execution to prevent jumbled output try { Thread.sleep(10); } catch (InterruptedException e) { System.out.println(e); } System.out.println(\"Thread: \" + title + \" Phase Two Started\"); phaser.arriveAndDeregister(); }} public class PhaserExample { public static void main(String[] args) { Phaser phaser = new Phaser(); phaser.register(); int currentPhase; System.out.println(\"Starting\"); new MyThread(phaser, \"A\"); new MyThread(phaser, \"B\"); new MyThread(phaser, \"C\"); // Wait for all threads to complete phase Zero. currentPhase = phaser.getPhase(); phaser.arriveAndAwaitAdvance(); System.out.println(\"Phase \" + currentPhase + \" Complete\"); System.out.println(\"Phase Zero Ended\"); // Wait for all threads to complete phase One. currentPhase = phaser.getPhase(); phaser.arriveAndAwaitAdvance(); System.out.println(\"Phase \" + currentPhase + \" Complete\"); System.out.println(\"Phase One Ended\"); currentPhase = phaser.getPhase(); phaser.arriveAndAwaitAdvance(); System.out.println(\"Phase \" + currentPhase + \" Complete\"); System.out.println(\"Phase Two Ended\"); // Deregister the main thread. phaser.arriveAndDeregister(); if (phaser.isTerminated()) { System.out.println(\"Phaser is terminated\"); } }}",
"e": 3778,
"s": 1337,
"text": null
},
{
"code": null,
"e": 4164,
"s": 3778,
"text": "Starting\nThread: B Phase Zero Started\nThread: A Phase Zero Started\nThread: C Phase Zero Started\nThread: A Phase One Started\nThread: B Phase One Started\nThread: C Phase One Started\nPhase 0 Complete\nPhase Zero Ended\nPhase 1 Complete\nPhase One Ended\nThread: C Phase Two Started\nThread: A Phase Two Started\nThread: B Phase Two Started\nPhase 2 Complete\nPhase Two Ended\nPhaser is terminated\n"
},
{
"code": null,
"e": 4175,
"s": 4164,
"text": "Example2: "
},
{
"code": null,
"e": 4180,
"s": 4175,
"text": "Java"
},
{
"code": "// Java program to show Phaser Class import java.util.concurrent.Phaser; // A thread of execution that uses a phaser.class MyThread implements Runnable { Phaser phaser; String title; public MyThread(Phaser phaser, String title) { this.phaser = phaser; this.title = title; phaser.register(); new Thread(this).start(); } @Override public void run() { System.out.println(\"Thread: \" + title + \" Phase Zero Started\"); phaser.arriveAndAwaitAdvance(); // Stop execution to prevent jumbled output try { Thread.sleep(10); } catch (InterruptedException e) { System.out.println(e); } System.out.println(\"Thread: \" + title + \" Phase One Started\"); phaser.arriveAndAwaitAdvance(); // Stop execution to prevent jumbled output try { Thread.sleep(10); } catch (InterruptedException e) { System.out.println(e); } System.out.println(\"Thread: \" + title + \" Phase Two Started\"); phaser.arriveAndDeregister(); }} public class PhaserExample { public static void main(String[] args) { Phaser phaser = new Phaser(); phaser.register(); int currentPhase; System.out.println(\"Starting\"); new MyThread(phaser, \"A\"); new MyThread(phaser, \"B\"); new MyThread(phaser, \"C\"); // Wait for all threads to complete phase Zero. currentPhase = phaser.getPhase(); phaser.arriveAndAwaitAdvance(); System.out.println(\"Phase \" + currentPhase + \" Complete\"); System.out.println(\"Phase Zero Ended\"); // Wait for all threads to complete phase One. currentPhase = phaser.getPhase(); phaser.arriveAndAwaitAdvance(); System.out.println(\"Phase \" + currentPhase + \" Complete\"); System.out.println(\"Phase One Ended\"); currentPhase = phaser.getPhase(); phaser.arriveAndAwaitAdvance(); System.out.println(\"Phase \" + currentPhase + \" Complete\"); System.out.println(\"Phase Two Ended\"); // Deregister the main thread. phaser.arriveAndDeregister(); if (phaser.isTerminated()) { System.out.println(\"Phaser is terminated\"); } }}",
"e": 6621,
"s": 4180,
"text": null
},
{
"code": null,
"e": 7007,
"s": 6621,
"text": "Starting\nThread: C Phase Zero Started\nThread: A Phase Zero Started\nThread: B Phase Zero Started\nThread: B Phase One Started\nThread: C Phase One Started\nThread: A Phase One Started\nPhase 0 Complete\nPhase Zero Ended\nPhase 1 Complete\nPhase One Ended\nThread: A Phase Two Started\nThread: C Phase Two Started\nThread: B Phase Two Started\nPhase 2 Complete\nPhase Two Ended\nPhaser is terminated\n"
},
{
"code": null,
"e": 7017,
"s": 7007,
"text": "Methods: "
},
{
"code": null,
"e": 7179,
"s": 7017,
"text": "int register() – This method is used to register parties after a phaser has been constructed. It returns the phase number of the phase to which it is registered."
},
{
"code": null,
"e": 7233,
"s": 7179,
"text": "public int register()\nthrows IllegalArgumentException"
},
{
"code": null,
"e": 7470,
"s": 7233,
"text": "int arrive() – This method signals that a thread has completed some portion of the task. It does not suspend the execution of the calling thread. It returns the current phase number or a negative value if the phaser has been terminated."
},
{
"code": null,
"e": 7519,
"s": 7470,
"text": "public int arrive()\nthrows IllegalStateException"
},
{
"code": null,
"e": 7756,
"s": 7519,
"text": "int arriveAndDeregister() – This method enables a thread to arrive at a phase and deregister itself, without waiting for other threads to arrive. It returns the current phase number or a negative value if the phaser has been terminated."
},
{
"code": null,
"e": 7818,
"s": 7756,
"text": "public int arriveAndDeregister()\nthrows IllegalStateException"
},
{
"code": null,
"e": 8027,
"s": 7818,
"text": "int arriveAndAwaitAdvance() – This method suspends the execution of the thread at a phase, to wait for other threads. It returns the current phase number or a negative value if the phaser has been terminated."
},
{
"code": null,
"e": 8091,
"s": 8027,
"text": "public int arriveAndAwaitAdvance()\nthrows IllegalStateException"
},
{
"code": null,
"e": 8225,
"s": 8091,
"text": "final int getPhase() – This method returns the current phase number. A negative value is returned if the invoking phasers terminated."
},
{
"code": null,
"e": 8254,
"s": 8225,
"text": "public final int getPhase() "
},
{
"code": null,
"e": 8501,
"s": 8254,
"text": "boolean onAdvance(int phase, int parties) – This method helps in defining how a phase advancement should occur. To do this, the user must override this method. To terminate the phaser, onAdvance() method returns true, otherwise, it returns false;"
},
{
"code": null,
"e": 8553,
"s": 8501,
"text": "protected boolean onAdvance(int phase, int parties)"
},
{
"code": null,
"e": 8701,
"s": 8553,
"text": "Example to demonstrate the methods of Phaser class – where the method is overridden so that the phaser executes only a specified number of phases. "
},
{
"code": null,
"e": 8706,
"s": 8701,
"text": "Java"
},
{
"code": "// Java program to demonstrate// the methods of Phaser class import java.util.concurrent.Phaser; // Extend MyPhaser and override onAdvance()// so that only specific number of phases// are executedclass MyPhaser extends Phaser { int numPhases; MyPhaser(int parties, int phaseCount) { super(parties); numPhases = phaseCount - 1; } @Override protected boolean onAdvance(int phase, int registeredParties) { System.out.println(\"Phase \" + phase + \" completed.\\n\"); // If all phases have completed, return true. if (phase == numPhases || registeredParties == 0) { return true; } // otherwise, return false return false; }} // A thread of execution that uses a phaserclass ModifiedThread implements Runnable { Phaser phsr; String name; ModifiedThread(Phaser p, String n) { phsr = p; name = n; phsr.register(); new Thread(this).start(); } @Override public void run() { while (!phsr.isTerminated()) { System.out.println(\"Thread \" + name + \" Beginning Phase \" + phsr.getPhase()); phsr.arriveAndAwaitAdvance(); try { Thread.sleep(10); } catch (InterruptedException e) { System.out.println(e); } } }} public class PhaserExample2 { public static void main(String[] args) { MyPhaser phsr = new MyPhaser(1, 4); System.out.println(\"Starting\"); new ModifiedThread(phsr, \"A\"); new ModifiedThread(phsr, \"B\"); new ModifiedThread(phsr, \"C\"); while (!phsr.isTerminated()) { phsr.arriveAndAwaitAdvance(); } System.out.println(\"The phaser is terminated\\n\"); }}",
"e": 10596,
"s": 8706,
"text": null
},
{
"code": null,
"e": 11036,
"s": 10596,
"text": "Starting\nThread B Beginning Phase 0\nThread C Beginning Phase 0\nThread A Beginning Phase 0\nPhase 0 completed.\n\nThread A Beginning Phase 1\nThread B Beginning Phase 1\nThread C Beginning Phase 1\nPhase 1 completed.\n\nThread C Beginning Phase 2\nThread A Beginning Phase 2\nThread B Beginning Phase 2\nPhase 2 completed.\n\nThread A Beginning Phase 3\nThread B Beginning Phase 3\nThread C Beginning Phase 3\nPhase 3 completed.\n\nThe phaser is terminated\n\n"
},
{
"code": null,
"e": 11123,
"s": 11036,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/Phaser.html "
},
{
"code": null,
"e": 11137,
"s": 11123,
"text": "ramandeepm007"
},
{
"code": null,
"e": 11157,
"s": 11137,
"text": "Java - util package"
},
{
"code": null,
"e": 11181,
"s": 11157,
"text": "Java-concurrent-package"
},
{
"code": null,
"e": 11196,
"s": 11181,
"text": "Java-Functions"
},
{
"code": null,
"e": 11208,
"s": 11196,
"text": "Java-Phaser"
},
{
"code": null,
"e": 11213,
"s": 11208,
"text": "Java"
},
{
"code": null,
"e": 11218,
"s": 11213,
"text": "Java"
},
{
"code": null,
"e": 11316,
"s": 11218,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11353,
"s": 11316,
"text": "List Interface in Java with Examples"
},
{
"code": null,
"e": 11369,
"s": 11353,
"text": "Strings in Java"
},
{
"code": null,
"e": 11415,
"s": 11369,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 11440,
"s": 11415,
"text": "Reverse an array in Java"
},
{
"code": null,
"e": 11489,
"s": 11440,
"text": "How to remove an element from ArrayList in Java?"
},
{
"code": null,
"e": 11529,
"s": 11489,
"text": "Checked vs Unchecked Exceptions in Java"
},
{
"code": null,
"e": 11579,
"s": 11529,
"text": "ArrayList get(index) Method in Java with Examples"
},
{
"code": null,
"e": 11637,
"s": 11579,
"text": "ArrayList to Array Conversion in Java : toArray() Methods"
},
{
"code": null,
"e": 11680,
"s": 11637,
"text": "Comparator Interface in Java with Examples"
}
] |
How to Set the X and the Y Limit in Matplotlib with Python? | 02 Dec, 2020
Prerequisites : Matplotlib
In this article, we will learn how to set the X limit and Y limit in matplotlib with Python. Before that some concepts need to be familiarized with:
Python : Python is a high-level, general-purpose and a very popular programming language. It is being used in web development, Machine Learning applications, along with all cutting edge technology in Software Industry.
Matplotlib : Matplotlib is a visualization library in supported by Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002.
xlim() : It is a function in pyplot module of matplotlib library which is used to get or set the x-limits of the current axes.
ylim() : It is a function in pyplot module of matplotlib library which is used to get or set the y-limits of the current axes.
Import Library
Load or create data
Plot a graph
Use xlim() / ylim() or both.
Let’s discuss these steps with the help of some examples :
Example 1: (By using xlim() method)
Python3
# import packagesimport matplotlib.pyplot as pltimport numpy as np # create datax = np.linspace(-10, 10, 1000)y = np.sin(x) # plot the graphplt.plot(x, y) # limit x by -5 to 5plt.xlim(-5, 5)
Output :
Simple Plot
X limited Plot
Example 2: (By using ylim() method)
Python3
# import packagesimport matplotlib.pyplot as pltimport numpy as np # create datax = np.linspace(-10, 10, 1000)y = np.cos(x) # plot the graphplt.plot(x, y) # limit y by 0 to 1plt.ylim(0, 1)
Output :
Simple Plot
Y Limited Plot
Example 3: (Using both xlim() and ylim() methods)
Python3
# import packagesimport matplotlib.pyplot as pltimport numpy as np # create datax = np.linspace(-10, 10, 20)y = x # plot the graphplt.plot(x, y) # limited to show positive axesplt.xlim(0)plt.ylim(0)
Output :
Simple Plot
X and Y Limited Plot
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Dec, 2020"
},
{
"code": null,
"e": 55,
"s": 28,
"text": "Prerequisites : Matplotlib"
},
{
"code": null,
"e": 204,
"s": 55,
"text": "In this article, we will learn how to set the X limit and Y limit in matplotlib with Python. Before that some concepts need to be familiarized with:"
},
{
"code": null,
"e": 424,
"s": 204,
"text": "Python : Python is a high-level, general-purpose and a very popular programming language. It is being used in web development, Machine Learning applications, along with all cutting edge technology in Software Industry. "
},
{
"code": null,
"e": 704,
"s": 424,
"text": "Matplotlib : Matplotlib is a visualization library in supported by Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002."
},
{
"code": null,
"e": 831,
"s": 704,
"text": "xlim() : It is a function in pyplot module of matplotlib library which is used to get or set the x-limits of the current axes."
},
{
"code": null,
"e": 958,
"s": 831,
"text": "ylim() : It is a function in pyplot module of matplotlib library which is used to get or set the y-limits of the current axes."
},
{
"code": null,
"e": 974,
"s": 958,
"text": "Import Library "
},
{
"code": null,
"e": 994,
"s": 974,
"text": "Load or create data"
},
{
"code": null,
"e": 1007,
"s": 994,
"text": "Plot a graph"
},
{
"code": null,
"e": 1036,
"s": 1007,
"text": "Use xlim() / ylim() or both."
},
{
"code": null,
"e": 1095,
"s": 1036,
"text": "Let’s discuss these steps with the help of some examples :"
},
{
"code": null,
"e": 1131,
"s": 1095,
"text": "Example 1: (By using xlim() method)"
},
{
"code": null,
"e": 1139,
"s": 1131,
"text": "Python3"
},
{
"code": "# import packagesimport matplotlib.pyplot as pltimport numpy as np # create datax = np.linspace(-10, 10, 1000)y = np.sin(x) # plot the graphplt.plot(x, y) # limit x by -5 to 5plt.xlim(-5, 5)",
"e": 1333,
"s": 1139,
"text": null
},
{
"code": null,
"e": 1342,
"s": 1333,
"text": "Output :"
},
{
"code": null,
"e": 1354,
"s": 1342,
"text": "Simple Plot"
},
{
"code": null,
"e": 1369,
"s": 1354,
"text": "X limited Plot"
},
{
"code": null,
"e": 1405,
"s": 1369,
"text": "Example 2: (By using ylim() method)"
},
{
"code": null,
"e": 1413,
"s": 1405,
"text": "Python3"
},
{
"code": "# import packagesimport matplotlib.pyplot as pltimport numpy as np # create datax = np.linspace(-10, 10, 1000)y = np.cos(x) # plot the graphplt.plot(x, y) # limit y by 0 to 1plt.ylim(0, 1)",
"e": 1605,
"s": 1413,
"text": null
},
{
"code": null,
"e": 1614,
"s": 1605,
"text": "Output :"
},
{
"code": null,
"e": 1626,
"s": 1614,
"text": "Simple Plot"
},
{
"code": null,
"e": 1641,
"s": 1626,
"text": "Y Limited Plot"
},
{
"code": null,
"e": 1691,
"s": 1641,
"text": "Example 3: (Using both xlim() and ylim() methods)"
},
{
"code": null,
"e": 1699,
"s": 1691,
"text": "Python3"
},
{
"code": "# import packagesimport matplotlib.pyplot as pltimport numpy as np # create datax = np.linspace(-10, 10, 20)y = x # plot the graphplt.plot(x, y) # limited to show positive axesplt.xlim(0)plt.ylim(0)",
"e": 1901,
"s": 1699,
"text": null
},
{
"code": null,
"e": 1910,
"s": 1901,
"text": "Output :"
},
{
"code": null,
"e": 1922,
"s": 1910,
"text": "Simple Plot"
},
{
"code": null,
"e": 1943,
"s": 1922,
"text": "X and Y Limited Plot"
},
{
"code": null,
"e": 1961,
"s": 1943,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 1968,
"s": 1961,
"text": "Python"
},
{
"code": null,
"e": 2066,
"s": 1968,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2098,
"s": 2066,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2125,
"s": 2098,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2146,
"s": 2125,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2169,
"s": 2146,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2225,
"s": 2169,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2256,
"s": 2225,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2298,
"s": 2256,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2340,
"s": 2298,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2379,
"s": 2340,
"text": "Python | Get unique values from a list"
}
] |
Operators in Dart | 08 Mar, 2022
The operators are special symbols that are used to carry out certain operations on the operands. The Dart has numerous built-in operators which can be used to carry out different functions, for example, ‘+’ is used to add two operands. Operators are meant to carry operations on one or two operands.
The following are the various types of operators in Dart:
Arithmetic OperatorsRelational OperatorsType Test OperatorsBitwise OperatorsAssignment OperatorsLogical OperatorsConditional OperatorCascade Notation Operator
Arithmetic Operators
Relational Operators
Type Test Operators
Bitwise Operators
Assignment Operators
Logical Operators
Conditional Operator
Cascade Notation Operator
This class of operators contain those operators which are used to perform arithmetic operation on the operands. They are binary operators i.e they act on two operands. They go like this:
Example: Using Arithmetic Operators in the program
Dart
void main(){ int a = 2; int b = 3; // Adding a and b var c = a + b; print("Sum of a and b is $c"); // Subtracting a and b var d = a - b; print("The difference between a and b is $d"); // Using unary minus var e = -d; print("The negation of difference between a and b is $e"); // Multiplication of a and b var f = a * b; print("The product of a and b is $f"); // Division of a and b var g = b / a; print("The quotient of a and b is $g"); // Using ~/ to divide a and b var h = b ~ / a; print("The quotient of a and b is $h"); // Remainder of a and b var i = b % a; print("The remainder of a and b is $i");}
Output:
Sum of a and b is 5
The difference between a and b is -1
The negation of difference between a and b is 1
Product of a and b is 6
The quotient of a and b is 1.5
The quotient of a and b is 1
The remainder of a and b is 1
This class of operators contain those operators which are used to perform relational operation on the operands. It goes like this:
Example: Using Relational Operators in the program
Dart
void main(){ int a = 2; int b = 3; // Greater between a and b var c = a > b; print("a is greater than b is $c"); // Smaller between a and b var d = a < b; print("a is smaller than b is $d"); // Greater than or equal to between a and b var e = a >= b; print("a is greater than b is $e"); // Less than or equal to between a and b var f = a <= b; print("a is smaller than b is $f"); // Equality between a and b var g = b == a; print("a and b are equal is $g"); // Unequality between a and b var h = b != a; print("a and b are not equal is $h");}
Output:
a is greater than b is false
a is smaller than b is true
a is greater than b is false
a is smaller than b is true
a and b are equal is false
a and b are not equal is true
This class of operators contain those operators which are used to perform comparison on the operands. It goes like this:
Example: Using Type Test Operators in the program
Dart
void main(){ String a = 'GFG'; double b = 3.3; // Using is to compare print(a is String); // Using is! to compare print(b is !int);}
Output:
true
true
This class of operators contain those operators which are used to perform bitwise operation on the operands. It goes like this:
Example: Using Bitwise Operators in the program
Dart
void main(){ int a = 5; int b = 7; // Performing Bitwise AND on a and b var c = a & b; print(c); // Performing Bitwise OR on a and b var d = a | b; print(d); // Performing Bitwise XOR on a and b var e = a ^ b; print(e); // Performing Bitwise NOT on a var f = ~a; print(f); // Performing left shift on a var g = a << b; print(g); // Performing right shift on a var h = a >> b; print(h);}
Output:
5
7
2
4294967290
640
0
This class of operators contain those operators which are used to assign value to the operands. It goes like this:
Example: Using Assignment Operators in the program
Dart
void main(){ int a = 5; int b = 7; // Assigning value to variable c var c = a * b; print(c); // Assigning value to variable d var d; d ? ? = a + b; // Value is assign as it is null print(d); // Again trying to assign value to d d ? ? = a - b; // Value is not assign as it is not null print(d);}
Output:
35
12
12
This class of operators contain those operators which are used to logically combine two or more conditions of the operands. It goes like this:
Example: Using Logical Operators in the program
Dart
void main(){ int a = 5; int b = 7; // Using And Operator bool c = a > 10 && b < 10; print(c); // Using Or Operator bool d = a > 10 || b < 10; print(d); // Using Not Operator bool e = !(a > 10); print(e);}
Output:
false
true
true
This class of operators contain those operators which are used to perform comparison on the operands. It goes like this:
Example: Using Conditional Operators in the program
Dart
void main(){ int a = 5; int b = 7; // Conditional Statement var c = (a < 10) ? "Statement is Correct, Geek" : "Statement is Wrong, Geek"; print(c); // Conditional statement int n; var d = n ? ? "n has Null value"; print(d); // After assigning value to n n = 10; d = n ? ? "n has Null value"; print(d);}
Output:
Statement is Correct, Geek
n has Null value
10
This class of operators allows you to perform a sequence of operation on the same element. It allows you to perform multiple methods on the same object. It goes like this:
Example: Using Cascade Notation Operators in the program
Dart
class GFG { var a; var b; void set(x, y) { this.a = x; this.b = y; } void add() { var z = this.a + this.b; print(z); }} void main(){ // Creating objects of class GFG GFG geek1 = new GFG(); GFG geek2 = new GFG(); // Without using Cascade Notation geek1.set(1, 2); geek1.add(); // Using Cascade Notation geek2..set(3, 4) ..add();}
Output:
3
7
Akanksha_Rai
almostsagar
sagar0719kumar
clintra
kothavvsaakash
Dart-basics
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
ListView Class in Flutter
Flutter - Row and Column Widgets
Flutter - Stack Widget
Dart Tutorial
How to Append or Concatenate Strings in Dart?
Flutter - Search Bar
Container class in Flutter | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n08 Mar, 2022"
},
{
"code": null,
"e": 354,
"s": 53,
"text": "The operators are special symbols that are used to carry out certain operations on the operands. The Dart has numerous built-in operators which can be used to carry out different functions, for example, ‘+’ is used to add two operands. Operators are meant to carry operations on one or two operands. "
},
{
"code": null,
"e": 412,
"s": 354,
"text": "The following are the various types of operators in Dart:"
},
{
"code": null,
"e": 571,
"s": 412,
"text": "Arithmetic OperatorsRelational OperatorsType Test OperatorsBitwise OperatorsAssignment OperatorsLogical OperatorsConditional OperatorCascade Notation Operator"
},
{
"code": null,
"e": 592,
"s": 571,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 613,
"s": 592,
"text": "Relational Operators"
},
{
"code": null,
"e": 633,
"s": 613,
"text": "Type Test Operators"
},
{
"code": null,
"e": 651,
"s": 633,
"text": "Bitwise Operators"
},
{
"code": null,
"e": 672,
"s": 651,
"text": "Assignment Operators"
},
{
"code": null,
"e": 690,
"s": 672,
"text": "Logical Operators"
},
{
"code": null,
"e": 711,
"s": 690,
"text": "Conditional Operator"
},
{
"code": null,
"e": 737,
"s": 711,
"text": "Cascade Notation Operator"
},
{
"code": null,
"e": 925,
"s": 737,
"text": "This class of operators contain those operators which are used to perform arithmetic operation on the operands. They are binary operators i.e they act on two operands. They go like this: "
},
{
"code": null,
"e": 977,
"s": 925,
"text": "Example: Using Arithmetic Operators in the program "
},
{
"code": null,
"e": 982,
"s": 977,
"text": "Dart"
},
{
"code": "void main(){ int a = 2; int b = 3; // Adding a and b var c = a + b; print(\"Sum of a and b is $c\"); // Subtracting a and b var d = a - b; print(\"The difference between a and b is $d\"); // Using unary minus var e = -d; print(\"The negation of difference between a and b is $e\"); // Multiplication of a and b var f = a * b; print(\"The product of a and b is $f\"); // Division of a and b var g = b / a; print(\"The quotient of a and b is $g\"); // Using ~/ to divide a and b var h = b ~ / a; print(\"The quotient of a and b is $h\"); // Remainder of a and b var i = b % a; print(\"The remainder of a and b is $i\");}",
"e": 1663,
"s": 982,
"text": null
},
{
"code": null,
"e": 1672,
"s": 1663,
"text": "Output: "
},
{
"code": null,
"e": 1891,
"s": 1672,
"text": "Sum of a and b is 5\nThe difference between a and b is -1\nThe negation of difference between a and b is 1\nProduct of a and b is 6\nThe quotient of a and b is 1.5\nThe quotient of a and b is 1\nThe remainder of a and b is 1"
},
{
"code": null,
"e": 2023,
"s": 1891,
"text": "This class of operators contain those operators which are used to perform relational operation on the operands. It goes like this: "
},
{
"code": null,
"e": 2075,
"s": 2023,
"text": "Example: Using Relational Operators in the program "
},
{
"code": null,
"e": 2080,
"s": 2075,
"text": "Dart"
},
{
"code": "void main(){ int a = 2; int b = 3; // Greater between a and b var c = a > b; print(\"a is greater than b is $c\"); // Smaller between a and b var d = a < b; print(\"a is smaller than b is $d\"); // Greater than or equal to between a and b var e = a >= b; print(\"a is greater than b is $e\"); // Less than or equal to between a and b var f = a <= b; print(\"a is smaller than b is $f\"); // Equality between a and b var g = b == a; print(\"a and b are equal is $g\"); // Unequality between a and b var h = b != a; print(\"a and b are not equal is $h\");}",
"e": 2689,
"s": 2080,
"text": null
},
{
"code": null,
"e": 2698,
"s": 2689,
"text": "Output: "
},
{
"code": null,
"e": 2870,
"s": 2698,
"text": "a is greater than b is false\na is smaller than b is true\na is greater than b is false\na is smaller than b is true\na and b are equal is false\na and b are not equal is true "
},
{
"code": null,
"e": 2992,
"s": 2870,
"text": "This class of operators contain those operators which are used to perform comparison on the operands. It goes like this: "
},
{
"code": null,
"e": 3043,
"s": 2992,
"text": "Example: Using Type Test Operators in the program "
},
{
"code": null,
"e": 3048,
"s": 3043,
"text": "Dart"
},
{
"code": "void main(){ String a = 'GFG'; double b = 3.3; // Using is to compare print(a is String); // Using is! to compare print(b is !int);}",
"e": 3201,
"s": 3048,
"text": null
},
{
"code": null,
"e": 3210,
"s": 3201,
"text": "Output: "
},
{
"code": null,
"e": 3220,
"s": 3210,
"text": "true\ntrue"
},
{
"code": null,
"e": 3349,
"s": 3220,
"text": "This class of operators contain those operators which are used to perform bitwise operation on the operands. It goes like this: "
},
{
"code": null,
"e": 3398,
"s": 3349,
"text": "Example: Using Bitwise Operators in the program "
},
{
"code": null,
"e": 3403,
"s": 3398,
"text": "Dart"
},
{
"code": "void main(){ int a = 5; int b = 7; // Performing Bitwise AND on a and b var c = a & b; print(c); // Performing Bitwise OR on a and b var d = a | b; print(d); // Performing Bitwise XOR on a and b var e = a ^ b; print(e); // Performing Bitwise NOT on a var f = ~a; print(f); // Performing left shift on a var g = a << b; print(g); // Performing right shift on a var h = a >> b; print(h);}",
"e": 3856,
"s": 3403,
"text": null
},
{
"code": null,
"e": 3865,
"s": 3856,
"text": "Output: "
},
{
"code": null,
"e": 3889,
"s": 3865,
"text": "5\n7\n2\n4294967290\n640\n0 "
},
{
"code": null,
"e": 4005,
"s": 3889,
"text": "This class of operators contain those operators which are used to assign value to the operands. It goes like this: "
},
{
"code": null,
"e": 4057,
"s": 4005,
"text": "Example: Using Assignment Operators in the program "
},
{
"code": null,
"e": 4062,
"s": 4057,
"text": "Dart"
},
{
"code": "void main(){ int a = 5; int b = 7; // Assigning value to variable c var c = a * b; print(c); // Assigning value to variable d var d; d ? ? = a + b; // Value is assign as it is null print(d); // Again trying to assign value to d d ? ? = a - b; // Value is not assign as it is not null print(d);}",
"e": 4395,
"s": 4062,
"text": null
},
{
"code": null,
"e": 4404,
"s": 4395,
"text": "Output: "
},
{
"code": null,
"e": 4414,
"s": 4404,
"text": "35\n12\n12 "
},
{
"code": null,
"e": 4558,
"s": 4414,
"text": "This class of operators contain those operators which are used to logically combine two or more conditions of the operands. It goes like this: "
},
{
"code": null,
"e": 4607,
"s": 4558,
"text": "Example: Using Logical Operators in the program "
},
{
"code": null,
"e": 4612,
"s": 4607,
"text": "Dart"
},
{
"code": "void main(){ int a = 5; int b = 7; // Using And Operator bool c = a > 10 && b < 10; print(c); // Using Or Operator bool d = a > 10 || b < 10; print(d); // Using Not Operator bool e = !(a > 10); print(e);}",
"e": 4853,
"s": 4612,
"text": null
},
{
"code": null,
"e": 4862,
"s": 4853,
"text": "Output: "
},
{
"code": null,
"e": 4878,
"s": 4862,
"text": "false\ntrue\ntrue"
},
{
"code": null,
"e": 5000,
"s": 4878,
"text": "This class of operators contain those operators which are used to perform comparison on the operands. It goes like this: "
},
{
"code": null,
"e": 5053,
"s": 5000,
"text": "Example: Using Conditional Operators in the program "
},
{
"code": null,
"e": 5058,
"s": 5053,
"text": "Dart"
},
{
"code": "void main(){ int a = 5; int b = 7; // Conditional Statement var c = (a < 10) ? \"Statement is Correct, Geek\" : \"Statement is Wrong, Geek\"; print(c); // Conditional statement int n; var d = n ? ? \"n has Null value\"; print(d); // After assigning value to n n = 10; d = n ? ? \"n has Null value\"; print(d);}",
"e": 5403,
"s": 5058,
"text": null
},
{
"code": null,
"e": 5412,
"s": 5403,
"text": "Output: "
},
{
"code": null,
"e": 5460,
"s": 5412,
"text": "Statement is Correct, Geek\nn has Null value\n10 "
},
{
"code": null,
"e": 5633,
"s": 5460,
"text": "This class of operators allows you to perform a sequence of operation on the same element. It allows you to perform multiple methods on the same object. It goes like this: "
},
{
"code": null,
"e": 5691,
"s": 5633,
"text": "Example: Using Cascade Notation Operators in the program "
},
{
"code": null,
"e": 5696,
"s": 5691,
"text": "Dart"
},
{
"code": "class GFG { var a; var b; void set(x, y) { this.a = x; this.b = y; } void add() { var z = this.a + this.b; print(z); }} void main(){ // Creating objects of class GFG GFG geek1 = new GFG(); GFG geek2 = new GFG(); // Without using Cascade Notation geek1.set(1, 2); geek1.add(); // Using Cascade Notation geek2..set(3, 4) ..add();}",
"e": 6112,
"s": 5696,
"text": null
},
{
"code": null,
"e": 6121,
"s": 6112,
"text": "Output: "
},
{
"code": null,
"e": 6125,
"s": 6121,
"text": "3\n7"
},
{
"code": null,
"e": 6138,
"s": 6125,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 6150,
"s": 6138,
"text": "almostsagar"
},
{
"code": null,
"e": 6165,
"s": 6150,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 6173,
"s": 6165,
"text": "clintra"
},
{
"code": null,
"e": 6188,
"s": 6173,
"text": "kothavvsaakash"
},
{
"code": null,
"e": 6200,
"s": 6188,
"text": "Dart-basics"
},
{
"code": null,
"e": 6205,
"s": 6200,
"text": "Dart"
},
{
"code": null,
"e": 6303,
"s": 6205,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6335,
"s": 6303,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 6374,
"s": 6335,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 6400,
"s": 6374,
"text": "Flutter - Checkbox Widget"
},
{
"code": null,
"e": 6426,
"s": 6400,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 6459,
"s": 6426,
"text": "Flutter - Row and Column Widgets"
},
{
"code": null,
"e": 6482,
"s": 6459,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 6496,
"s": 6482,
"text": "Dart Tutorial"
},
{
"code": null,
"e": 6542,
"s": 6496,
"text": "How to Append or Concatenate Strings in Dart?"
},
{
"code": null,
"e": 6563,
"s": 6542,
"text": "Flutter - Search Bar"
}
] |
How to Add All Items From a Collection to an ArrayList in Java? | 18 Nov, 2021
Given a Collection with some values, the task is to add all the items of this Collection to an ArrayList in Java.
Illustrations:
Input: Collection = [1, 2, 3]
Output: ArrayList = [1, 2, 3]
Input: Collection = [GFG, Geek, GeeksForGeeks]
Output: ArrayList = [GFG, Geek, GeeksForGeeks]
Approach:
Get the Collection whose items are to be added into the ArrayListCreate an ArrayListAdd all the items of Collection into this ArrayList using ArrayList.addAll() methodArrayList with all the items of Collections have been created.
Get the Collection whose items are to be added into the ArrayList
Create an ArrayList
Add all the items of Collection into this ArrayList using ArrayList.addAll() method
ArrayList with all the items of Collections have been created.
Example
Java
// Java Program to Add All Items from a collection// to an ArrayList // Importing required classesimport java.io.*;import java.util.*;import java.util.stream.*; // Main classclass GFG { // Method 1 // To add all items from a collection // to an ArrayList public static <T> ArrayList<T> createArrayList(List<T> collection) { // Creating an ArrayList ArrayList<T> list = new ArrayList<T>(); // Adding all the items of Collection // into this ArrayList list.addAll(collection); return list; } // Method 2 // Main driver method public static void main(String[] args) { // Getting array elements as list // and storing in a List object List<Integer> collection1 = Arrays.asList(1, 2, 3); // Printing elements in above List object System.out.println("ArrayList with all " + "elements of collection " + collection1 + ": " + createArrayList(collection1)); // Again creating another List class object List<String> collection2 = Arrays.asList( "GFG", "Geeks", "GeeksForGeeks"); // Printing elements in above List object System.out.println("ArrayList with all" + " elements of collection " + collection2 + ": " + createArrayList(collection2)); }}
ArrayList with all elements of collection [1, 2, 3]: [1, 2, 3]
ArrayList with all elements of collection [GFG, Geeks, GeeksForGeeks]: [GFG, Geeks, GeeksForGeeks]
solankimayank
Java-ArrayList
Java-Collections
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Nov, 2021"
},
{
"code": null,
"e": 142,
"s": 28,
"text": "Given a Collection with some values, the task is to add all the items of this Collection to an ArrayList in Java."
},
{
"code": null,
"e": 158,
"s": 142,
"text": "Illustrations: "
},
{
"code": null,
"e": 219,
"s": 158,
"text": "Input: Collection = [1, 2, 3] \nOutput: ArrayList = [1, 2, 3]"
},
{
"code": null,
"e": 315,
"s": 219,
"text": "Input: Collection = [GFG, Geek, GeeksForGeeks] \nOutput: ArrayList = [GFG, Geek, GeeksForGeeks] "
},
{
"code": null,
"e": 325,
"s": 315,
"text": "Approach:"
},
{
"code": null,
"e": 555,
"s": 325,
"text": "Get the Collection whose items are to be added into the ArrayListCreate an ArrayListAdd all the items of Collection into this ArrayList using ArrayList.addAll() methodArrayList with all the items of Collections have been created."
},
{
"code": null,
"e": 621,
"s": 555,
"text": "Get the Collection whose items are to be added into the ArrayList"
},
{
"code": null,
"e": 641,
"s": 621,
"text": "Create an ArrayList"
},
{
"code": null,
"e": 725,
"s": 641,
"text": "Add all the items of Collection into this ArrayList using ArrayList.addAll() method"
},
{
"code": null,
"e": 788,
"s": 725,
"text": "ArrayList with all the items of Collections have been created."
},
{
"code": null,
"e": 796,
"s": 788,
"text": "Example"
},
{
"code": null,
"e": 801,
"s": 796,
"text": "Java"
},
{
"code": "// Java Program to Add All Items from a collection// to an ArrayList // Importing required classesimport java.io.*;import java.util.*;import java.util.stream.*; // Main classclass GFG { // Method 1 // To add all items from a collection // to an ArrayList public static <T> ArrayList<T> createArrayList(List<T> collection) { // Creating an ArrayList ArrayList<T> list = new ArrayList<T>(); // Adding all the items of Collection // into this ArrayList list.addAll(collection); return list; } // Method 2 // Main driver method public static void main(String[] args) { // Getting array elements as list // and storing in a List object List<Integer> collection1 = Arrays.asList(1, 2, 3); // Printing elements in above List object System.out.println(\"ArrayList with all \" + \"elements of collection \" + collection1 + \": \" + createArrayList(collection1)); // Again creating another List class object List<String> collection2 = Arrays.asList( \"GFG\", \"Geeks\", \"GeeksForGeeks\"); // Printing elements in above List object System.out.println(\"ArrayList with all\" + \" elements of collection \" + collection2 + \": \" + createArrayList(collection2)); }}",
"e": 2254,
"s": 801,
"text": null
},
{
"code": null,
"e": 2416,
"s": 2254,
"text": "ArrayList with all elements of collection [1, 2, 3]: [1, 2, 3]\nArrayList with all elements of collection [GFG, Geeks, GeeksForGeeks]: [GFG, Geeks, GeeksForGeeks]"
},
{
"code": null,
"e": 2430,
"s": 2416,
"text": "solankimayank"
},
{
"code": null,
"e": 2445,
"s": 2430,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 2462,
"s": 2445,
"text": "Java-Collections"
},
{
"code": null,
"e": 2467,
"s": 2462,
"text": "Java"
},
{
"code": null,
"e": 2472,
"s": 2467,
"text": "Java"
},
{
"code": null,
"e": 2489,
"s": 2472,
"text": "Java-Collections"
}
] |
Create MySQL Tables | To begin with, the table creation command requires the following details −
Name of the table
Name of the fields
Definitions for each field
Here is a generic SQL syntax to create a MySQL table −
CREATE TABLE table_name (column_name column_type);
Now, we will create the following table in the TUTORIALS database.
create table tutorials_tbl(
tutorial_id INT NOT NULL AUTO_INCREMENT,
tutorial_title VARCHAR(100) NOT NULL,
tutorial_author VARCHAR(40) NOT NULL,
submission_date DATE,
PRIMARY KEY ( tutorial_id )
);
Here, a few items need explanation −
Field Attribute NOT NULL is being used because we do not want this field to be NULL. So, if a user will try to create a record with a NULL value, then MySQL will raise an error.
Field Attribute NOT NULL is being used because we do not want this field to be NULL. So, if a user will try to create a record with a NULL value, then MySQL will raise an error.
Field Attribute AUTO_INCREMENT tells MySQL to go ahead and add the next available number to the id field.
Field Attribute AUTO_INCREMENT tells MySQL to go ahead and add the next available number to the id field.
Keyword PRIMARY KEY is used to define a column as a primary key. You can use multiple columns separated by a comma to define a primary key.
Keyword PRIMARY KEY is used to define a column as a primary key. You can use multiple columns separated by a comma to define a primary key.
It is easy to create a MySQL table from the mysql> prompt. You will use the SQL command CREATE TABLE to create a table.
Here is an example, which will create tutorials_tbl −
root@host# mysql -u root -p
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> CREATE TABLE tutorials_tbl(
-> tutorial_id INT NOT NULL AUTO_INCREMENT,
-> tutorial_title VARCHAR(100) NOT NULL,
-> tutorial_author VARCHAR(40) NOT NULL,
-> submission_date DATE,
-> PRIMARY KEY ( tutorial_id )
-> );
Query OK, 0 rows affected (0.16 sec)
mysql>
NOTE − MySQL does not terminate a command until you give a semicolon (;) at the end of SQL command.
PHP uses mysqli query() or mysql_query() function to create a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure.
$mysqli->query($sql,$resultmode)
$sql
Required - SQL query to create a MySQL table.
$resultmode
Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.
Try the following example to create a table −
Copy and paste the following example as mysql_example.php −
<html>
<head>
<title>Creating MySQL Table</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root@123';
$dbname = 'TUTORIALS';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($mysqli->connect_errno ) {
printf("Connect failed: %s<br />", $mysqli->connect_error);
exit();
}
printf('Connected successfully.<br />');
$sql = "CREATE TABLE tutorials_tbl( ".
"tutorial_id INT NOT NULL AUTO_INCREMENT, ".
"tutorial_title VARCHAR(100) NOT NULL, ".
"tutorial_author VARCHAR(40) NOT NULL, ".
"submission_date DATE, ".
"PRIMARY KEY ( tutorial_id )); ";
if ($mysqli->query($sql)) {
printf("Table tutorials_tbl created successfully.<br />");
}
if ($mysqli->errno) {
printf("Could not create table: %s<br />", $mysqli->error);
}
$mysqli->close();
?>
</body>
</html>
Access the mysql_example.php deployed on apache web server and verify the output.
Connected successfully.
Table tutorials_tbl created successfully. | [
{
"code": null,
"e": 2516,
"s": 2441,
"text": "To begin with, the table creation command requires the following details −"
},
{
"code": null,
"e": 2534,
"s": 2516,
"text": "Name of the table"
},
{
"code": null,
"e": 2553,
"s": 2534,
"text": "Name of the fields"
},
{
"code": null,
"e": 2580,
"s": 2553,
"text": "Definitions for each field"
},
{
"code": null,
"e": 2635,
"s": 2580,
"text": "Here is a generic SQL syntax to create a MySQL table −"
},
{
"code": null,
"e": 2687,
"s": 2635,
"text": "CREATE TABLE table_name (column_name column_type);\n"
},
{
"code": null,
"e": 2754,
"s": 2687,
"text": "Now, we will create the following table in the TUTORIALS database."
},
{
"code": null,
"e": 2967,
"s": 2754,
"text": "create table tutorials_tbl(\n tutorial_id INT NOT NULL AUTO_INCREMENT,\n tutorial_title VARCHAR(100) NOT NULL,\n tutorial_author VARCHAR(40) NOT NULL,\n submission_date DATE,\n PRIMARY KEY ( tutorial_id )\n);"
},
{
"code": null,
"e": 3004,
"s": 2967,
"text": "Here, a few items need explanation −"
},
{
"code": null,
"e": 3182,
"s": 3004,
"text": "Field Attribute NOT NULL is being used because we do not want this field to be NULL. So, if a user will try to create a record with a NULL value, then MySQL will raise an error."
},
{
"code": null,
"e": 3360,
"s": 3182,
"text": "Field Attribute NOT NULL is being used because we do not want this field to be NULL. So, if a user will try to create a record with a NULL value, then MySQL will raise an error."
},
{
"code": null,
"e": 3466,
"s": 3360,
"text": "Field Attribute AUTO_INCREMENT tells MySQL to go ahead and add the next available number to the id field."
},
{
"code": null,
"e": 3572,
"s": 3466,
"text": "Field Attribute AUTO_INCREMENT tells MySQL to go ahead and add the next available number to the id field."
},
{
"code": null,
"e": 3712,
"s": 3572,
"text": "Keyword PRIMARY KEY is used to define a column as a primary key. You can use multiple columns separated by a comma to define a primary key."
},
{
"code": null,
"e": 3852,
"s": 3712,
"text": "Keyword PRIMARY KEY is used to define a column as a primary key. You can use multiple columns separated by a comma to define a primary key."
},
{
"code": null,
"e": 3972,
"s": 3852,
"text": "It is easy to create a MySQL table from the mysql> prompt. You will use the SQL command CREATE TABLE to create a table."
},
{
"code": null,
"e": 4026,
"s": 3972,
"text": "Here is an example, which will create tutorials_tbl −"
},
{
"code": null,
"e": 4401,
"s": 4026,
"text": "root@host# mysql -u root -p\nEnter password:*******\nmysql> use TUTORIALS;\nDatabase changed\nmysql> CREATE TABLE tutorials_tbl(\n -> tutorial_id INT NOT NULL AUTO_INCREMENT,\n -> tutorial_title VARCHAR(100) NOT NULL,\n -> tutorial_author VARCHAR(40) NOT NULL,\n -> submission_date DATE,\n -> PRIMARY KEY ( tutorial_id )\n -> );\nQuery OK, 0 rows affected (0.16 sec)\nmysql>"
},
{
"code": null,
"e": 4501,
"s": 4401,
"text": "NOTE − MySQL does not terminate a command until you give a semicolon (;) at the end of SQL command."
},
{
"code": null,
"e": 4660,
"s": 4501,
"text": "PHP uses mysqli query() or mysql_query() function to create a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure."
},
{
"code": null,
"e": 4694,
"s": 4660,
"text": "$mysqli->query($sql,$resultmode)\n"
},
{
"code": null,
"e": 4699,
"s": 4694,
"text": "$sql"
},
{
"code": null,
"e": 4745,
"s": 4699,
"text": "Required - SQL query to create a MySQL table."
},
{
"code": null,
"e": 4757,
"s": 4745,
"text": "$resultmode"
},
{
"code": null,
"e": 4905,
"s": 4757,
"text": "Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used."
},
{
"code": null,
"e": 4951,
"s": 4905,
"text": "Try the following example to create a table −"
},
{
"code": null,
"e": 5011,
"s": 4951,
"text": "Copy and paste the following example as mysql_example.php −"
},
{
"code": null,
"e": 6084,
"s": 5011,
"text": "<html>\n <head>\n <title>Creating MySQL Table</title>\n </head>\n <body>\n <?php\n $dbhost = 'localhost';\n $dbuser = 'root';\n $dbpass = 'root@123';\n $dbname = 'TUTORIALS';\n $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);\n \n if($mysqli->connect_errno ) {\n printf(\"Connect failed: %s<br />\", $mysqli->connect_error);\n exit();\n }\n printf('Connected successfully.<br />');\n \n $sql = \"CREATE TABLE tutorials_tbl( \".\n \"tutorial_id INT NOT NULL AUTO_INCREMENT, \".\n \"tutorial_title VARCHAR(100) NOT NULL, \".\n \"tutorial_author VARCHAR(40) NOT NULL, \".\n \"submission_date DATE, \".\n \"PRIMARY KEY ( tutorial_id )); \";\n if ($mysqli->query($sql)) {\n printf(\"Table tutorials_tbl created successfully.<br />\");\n }\n if ($mysqli->errno) {\n printf(\"Could not create table: %s<br />\", $mysqli->error);\n }\n\n $mysqli->close();\n ?>\n </body>\n</html>"
},
{
"code": null,
"e": 6166,
"s": 6084,
"text": "Access the mysql_example.php deployed on apache web server and verify the output."
}
] |
How to play a notification sound on websites? | 05 Jun, 2020
There are various ways to play a notification sound on a website. IN this article we will play the notification sound in three different ways:
Using Onclick Event in JavaScript
Using Audio class in Javascript
Using pure Jquery:
Below all the procedures are explained in details with the exxampl code:
Using Onclick Event in Javascript: The onclick event fires the function when the user clicks on the button. In the following code, the play1 function is associated with onclick event. Function play1 receives the name of the audio file, then we select division with id=sound and inserts an HTML containing the audio tag.Example:<!DOCTYPE html><html> <head> <title>Notification Sound</title> <style> body { text-align: center; } h1 { color: green; } </style> <script> function play1() { /* Audio link for notification */ var mp3 = '<source src=" " type="audio/mpeg">'; document.getElementById("sound").innerHTML = '<audio autoplay="autoplay">' + mp3 + "</audio>"; } </script> </head> <body> <h1>GeeksforGeeks</h1> <b>Notification Sound</b> <br> <!-- The onclick fires play1 function --> <button onclick="play1();"> Get notification sound </button> <div id="sound"></div> </body></html>
Example:
<!DOCTYPE html><html> <head> <title>Notification Sound</title> <style> body { text-align: center; } h1 { color: green; } </style> <script> function play1() { /* Audio link for notification */ var mp3 = '<source src=" " type="audio/mpeg">'; document.getElementById("sound").innerHTML = '<audio autoplay="autoplay">' + mp3 + "</audio>"; } </script> </head> <body> <h1>GeeksforGeeks</h1> <b>Notification Sound</b> <br> <!-- The onclick fires play1 function --> <button onclick="play1();"> Get notification sound </button> <div id="sound"></div> </body></html>
Using Audio class in JavaScript: This method purely uses JavaScript where an Audio object is created and the in-built audio.play() method.<!DOCTYPE html><html> <head> <title>Notification Sound</title> <style> body { text-align: center; } h1 { color: green; } </style> <script> function play2() { /* Audio link for notification */ var audio = new Audio(" "); audio.play(); } </script> </head> <body> <h1>GeeksforGeeks</h1> <b>Notification Sound</b> <br> <!-- Plays default sound that is already set in the function --> <button onclick="play2();"> Get notification sound </button> </body></html>
<!DOCTYPE html><html> <head> <title>Notification Sound</title> <style> body { text-align: center; } h1 { color: green; } </style> <script> function play2() { /* Audio link for notification */ var audio = new Audio(" "); audio.play(); } </script> </head> <body> <h1>GeeksforGeeks</h1> <b>Notification Sound</b> <br> <!-- Plays default sound that is already set in the function --> <button onclick="play2();"> Get notification sound </button> </body></html>
Using pure Jquery: In this procedure, we Select play id and bind with click event. In the function, we create a new audio file and then play it.<!DOCTYPE html><html> <head> <title>Notification Sound</title> <style> body { text-align: center; } h1 { color: green; } </style> <script> $(document).ready(function () { $("#play").click(function () { /* Audio link for notification */ var audio = new Audio(" "); audio.play(); }); }); </script> </head> <body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <h1>GeeksforGeeks</h1> <b>Notification Sound</b> <br> <button id="play"> Get notification sound </button> </body></html>
<!DOCTYPE html><html> <head> <title>Notification Sound</title> <style> body { text-align: center; } h1 { color: green; } </style> <script> $(document).ready(function () { $("#play").click(function () { /* Audio link for notification */ var audio = new Audio(" "); audio.play(); }); }); </script> </head> <body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <h1>GeeksforGeeks</h1> <b>Notification Sound</b> <br> <button id="play"> Get notification sound </button> </body></html>
Output: For any procedure you use, it will work the same.
CSS-Misc
HTML-Misc
JavaScript-Misc
Picked
HTML
JavaScript
JQuery
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Jun, 2020"
},
{
"code": null,
"e": 171,
"s": 28,
"text": "There are various ways to play a notification sound on a website. IN this article we will play the notification sound in three different ways:"
},
{
"code": null,
"e": 205,
"s": 171,
"text": "Using Onclick Event in JavaScript"
},
{
"code": null,
"e": 237,
"s": 205,
"text": "Using Audio class in Javascript"
},
{
"code": null,
"e": 256,
"s": 237,
"text": "Using pure Jquery:"
},
{
"code": null,
"e": 329,
"s": 256,
"text": "Below all the procedures are explained in details with the exxampl code:"
},
{
"code": null,
"e": 1508,
"s": 329,
"text": "Using Onclick Event in Javascript: The onclick event fires the function when the user clicks on the button. In the following code, the play1 function is associated with onclick event. Function play1 receives the name of the audio file, then we select division with id=sound and inserts an HTML containing the audio tag.Example:<!DOCTYPE html><html> <head> <title>Notification Sound</title> <style> body { text-align: center; } h1 { color: green; } </style> <script> function play1() { /* Audio link for notification */ var mp3 = '<source src=\" \" type=\"audio/mpeg\">'; document.getElementById(\"sound\").innerHTML = '<audio autoplay=\"autoplay\">' + mp3 + \"</audio>\"; } </script> </head> <body> <h1>GeeksforGeeks</h1> <b>Notification Sound</b> <br> <!-- The onclick fires play1 function --> <button onclick=\"play1();\"> Get notification sound </button> <div id=\"sound\"></div> </body></html>"
},
{
"code": null,
"e": 1517,
"s": 1508,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Notification Sound</title> <style> body { text-align: center; } h1 { color: green; } </style> <script> function play1() { /* Audio link for notification */ var mp3 = '<source src=\" \" type=\"audio/mpeg\">'; document.getElementById(\"sound\").innerHTML = '<audio autoplay=\"autoplay\">' + mp3 + \"</audio>\"; } </script> </head> <body> <h1>GeeksforGeeks</h1> <b>Notification Sound</b> <br> <!-- The onclick fires play1 function --> <button onclick=\"play1();\"> Get notification sound </button> <div id=\"sound\"></div> </body></html>",
"e": 2369,
"s": 1517,
"text": null
},
{
"code": null,
"e": 3229,
"s": 2369,
"text": "Using Audio class in JavaScript: This method purely uses JavaScript where an Audio object is created and the in-built audio.play() method.<!DOCTYPE html><html> <head> <title>Notification Sound</title> <style> body { text-align: center; } h1 { color: green; } </style> <script> function play2() { /* Audio link for notification */ var audio = new Audio(\" \"); audio.play(); } </script> </head> <body> <h1>GeeksforGeeks</h1> <b>Notification Sound</b> <br> <!-- Plays default sound that is already set in the function --> <button onclick=\"play2();\"> Get notification sound </button> </body></html>"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Notification Sound</title> <style> body { text-align: center; } h1 { color: green; } </style> <script> function play2() { /* Audio link for notification */ var audio = new Audio(\" \"); audio.play(); } </script> </head> <body> <h1>GeeksforGeeks</h1> <b>Notification Sound</b> <br> <!-- Plays default sound that is already set in the function --> <button onclick=\"play2();\"> Get notification sound </button> </body></html>",
"e": 3951,
"s": 3229,
"text": null
},
{
"code": null,
"e": 4931,
"s": 3951,
"text": "Using pure Jquery: In this procedure, we Select play id and bind with click event. In the function, we create a new audio file and then play it.<!DOCTYPE html><html> <head> <title>Notification Sound</title> <style> body { text-align: center; } h1 { color: green; } </style> <script> $(document).ready(function () { $(\"#play\").click(function () { /* Audio link for notification */ var audio = new Audio(\" \"); audio.play(); }); }); </script> </head> <body> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <h1>GeeksforGeeks</h1> <b>Notification Sound</b> <br> <button id=\"play\"> Get notification sound </button> </body></html>"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Notification Sound</title> <style> body { text-align: center; } h1 { color: green; } </style> <script> $(document).ready(function () { $(\"#play\").click(function () { /* Audio link for notification */ var audio = new Audio(\" \"); audio.play(); }); }); </script> </head> <body> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <h1>GeeksforGeeks</h1> <b>Notification Sound</b> <br> <button id=\"play\"> Get notification sound </button> </body></html>",
"e": 5767,
"s": 4931,
"text": null
},
{
"code": null,
"e": 5825,
"s": 5767,
"text": "Output: For any procedure you use, it will work the same."
},
{
"code": null,
"e": 5834,
"s": 5825,
"text": "CSS-Misc"
},
{
"code": null,
"e": 5844,
"s": 5834,
"text": "HTML-Misc"
},
{
"code": null,
"e": 5860,
"s": 5844,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 5867,
"s": 5860,
"text": "Picked"
},
{
"code": null,
"e": 5872,
"s": 5867,
"text": "HTML"
},
{
"code": null,
"e": 5883,
"s": 5872,
"text": "JavaScript"
},
{
"code": null,
"e": 5890,
"s": 5883,
"text": "JQuery"
},
{
"code": null,
"e": 5907,
"s": 5890,
"text": "Web Technologies"
},
{
"code": null,
"e": 5934,
"s": 5907,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 5939,
"s": 5934,
"text": "HTML"
}
] |
PHP | shell_exec() vs exec() Function | 31 Jul, 2021
shell_exec() Function
The shell_exec() function is an inbuilt function in PHP which is used to execute the commands via shell and return the complete output as a string. The shell_exec is an alias for the backtick operator, for those used to *nix. If the command fails return NULL and the values are not reliable for error checking.
Syntax:
string shell_exec( $cmd )
Parameters: This function accepts single parameter $cmd which is used to hold the command that will be executed.
Return Value: This function returns the executed command or NULL if an error occurred.
Note: This function is disabled when PHP is running in safe mode.
Example:
<?php // Use ls command to shell_exec// function$output = shell_exec('ls'); // Display the list of all file// and directoryecho "<pre>$output</pre>";?>
Output:
gfg.php
index.html
geeks.php
exec() Function
The exec() function is an inbuilt function in PHP which is used to execute an external program and returns the last line of the output. It also returns NULL if no command run properly.
Syntax:
string exec( $command, $output, $return_var )
Parameters: This function accepts three parameters as mentioned above and described below:
$command: This parameter is used to hold the command which will be executed.
$output: This parameter is used to specify the array which will be filled with every line of output from the command.
$return_var: The $return_var parameter is present along with the output argument, then it returns the status of the executed command will be written to this variable.
Return Value: This function returns the executed command, be sure to set and use the output parameter.
Example:
<?php// (on a system with the "iamexecfunction" executable in the path)echo exec('iamexecfunction');?>
Output:
geeks.php
References:
http://php.net/manual/en/function.shell-exec.php
http://php.net/manual/en/function.exec.php
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Jul, 2021"
},
{
"code": null,
"e": 50,
"s": 28,
"text": "shell_exec() Function"
},
{
"code": null,
"e": 361,
"s": 50,
"text": "The shell_exec() function is an inbuilt function in PHP which is used to execute the commands via shell and return the complete output as a string. The shell_exec is an alias for the backtick operator, for those used to *nix. If the command fails return NULL and the values are not reliable for error checking."
},
{
"code": null,
"e": 369,
"s": 361,
"text": "Syntax:"
},
{
"code": null,
"e": 395,
"s": 369,
"text": "string shell_exec( $cmd )"
},
{
"code": null,
"e": 508,
"s": 395,
"text": "Parameters: This function accepts single parameter $cmd which is used to hold the command that will be executed."
},
{
"code": null,
"e": 595,
"s": 508,
"text": "Return Value: This function returns the executed command or NULL if an error occurred."
},
{
"code": null,
"e": 661,
"s": 595,
"text": "Note: This function is disabled when PHP is running in safe mode."
},
{
"code": null,
"e": 670,
"s": 661,
"text": "Example:"
},
{
"code": "<?php // Use ls command to shell_exec// function$output = shell_exec('ls'); // Display the list of all file// and directoryecho \"<pre>$output</pre>\";?>",
"e": 824,
"s": 670,
"text": null
},
{
"code": null,
"e": 832,
"s": 824,
"text": "Output:"
},
{
"code": null,
"e": 861,
"s": 832,
"text": "gfg.php\nindex.html\ngeeks.php"
},
{
"code": null,
"e": 877,
"s": 861,
"text": "exec() Function"
},
{
"code": null,
"e": 1062,
"s": 877,
"text": "The exec() function is an inbuilt function in PHP which is used to execute an external program and returns the last line of the output. It also returns NULL if no command run properly."
},
{
"code": null,
"e": 1070,
"s": 1062,
"text": "Syntax:"
},
{
"code": null,
"e": 1116,
"s": 1070,
"text": "string exec( $command, $output, $return_var )"
},
{
"code": null,
"e": 1207,
"s": 1116,
"text": "Parameters: This function accepts three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 1284,
"s": 1207,
"text": "$command: This parameter is used to hold the command which will be executed."
},
{
"code": null,
"e": 1402,
"s": 1284,
"text": "$output: This parameter is used to specify the array which will be filled with every line of output from the command."
},
{
"code": null,
"e": 1569,
"s": 1402,
"text": "$return_var: The $return_var parameter is present along with the output argument, then it returns the status of the executed command will be written to this variable."
},
{
"code": null,
"e": 1672,
"s": 1569,
"text": "Return Value: This function returns the executed command, be sure to set and use the output parameter."
},
{
"code": null,
"e": 1681,
"s": 1672,
"text": "Example:"
},
{
"code": "<?php// (on a system with the \"iamexecfunction\" executable in the path)echo exec('iamexecfunction');?>",
"e": 1784,
"s": 1681,
"text": null
},
{
"code": null,
"e": 1792,
"s": 1784,
"text": "Output:"
},
{
"code": null,
"e": 1802,
"s": 1792,
"text": "geeks.php"
},
{
"code": null,
"e": 1814,
"s": 1802,
"text": "References:"
},
{
"code": null,
"e": 1863,
"s": 1814,
"text": "http://php.net/manual/en/function.shell-exec.php"
},
{
"code": null,
"e": 1906,
"s": 1863,
"text": "http://php.net/manual/en/function.exec.php"
},
{
"code": null,
"e": 2075,
"s": 1906,
"text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples."
},
{
"code": null,
"e": 2088,
"s": 2075,
"text": "PHP-function"
},
{
"code": null,
"e": 2092,
"s": 2088,
"text": "PHP"
},
{
"code": null,
"e": 2109,
"s": 2092,
"text": "Web Technologies"
},
{
"code": null,
"e": 2113,
"s": 2109,
"text": "PHP"
}
] |
How to find all elements in a given array except for the first one using JavaScript ? | 18 Aug, 2021
In this article, we will learn how to find all elements in a given array except for the first one.
Method 1: Using for loopIn this method, we will use a for loop to grab all the elements except first. We know that in an array the first element is present at index ‘0’. We will run a loop from 1 to array.length and saving those remaining elements to another array.
Example:
Javascript
<script> //Javascript program to find all //element of an array except first //function which takes an array as argument const print = (arr) => { //creating a dummy array to store result const find = [] //a counter for adding result let k = 0 for (let i = 1; i < arr.length; i++) { find[k] = arr[i] k++ } //returning resultant array return find } //input array const arr = [1, 2, 3, 4, 5] //printing the result console.log(print(arr))</script>
Output:
[ 2, 3, 4, 5 ]
Method 2: Using slice() method
The slice()It is a method that returns a slice of an array. It takes two arguments, the start and end index.
Example:
Javascript
<script> //Javascript program to find all //element of array except first //function which takes an array as argument const print = (arr) => { //returning resultant array return arr.slice(1) } //input array const arr = [10, 20, 30, 40, 50] //printing the result console.log(print(arr))</script>
Output :
[20, 30, 40, 50]
arorakashish0911
javascript-array
JavaScript-Methods
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Aug, 2021"
},
{
"code": null,
"e": 153,
"s": 54,
"text": "In this article, we will learn how to find all elements in a given array except for the first one."
},
{
"code": null,
"e": 419,
"s": 153,
"text": "Method 1: Using for loopIn this method, we will use a for loop to grab all the elements except first. We know that in an array the first element is present at index ‘0’. We will run a loop from 1 to array.length and saving those remaining elements to another array."
},
{
"code": null,
"e": 428,
"s": 419,
"text": "Example:"
},
{
"code": null,
"e": 439,
"s": 428,
"text": "Javascript"
},
{
"code": "<script> //Javascript program to find all //element of an array except first //function which takes an array as argument const print = (arr) => { //creating a dummy array to store result const find = [] //a counter for adding result let k = 0 for (let i = 1; i < arr.length; i++) { find[k] = arr[i] k++ } //returning resultant array return find } //input array const arr = [1, 2, 3, 4, 5] //printing the result console.log(print(arr))</script>",
"e": 994,
"s": 439,
"text": null
},
{
"code": null,
"e": 1002,
"s": 994,
"text": "Output:"
},
{
"code": null,
"e": 1017,
"s": 1002,
"text": "[ 2, 3, 4, 5 ]"
},
{
"code": null,
"e": 1048,
"s": 1017,
"text": "Method 2: Using slice() method"
},
{
"code": null,
"e": 1157,
"s": 1048,
"text": "The slice()It is a method that returns a slice of an array. It takes two arguments, the start and end index."
},
{
"code": null,
"e": 1167,
"s": 1157,
"text": "Example: "
},
{
"code": null,
"e": 1178,
"s": 1167,
"text": "Javascript"
},
{
"code": "<script> //Javascript program to find all //element of array except first //function which takes an array as argument const print = (arr) => { //returning resultant array return arr.slice(1) } //input array const arr = [10, 20, 30, 40, 50] //printing the result console.log(print(arr))</script>",
"e": 1517,
"s": 1178,
"text": null
},
{
"code": null,
"e": 1526,
"s": 1517,
"text": "Output :"
},
{
"code": null,
"e": 1543,
"s": 1526,
"text": "[20, 30, 40, 50]"
},
{
"code": null,
"e": 1560,
"s": 1543,
"text": "arorakashish0911"
},
{
"code": null,
"e": 1577,
"s": 1560,
"text": "javascript-array"
},
{
"code": null,
"e": 1596,
"s": 1577,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 1617,
"s": 1596,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 1624,
"s": 1617,
"text": "Picked"
},
{
"code": null,
"e": 1635,
"s": 1624,
"text": "JavaScript"
},
{
"code": null,
"e": 1652,
"s": 1635,
"text": "Web Technologies"
},
{
"code": null,
"e": 1750,
"s": 1652,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1811,
"s": 1750,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1851,
"s": 1811,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1892,
"s": 1851,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1934,
"s": 1892,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 1956,
"s": 1934,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 2018,
"s": 1956,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2051,
"s": 2018,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2112,
"s": 2051,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2162,
"s": 2112,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Latent Dirichlet Allocation | 06 Jun, 2021
Topic modeling is a way of abstract modeling to discover the abstract ‘topics’ that occur in the collections of documents. The idea is that we will perform unsupervised classification on different documents, which find some natural groups in topics. We can answer the following question using topic modeling.
What is the topic/main idea of the document?
Given a document, can we find another document with a similar topic?
How do topics field change over time?
Topic modeling can help in optimizing the search process. In this article, we will be discussing Latent Dirichlet Allocation, a topic modeling process.
Latent Dirichlet allocation is one of the most popular methods for performing topic modeling. Each document consists of various words and each topic can be associated with some words. The aim behind the LDA to find topics that the document belongs to, on the basis of words contains in it. It assumes that documents with similar topics will use a similar group of words. This enables the documents to map the probability distribution over latent topics and topics are probability distribution.
Let’s suppose we have D documents using the vocabulary of V-word types. Each document consists of an N-words token (can be removed or padded ). Now, we assume K topics, this required a K-dimensional vector that represents the topic distribution for the document.
Each topic has a V-dimensional multinomial beta_k over words with a common symmetric prior.
For each topic 1...k:Draw a multinomial over words .
Draw a multinomial over words .
For each document 1...d:Draw a multinomial over topics For each word :Draw a topic with Draw a word W_{N_d} \sim Mult(\varphi).
Draw a multinomial over topics
For each word :Draw a topic with Draw a word W_{N_d} \sim Mult(\varphi).
Draw a topic with
Draw a word W_{N_d} \sim Mult(\varphi).
In the above equation, the LHS represents the probability of generating the original document from the LDA machine.
On the right side of the equation, there are 4 probability terms, the first two terms represent Dirichlet distribution and the other two represent the multinomial distribution. The first and third terms represent the distribution of topics but the second and fourth represent the word distribution. We will discuss the Dirichlet distribution first.
Dirichlet Distribution
Dirichlet’s distribution can be defined as a probability density for a vector-valued input having the same characteristics as our multinomial parameter . It has non-zero values such that:
The Dirichlet distribution is parameterized by the vector α, which has the same number of elements K as the multinomial parameter θ.
We can interpret p(θ|α) as answering the question “what is the probability density associated with multinomial distribution θ, given that our Dirichlet distribution has parameter α?”.
Dirichlet distribution
Above is the visualization of the Dirichlet distribution, for our purpose, we can assume that corners/vertices represent the topics with words inside the triangle (the word is closer to the topic if it frequently relates with it. ) or vice-versa.
This distribution can be extended to more than 3-dimensions. For 4-dimension we can use tetrahedron and for further dimension. We can use k-1 dimensions simplex.
The inference problem in LDA to compute the posterior of the hidden variables given the document and corpus parameter \alpha and \beta. That is to compute the P(
Let’s consider we have two categories of topics, we have a word vector for each topic consisting of some words. Following are the words that represented different topics:
Now, we have some document, and we scan some documents for these words:
Now, we update the above words to topics matrix using the probabilities from document matrix below.
In this implementation, we use scikit-learn and pyLDAvis. For datasets, we use yelp reviews datasets that can be found on the Yelp website.
Python3
# install pyldavis!pip install pyldavis# imports!pip install gensim pyLDAvis! python3 -m spacy download en_core_web_sm import pandas as pdimport numpy as np import stringimport spacyimport nltk import gensimfrom gensim import corpora import matplotlib.pyplot as plt import pyLDAvisimport pyLDAvis.gensim_models nltk.download('wordnet')from nltk.corpus import wordnet as wnnltk.download('stopwords')from nltk.corpus import stopwordsimport spacy.clispacy.cli.download("en_core_web_md")import en_core_web_md# fetch yelp review dataset and clean ityelp_review = pd.read_csv('/content/yelp.csv')yelp_review.head()# print number of document and topicsprint(len(yelp_review))print("Unique Business")print(len(yelp_review.groupby('business_id')))print("Unique User")print(len(yelp_review.groupby('user_id'))) # clean the document and remove punctuationdef clean_text(text): delete_dict = {sp_char: '' for sp_char in string.punctuation} delete_dict[' '] =' ' table = str.maketrans(delete_dict) text1 = text.translate(table) textArr= text1.split() text2 = ' '.join([w for w in textArr if ( not w.isdigit() and ( not w.isdigit() and len(w)>3))]) return text2.lower() yelp_review['text'] = yelp_review['text'].apply(clean_text)yelp_review['Num_words_text'] = yelp_review['text'].apply(lambda x:len(str(x).split())) print('-------Reviews By Stars --------')print(yelp_review['stars'].value_counts())print(len(yelp_review))print('-------------------------')max_review_data_sentence_length = yelp_review['Num_words_text'].max() # print short review (mask = (yelp_review['Num_words_text'] < 100) & (yelp_review['Num_words_text'] >=20)df_short_reviews = yelp_review[mask]df_sampled = df_short_reviews.groupby('stars') .apply(lambda x: x.sample(n=100)).reset_index(drop = True) print('No of Short reviews')print(len(df_short_reviews)) # function to remove stopwordsdef remove_stopwords(text): textArr = text.split(' ') rem_text = " ".join([i for i in textArr if i not in stop_words]) return rem_text # remove stopwords from the textstop_words = stopwords.words('english')df_sampled['text']=df_sampled['text'].apply(remove_stopwords) # perform Lemmatizationlp = en_core_web_md.load(disable=['parser', 'ner'])def lemmatization(texts,allowed_postags=['NOUN', 'ADJ']): output = [] for sent in texts: doc = nlp(sent) output.append([token.lemma_ for token in doc if token.pos_ in allowed_postags ]) return outputtext_list=df_sampled['text'].tolist()print(text_list[2])tokenized_reviews = lemmatization(text_list)print(tokenized_reviews[2]) # convert to document term frequency:dictionary = corpora.Dictionary(tokenized_reviews)doc_term_matrix = [dictionary.doc2bow(rev) for rev in tokenized_reviews] # Creating the object for LDA model using gensim libraryLDA = gensim.models.ldamodel.LdaModel # Build LDA modellda_model = LDA(corpus=doc_term_matrix, id2word=dictionary, num_topics=10, random_state=100, chunksize=1000, passes=50,iterations=100)# print lda topics with respect to each word of documentlda_model.print_topics() # calculate perplexity and coherenceprint('\Perplexity: ', lda_model.log_perplexity(doc_term_matrix, total_docs=10000)) # calculate coherencecoherence_model_lda = CoherenceModel(model=lda_model, texts=tokenized_reviews, dictionary=dictionary , coherence='c_v')coherence_lda = coherence_model_lda.get_coherence()print('Coherence: ', coherence_lda) # Now, we use pyLDA vis to visualize itpyLDAvis.sklearn.prepare(lda_tf, dtm_tf, tf_vectorizer)
Total reviews
10000
Unique Business
4174
Unique User
6403
--------------
-------Reviews by stars --------
4 3526
5 3337
3 1461
2 927
1 749
Name: stars, dtype: int64
10000
-------------------------
No of Short reviews
6276
-------------------------
# review and tokenized version
decided completely write place three times tried closed website posted hours open wants drive suburbs
youd better call first place cannot trusted wasted time spent hungry minutes walking disappointed vitamin
fail said
['place', 'time', 'closed', 'website', 'hour', 'open', 'drive', 'suburb', 'first', 'place', 'time', 'hungry',
'minute', 'vitamin']
---------------------------
# LDA print topics
[(0,
'0.015*"food" + 0.013*"good" + 0.010*"gelato" + 0.008*"sandwich" + 0.008*"chocolate" + 0.005*"wife" + 0.005*"next" + 0.005*"bad" + 0.005*"night" + 0.005*"sauce"'),
(1,
'0.030*"food" + 0.021*"great" + 0.019*"place" + 0.019*"good" + 0.016*"service" + 0.011*"time" + 0.011*"nice" + 0.008*"lunch" + 0.008*"dish" + 0.007*"staff"'),
(2,
'0.023*"food" + 0.023*"good" + 0.018*"place" + 0.014*"great" + 0.009*"star" + 0.009*"service" + 0.008*"store" + 0.007*"salad" + 0.007*"well" + 0.006*"pizza"'),
(3,
'0.035*"good" + 0.025*"place" + 0.023*"food" + 0.020*"time" + 0.015*"service" + 0.012*"great" + 0.009*"friend" + 0.008*"table" + 0.008*"chicken" + 0.007*"hour"'),
(4,
'0.020*"food" + 0.019*"time" + 0.012*"good" + 0.009*"restaurant" + 0.009*"great" + 0.008*"service" + 0.007*"order" + 0.006*"small" + 0.006*"hour" + 0.006*"next"'),
(5,
'0.012*"drink" + 0.009*"star" + 0.006*"worth" + 0.006*"place" + 0.006*"friend" + 0.005*"great" + 0.005*"kid" + 0.005*"drive" + 0.005*"simple" + 0.005*"experience"'),
(6,
'0.024*"place" + 0.015*"time" + 0.012*"food" + 0.011*"price" + 0.009*"good" + 0.009*"great" + 0.009*"kid" + 0.008*"staff" + 0.008*"nice" + 0.007*"happy"'),
(7,
'0.028*"place" + 0.019*"service" + 0.015*"good" + 0.014*"pizza" + 0.014*"time" + 0.013*"food" + 0.013*"great" + 0.011*"well" + 0.009*"order" + 0.007*"price"'),
(8,
'0.032*"food" + 0.026*"good" + 0.026*"place" + 0.015*"great" + 0.009*"service" + 0.008*"time" + 0.006*"price" + 0.006*"meal" + 0.006*"shop" + 0.006*"coffee"'),
(9,
'0.020*"food" + 0.014*"place" + 0.011*"meat" + 0.010*"line" + 0.009*"good" + 0.009*"minute" + 0.008*"time" + 0.008*"chicken" + 0.008*"wing" + 0.007*"hour"')]
------------------------------
PyLDAvis Visualization
anikaseth98
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Information Retrieval?
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Sequential Covering Algorithm
ML | Expectation-Maximization Algorithm
Iterate over a list in Python
How to iterate through Excel rows in Python?
Read JSON file using Python
Python map() function
Rotate axis tick labels in Seaborn and Matplotlib | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 337,
"s": 28,
"text": "Topic modeling is a way of abstract modeling to discover the abstract ‘topics’ that occur in the collections of documents. The idea is that we will perform unsupervised classification on different documents, which find some natural groups in topics. We can answer the following question using topic modeling."
},
{
"code": null,
"e": 382,
"s": 337,
"text": "What is the topic/main idea of the document?"
},
{
"code": null,
"e": 451,
"s": 382,
"text": "Given a document, can we find another document with a similar topic?"
},
{
"code": null,
"e": 489,
"s": 451,
"text": "How do topics field change over time?"
},
{
"code": null,
"e": 641,
"s": 489,
"text": "Topic modeling can help in optimizing the search process. In this article, we will be discussing Latent Dirichlet Allocation, a topic modeling process."
},
{
"code": null,
"e": 1135,
"s": 641,
"text": "Latent Dirichlet allocation is one of the most popular methods for performing topic modeling. Each document consists of various words and each topic can be associated with some words. The aim behind the LDA to find topics that the document belongs to, on the basis of words contains in it. It assumes that documents with similar topics will use a similar group of words. This enables the documents to map the probability distribution over latent topics and topics are probability distribution."
},
{
"code": null,
"e": 1398,
"s": 1135,
"text": "Let’s suppose we have D documents using the vocabulary of V-word types. Each document consists of an N-words token (can be removed or padded ). Now, we assume K topics, this required a K-dimensional vector that represents the topic distribution for the document."
},
{
"code": null,
"e": 1490,
"s": 1398,
"text": "Each topic has a V-dimensional multinomial beta_k over words with a common symmetric prior."
},
{
"code": null,
"e": 1543,
"s": 1490,
"text": "For each topic 1...k:Draw a multinomial over words ."
},
{
"code": null,
"e": 1575,
"s": 1543,
"text": "Draw a multinomial over words ."
},
{
"code": null,
"e": 1704,
"s": 1575,
"text": "For each document 1...d:Draw a multinomial over topics For each word :Draw a topic with Draw a word W_{N_d} \\sim Mult(\\varphi)."
},
{
"code": null,
"e": 1736,
"s": 1704,
"text": "Draw a multinomial over topics "
},
{
"code": null,
"e": 1810,
"s": 1736,
"text": "For each word :Draw a topic with Draw a word W_{N_d} \\sim Mult(\\varphi)."
},
{
"code": null,
"e": 1830,
"s": 1810,
"text": "Draw a topic with "
},
{
"code": null,
"e": 1870,
"s": 1830,
"text": "Draw a word W_{N_d} \\sim Mult(\\varphi)."
},
{
"code": null,
"e": 1986,
"s": 1870,
"text": "In the above equation, the LHS represents the probability of generating the original document from the LDA machine."
},
{
"code": null,
"e": 2335,
"s": 1986,
"text": "On the right side of the equation, there are 4 probability terms, the first two terms represent Dirichlet distribution and the other two represent the multinomial distribution. The first and third terms represent the distribution of topics but the second and fourth represent the word distribution. We will discuss the Dirichlet distribution first."
},
{
"code": null,
"e": 2358,
"s": 2335,
"text": "Dirichlet Distribution"
},
{
"code": null,
"e": 2546,
"s": 2358,
"text": "Dirichlet’s distribution can be defined as a probability density for a vector-valued input having the same characteristics as our multinomial parameter . It has non-zero values such that:"
},
{
"code": null,
"e": 2679,
"s": 2546,
"text": "The Dirichlet distribution is parameterized by the vector α, which has the same number of elements K as the multinomial parameter θ."
},
{
"code": null,
"e": 2863,
"s": 2679,
"text": "We can interpret p(θ|α) as answering the question “what is the probability density associated with multinomial distribution θ, given that our Dirichlet distribution has parameter α?”."
},
{
"code": null,
"e": 2886,
"s": 2863,
"text": "Dirichlet distribution"
},
{
"code": null,
"e": 3133,
"s": 2886,
"text": "Above is the visualization of the Dirichlet distribution, for our purpose, we can assume that corners/vertices represent the topics with words inside the triangle (the word is closer to the topic if it frequently relates with it. ) or vice-versa."
},
{
"code": null,
"e": 3295,
"s": 3133,
"text": "This distribution can be extended to more than 3-dimensions. For 4-dimension we can use tetrahedron and for further dimension. We can use k-1 dimensions simplex."
},
{
"code": null,
"e": 3457,
"s": 3295,
"text": "The inference problem in LDA to compute the posterior of the hidden variables given the document and corpus parameter \\alpha and \\beta. That is to compute the P("
},
{
"code": null,
"e": 3628,
"s": 3457,
"text": "Let’s consider we have two categories of topics, we have a word vector for each topic consisting of some words. Following are the words that represented different topics:"
},
{
"code": null,
"e": 3700,
"s": 3628,
"text": "Now, we have some document, and we scan some documents for these words:"
},
{
"code": null,
"e": 3800,
"s": 3700,
"text": "Now, we update the above words to topics matrix using the probabilities from document matrix below."
},
{
"code": null,
"e": 3940,
"s": 3800,
"text": "In this implementation, we use scikit-learn and pyLDAvis. For datasets, we use yelp reviews datasets that can be found on the Yelp website."
},
{
"code": null,
"e": 3948,
"s": 3940,
"text": "Python3"
},
{
"code": "# install pyldavis!pip install pyldavis# imports!pip install gensim pyLDAvis! python3 -m spacy download en_core_web_sm import pandas as pdimport numpy as np import stringimport spacyimport nltk import gensimfrom gensim import corpora import matplotlib.pyplot as plt import pyLDAvisimport pyLDAvis.gensim_models nltk.download('wordnet')from nltk.corpus import wordnet as wnnltk.download('stopwords')from nltk.corpus import stopwordsimport spacy.clispacy.cli.download(\"en_core_web_md\")import en_core_web_md# fetch yelp review dataset and clean ityelp_review = pd.read_csv('/content/yelp.csv')yelp_review.head()# print number of document and topicsprint(len(yelp_review))print(\"Unique Business\")print(len(yelp_review.groupby('business_id')))print(\"Unique User\")print(len(yelp_review.groupby('user_id'))) # clean the document and remove punctuationdef clean_text(text): delete_dict = {sp_char: '' for sp_char in string.punctuation} delete_dict[' '] =' ' table = str.maketrans(delete_dict) text1 = text.translate(table) textArr= text1.split() text2 = ' '.join([w for w in textArr if ( not w.isdigit() and ( not w.isdigit() and len(w)>3))]) return text2.lower() yelp_review['text'] = yelp_review['text'].apply(clean_text)yelp_review['Num_words_text'] = yelp_review['text'].apply(lambda x:len(str(x).split())) print('-------Reviews By Stars --------')print(yelp_review['stars'].value_counts())print(len(yelp_review))print('-------------------------')max_review_data_sentence_length = yelp_review['Num_words_text'].max() # print short review (mask = (yelp_review['Num_words_text'] < 100) & (yelp_review['Num_words_text'] >=20)df_short_reviews = yelp_review[mask]df_sampled = df_short_reviews.groupby('stars') .apply(lambda x: x.sample(n=100)).reset_index(drop = True) print('No of Short reviews')print(len(df_short_reviews)) # function to remove stopwordsdef remove_stopwords(text): textArr = text.split(' ') rem_text = \" \".join([i for i in textArr if i not in stop_words]) return rem_text # remove stopwords from the textstop_words = stopwords.words('english')df_sampled['text']=df_sampled['text'].apply(remove_stopwords) # perform Lemmatizationlp = en_core_web_md.load(disable=['parser', 'ner'])def lemmatization(texts,allowed_postags=['NOUN', 'ADJ']): output = [] for sent in texts: doc = nlp(sent) output.append([token.lemma_ for token in doc if token.pos_ in allowed_postags ]) return outputtext_list=df_sampled['text'].tolist()print(text_list[2])tokenized_reviews = lemmatization(text_list)print(tokenized_reviews[2]) # convert to document term frequency:dictionary = corpora.Dictionary(tokenized_reviews)doc_term_matrix = [dictionary.doc2bow(rev) for rev in tokenized_reviews] # Creating the object for LDA model using gensim libraryLDA = gensim.models.ldamodel.LdaModel # Build LDA modellda_model = LDA(corpus=doc_term_matrix, id2word=dictionary, num_topics=10, random_state=100, chunksize=1000, passes=50,iterations=100)# print lda topics with respect to each word of documentlda_model.print_topics() # calculate perplexity and coherenceprint('\\Perplexity: ', lda_model.log_perplexity(doc_term_matrix, total_docs=10000)) # calculate coherencecoherence_model_lda = CoherenceModel(model=lda_model, texts=tokenized_reviews, dictionary=dictionary , coherence='c_v')coherence_lda = coherence_model_lda.get_coherence()print('Coherence: ', coherence_lda) # Now, we use pyLDA vis to visualize itpyLDAvis.sklearn.prepare(lda_tf, dtm_tf, tf_vectorizer)",
"e": 7674,
"s": 3948,
"text": null
},
{
"code": null,
"e": 10081,
"s": 7674,
"text": "Total reviews\n10000\nUnique Business\n4174\nUnique User\n6403\n--------------\n-------Reviews by stars --------\n4 3526\n5 3337\n3 1461\n2 927\n1 749\nName: stars, dtype: int64\n10000\n-------------------------\nNo of Short reviews\n6276\n-------------------------\n# review and tokenized version\ndecided completely write place three times tried closed website posted hours open wants drive suburbs\n youd better call first place cannot trusted wasted time spent hungry minutes walking disappointed vitamin\n fail said\n\n['place', 'time', 'closed', 'website', 'hour', 'open', 'drive', 'suburb', 'first', 'place', 'time', 'hungry', \n'minute', 'vitamin']\n---------------------------\n# LDA print topics\n[(0,\n '0.015*\"food\" + 0.013*\"good\" + 0.010*\"gelato\" + 0.008*\"sandwich\" + 0.008*\"chocolate\" + 0.005*\"wife\" + 0.005*\"next\" + 0.005*\"bad\" + 0.005*\"night\" + 0.005*\"sauce\"'),\n (1,\n '0.030*\"food\" + 0.021*\"great\" + 0.019*\"place\" + 0.019*\"good\" + 0.016*\"service\" + 0.011*\"time\" + 0.011*\"nice\" + 0.008*\"lunch\" + 0.008*\"dish\" + 0.007*\"staff\"'),\n (2,\n '0.023*\"food\" + 0.023*\"good\" + 0.018*\"place\" + 0.014*\"great\" + 0.009*\"star\" + 0.009*\"service\" + 0.008*\"store\" + 0.007*\"salad\" + 0.007*\"well\" + 0.006*\"pizza\"'),\n (3,\n '0.035*\"good\" + 0.025*\"place\" + 0.023*\"food\" + 0.020*\"time\" + 0.015*\"service\" + 0.012*\"great\" + 0.009*\"friend\" + 0.008*\"table\" + 0.008*\"chicken\" + 0.007*\"hour\"'),\n (4,\n '0.020*\"food\" + 0.019*\"time\" + 0.012*\"good\" + 0.009*\"restaurant\" + 0.009*\"great\" + 0.008*\"service\" + 0.007*\"order\" + 0.006*\"small\" + 0.006*\"hour\" + 0.006*\"next\"'),\n (5,\n '0.012*\"drink\" + 0.009*\"star\" + 0.006*\"worth\" + 0.006*\"place\" + 0.006*\"friend\" + 0.005*\"great\" + 0.005*\"kid\" + 0.005*\"drive\" + 0.005*\"simple\" + 0.005*\"experience\"'),\n (6,\n '0.024*\"place\" + 0.015*\"time\" + 0.012*\"food\" + 0.011*\"price\" + 0.009*\"good\" + 0.009*\"great\" + 0.009*\"kid\" + 0.008*\"staff\" + 0.008*\"nice\" + 0.007*\"happy\"'),\n (7,\n '0.028*\"place\" + 0.019*\"service\" + 0.015*\"good\" + 0.014*\"pizza\" + 0.014*\"time\" + 0.013*\"food\" + 0.013*\"great\" + 0.011*\"well\" + 0.009*\"order\" + 0.007*\"price\"'),\n (8,\n '0.032*\"food\" + 0.026*\"good\" + 0.026*\"place\" + 0.015*\"great\" + 0.009*\"service\" + 0.008*\"time\" + 0.006*\"price\" + 0.006*\"meal\" + 0.006*\"shop\" + 0.006*\"coffee\"'),\n (9,\n '0.020*\"food\" + 0.014*\"place\" + 0.011*\"meat\" + 0.010*\"line\" + 0.009*\"good\" + 0.009*\"minute\" + 0.008*\"time\" + 0.008*\"chicken\" + 0.008*\"wing\" + 0.007*\"hour\"')]\n------------------------------"
},
{
"code": null,
"e": 10104,
"s": 10081,
"text": "PyLDAvis Visualization"
},
{
"code": null,
"e": 10116,
"s": 10104,
"text": "anikaseth98"
},
{
"code": null,
"e": 10133,
"s": 10116,
"text": "Machine Learning"
},
{
"code": null,
"e": 10140,
"s": 10133,
"text": "Python"
},
{
"code": null,
"e": 10157,
"s": 10140,
"text": "Machine Learning"
},
{
"code": null,
"e": 10255,
"s": 10157,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10286,
"s": 10255,
"text": "What is Information Retrieval?"
},
{
"code": null,
"e": 10327,
"s": 10286,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 10360,
"s": 10327,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 10390,
"s": 10360,
"text": "Sequential Covering Algorithm"
},
{
"code": null,
"e": 10430,
"s": 10390,
"text": "ML | Expectation-Maximization Algorithm"
},
{
"code": null,
"e": 10460,
"s": 10430,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 10505,
"s": 10460,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 10533,
"s": 10505,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 10555,
"s": 10533,
"text": "Python map() function"
}
] |
Difference between mysqli_fetch_array() & mysqli_fetch_object() in PHP | 28 Apr, 2022
In this article, we will see the mysqli_fetch_array() & mysqli_fetch_object() function in PHP. The mysqli_fetch_object() function returns objects from the database, whereas mysqli_fetch_array() function delivers an array of results. This will allow field names to be used to access the data.
mysqli_fetch_object() function: This function returns an object with properties that match the fetched row’s properties and advances the internal data pointer. We can only access the data by the specific field names, and not by their offsets. It returns an object containing properties that match the fetched row, or FALSE if no further rows are available.
Syntax:
mysqli_fetch_object(data);
Parameters:
data: The data resource that is being evaluated. This result comes from a call to mysqli_query() function.
Example: This example describes the mysqli_fetch_object() function that fetches the next row of a result set as an object.
Suppose we have table named students which have the following data values:
Create table:
CREATE TABLE students (
student_id int(10),
student_name VARCHAR(20)
)
Insert into the table:
Insert into students(
student_id, student_name
) Values(01, 'Abc')
Insert into Students(
student_id, student_name
) Values(02, 'Xyz')
After creating the table, the following table structure will appear.
PHP
<?php $con = mysqli_connect("localhost", "root", "", "mydb") or die(mysqli_error($con)); $select_query = "SELECT * FROM students"; $select_query_result = mysqli_query($con, $select_query) or die(mysqli_error($con)); while ($row = mysqli_fetch_object($select_query_result)) { echo $row->student_id; echo " "; echo $row->student_name;} mysqli_free_result($select_query_result); ?>
Output:
01 Abc
02 Xyz
mysqli_fetch_array() function: It is used to fetch rows from the database and store them as an array. The array can be fetched as an associative array, as a numeric array, or both.
Syntax:
mysqli_fetch_array(result, arrayType);
Parameters:
result: The result of resource that is being evaluated. This result comes from a call to mysqli_query() function.
arrayType: The type of array that is to be fetched. It’s a constant and can take the following values: MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH.
Example: This example describes the mysqli_fetch_array() function that returns an array that corresponds to the fetched row & moves the internal data pointer ahead.
Suppose we have table named students which have the following data values:
Create table:
CREATE TABLE students (
student_id int(10),
student_name VARCHAR(20)
)
Insert into the table:
Insert into students(
student_id, student_name
) Values(01, 'Abc')
Insert into Students(
student_id, student_name
) Values(02, 'Xyz')
After creating the table, the following table structure will appear.
PHP
<?php $con = mysqli_connect("localhost", "root", "", "mydb") or die(mysqli_error($con)); $select_query = "SELECT * FROM students"; $select_query_result = mysqli_query($con, $select_query) or die(mysqli_error($con)); while ($row = mysqli_fetch_array($select_query_result)) { echo $row['student_id'] . " " . $row['student_name'];} mysqli_free_result($select_query_result); ?>
Output:
01 Abc
02 Xyz
Difference between mysqli_fetch_array() and mysqli_fetch_object() Function:
mysqli_fetch_object() function: Fetch a result row as an object.
mysqli_fetch_array() function: Fetch a result row as a combination of associative array and regular array.
Let us see the differences in a tabular form -:
Its syntax is -:
$mysqli_result -> fetch_array(result_type)
Its syntax is -:
$mysqli_result -> fetch_object(classname, params)
mayank007rawa
PHP-function
PHP-Questions
Picked
Difference Between
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Compile-time and Run-time Polymorphism in Java
Similarities and Difference between Java and C++
Difference between Internal and External fragmentation
How to execute PHP code using command line ?
PHP in_array() Function
How to delete an array element based on key in PHP?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Apr, 2022"
},
{
"code": null,
"e": 321,
"s": 28,
"text": "In this article, we will see the mysqli_fetch_array() & mysqli_fetch_object() function in PHP. The mysqli_fetch_object() function returns objects from the database, whereas mysqli_fetch_array() function delivers an array of results. This will allow field names to be used to access the data."
},
{
"code": null,
"e": 678,
"s": 321,
"text": "mysqli_fetch_object() function: This function returns an object with properties that match the fetched row’s properties and advances the internal data pointer. We can only access the data by the specific field names, and not by their offsets. It returns an object containing properties that match the fetched row, or FALSE if no further rows are available."
},
{
"code": null,
"e": 686,
"s": 678,
"text": "Syntax:"
},
{
"code": null,
"e": 713,
"s": 686,
"text": "mysqli_fetch_object(data);"
},
{
"code": null,
"e": 725,
"s": 713,
"text": "Parameters:"
},
{
"code": null,
"e": 832,
"s": 725,
"text": "data: The data resource that is being evaluated. This result comes from a call to mysqli_query() function."
},
{
"code": null,
"e": 955,
"s": 832,
"text": "Example: This example describes the mysqli_fetch_object() function that fetches the next row of a result set as an object."
},
{
"code": null,
"e": 1030,
"s": 955,
"text": "Suppose we have table named students which have the following data values:"
},
{
"code": null,
"e": 1044,
"s": 1030,
"text": "Create table:"
},
{
"code": null,
"e": 1123,
"s": 1044,
"text": "CREATE TABLE students (\n student_id int(10),\n student_name VARCHAR(20)\n)"
},
{
"code": null,
"e": 1146,
"s": 1123,
"text": "Insert into the table:"
},
{
"code": null,
"e": 1289,
"s": 1146,
"text": "Insert into students(\n student_id, student_name\n) Values(01, 'Abc')\n\nInsert into Students(\n student_id, student_name\n) Values(02, 'Xyz')"
},
{
"code": null,
"e": 1358,
"s": 1289,
"text": "After creating the table, the following table structure will appear."
},
{
"code": null,
"e": 1362,
"s": 1358,
"text": "PHP"
},
{
"code": "<?php $con = mysqli_connect(\"localhost\", \"root\", \"\", \"mydb\") or die(mysqli_error($con)); $select_query = \"SELECT * FROM students\"; $select_query_result = mysqli_query($con, $select_query) or die(mysqli_error($con)); while ($row = mysqli_fetch_object($select_query_result)) { echo $row->student_id; echo \" \"; echo $row->student_name;} mysqli_free_result($select_query_result); ?>",
"e": 1756,
"s": 1362,
"text": null
},
{
"code": null,
"e": 1764,
"s": 1756,
"text": "Output:"
},
{
"code": null,
"e": 1778,
"s": 1764,
"text": "01 Abc\n02 Xyz"
},
{
"code": null,
"e": 1959,
"s": 1778,
"text": "mysqli_fetch_array() function: It is used to fetch rows from the database and store them as an array. The array can be fetched as an associative array, as a numeric array, or both."
},
{
"code": null,
"e": 1967,
"s": 1959,
"text": "Syntax:"
},
{
"code": null,
"e": 2006,
"s": 1967,
"text": "mysqli_fetch_array(result, arrayType);"
},
{
"code": null,
"e": 2018,
"s": 2006,
"text": "Parameters:"
},
{
"code": null,
"e": 2132,
"s": 2018,
"text": "result: The result of resource that is being evaluated. This result comes from a call to mysqli_query() function."
},
{
"code": null,
"e": 2277,
"s": 2132,
"text": "arrayType: The type of array that is to be fetched. It’s a constant and can take the following values: MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH."
},
{
"code": null,
"e": 2442,
"s": 2277,
"text": "Example: This example describes the mysqli_fetch_array() function that returns an array that corresponds to the fetched row & moves the internal data pointer ahead."
},
{
"code": null,
"e": 2517,
"s": 2442,
"text": "Suppose we have table named students which have the following data values:"
},
{
"code": null,
"e": 2531,
"s": 2517,
"text": "Create table:"
},
{
"code": null,
"e": 2610,
"s": 2531,
"text": "CREATE TABLE students (\n student_id int(10),\n student_name VARCHAR(20)\n)"
},
{
"code": null,
"e": 2633,
"s": 2610,
"text": "Insert into the table:"
},
{
"code": null,
"e": 2776,
"s": 2633,
"text": "Insert into students(\n student_id, student_name\n) Values(01, 'Abc')\n\nInsert into Students(\n student_id, student_name\n) Values(02, 'Xyz')"
},
{
"code": null,
"e": 2845,
"s": 2776,
"text": "After creating the table, the following table structure will appear."
},
{
"code": null,
"e": 2849,
"s": 2845,
"text": "PHP"
},
{
"code": "<?php $con = mysqli_connect(\"localhost\", \"root\", \"\", \"mydb\") or die(mysqli_error($con)); $select_query = \"SELECT * FROM students\"; $select_query_result = mysqli_query($con, $select_query) or die(mysqli_error($con)); while ($row = mysqli_fetch_array($select_query_result)) { echo $row['student_id'] . \" \" . $row['student_name'];} mysqli_free_result($select_query_result); ?>",
"e": 3232,
"s": 2849,
"text": null
},
{
"code": null,
"e": 3240,
"s": 3232,
"text": "Output:"
},
{
"code": null,
"e": 3254,
"s": 3240,
"text": "01 Abc\n02 Xyz"
},
{
"code": null,
"e": 3330,
"s": 3254,
"text": "Difference between mysqli_fetch_array() and mysqli_fetch_object() Function:"
},
{
"code": null,
"e": 3395,
"s": 3330,
"text": "mysqli_fetch_object() function: Fetch a result row as an object."
},
{
"code": null,
"e": 3502,
"s": 3395,
"text": "mysqli_fetch_array() function: Fetch a result row as a combination of associative array and regular array."
},
{
"code": null,
"e": 3550,
"s": 3502,
"text": "Let us see the differences in a tabular form -:"
},
{
"code": null,
"e": 3567,
"s": 3550,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 3610,
"s": 3567,
"text": "$mysqli_result -> fetch_array(result_type)"
},
{
"code": null,
"e": 3627,
"s": 3610,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 3677,
"s": 3627,
"text": "$mysqli_result -> fetch_object(classname, params)"
},
{
"code": null,
"e": 3691,
"s": 3677,
"text": "mayank007rawa"
},
{
"code": null,
"e": 3704,
"s": 3691,
"text": "PHP-function"
},
{
"code": null,
"e": 3718,
"s": 3704,
"text": "PHP-Questions"
},
{
"code": null,
"e": 3725,
"s": 3718,
"text": "Picked"
},
{
"code": null,
"e": 3744,
"s": 3725,
"text": "Difference Between"
},
{
"code": null,
"e": 3748,
"s": 3744,
"text": "PHP"
},
{
"code": null,
"e": 3765,
"s": 3748,
"text": "Web Technologies"
},
{
"code": null,
"e": 3769,
"s": 3765,
"text": "PHP"
},
{
"code": null,
"e": 3867,
"s": 3769,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3928,
"s": 3867,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3996,
"s": 3928,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 4062,
"s": 3996,
"text": "Difference between Compile-time and Run-time Polymorphism in Java"
},
{
"code": null,
"e": 4111,
"s": 4062,
"text": "Similarities and Difference between Java and C++"
},
{
"code": null,
"e": 4166,
"s": 4111,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 4211,
"s": 4166,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 4235,
"s": 4211,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 4287,
"s": 4235,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 4337,
"s": 4287,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
Python PIL | getcolors() Method | 02 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.
getcolors() Returns a list of colors used in this image.
Syntax: Image.getcolors(maxcolors=256)
Parameters:maxcolors – Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors.
Returns: An unsorted list of (count, pixel) values.
Image Used:
# importing Image module from PIL package from PIL import Image # opening a image im = Image.open(r"C:\Users\System-Pc\Desktop\lion.png").convert("L") # getting colors # multiband images (RBG) im1 = Image.Image.getcolors(im) print(im1)
Output:
[(38510, 0), (27, 12), (17, 21), (2, 24), (34, 26), (46, 39), (30, 41), (18, 48), (42, 50), (58, 62), (27, 67), (37, 73), (51, 79), (46, 85), (57, 90), (58, 101), (21, 104), (41, 111), (30, 117), (48, 123), (50, 130), (42, 135), (60, 143), (63, 149), (63, 155), (49, 162), (25, 165), (65, 169), (58, 178), (67, 184), (61, 193), (61, 195), (65, 204), (61, 208), (61, 215), (50, 221), (59, 225), (49, 232), (81, 235), (80, 244), (56, 247), (64, 252), (9835, 255)]
Another Example:Here changing image.
Image Used:
# importing Image module from PIL package from PIL import Image # opening a image im = Image.open(r"C:\Users\System-Pc\Desktop\new.jpg").convert("L") # getting colors # multiband images (RBG) im1 = Image.Image.getcolors(im) print(im1)
Output:
[(97, 0), (158, 1), (243, 2), (207, 3), (258, 4), (259, 5), (179, 6), (270, 7), (248, 8), (270, 9), (246, 10), (255, 11), (298, 12), (271, 13), (283, 14), (335, 15), (248, 16), (353, 17), (311, 18), (265, 19), (353, 20), (314, 21), (330, 22), (342, 23), (313, 24), (359, 25), (337, 26), (303, 27), (375, 28), (305, 29), (358, 30), (370, 31), (346, 32), (394, 33), (372, 34), (332, 35), (400, 36), (367, 37), (370, 38), (400, 39), (406, 40), (423, 41), (371, 42), (366, 43), (362, 44), (391, 45), (397, 46), (403, 47), (439, 48), (397, 49), (433, 50), (407, 51), (424, 52), (383, 53), (426, 54), (398, 55), (407, 56), (405, 57), (411, 58), (428, 59), (394, 60), (401, 61), (372, 62), (394, 63), (393, 64), (384, 65), (374, 66), (380, 67), (399, 68), (368, 69), (375, 70), (365, 71), (323, 72), (363, 73), (348, 74), (355, 75), (326, 76), (345, 77), (332, 78), (332, 79), (324, 80), (314, 81), (348, 82), (322, 83), (335, 84), (343, 85), (330, 86), (326, 87), (296, 88), (327, 89), (315, 90), (322, 91), (275, 92), (305, 93), (278, 94), (286, 95), (284, 96), (256, 97), (253, 98), (292, 99), (258, 100), (286, 101), (295, 102), (280, 103), (269, 104), (259, 105), (259, 106), (312, 107), (254, 108), (265, 109), (278, 110), (265, 111), (263, 112), (265, 113), (255, 114), (264, 115), (273, 116), (255, 117), (245, 118), (250, 119), (240, 120), (244, 121), (242, 122), (247, 123), (224, 124), (240, 125), (209, 126), (240, 127), (200, 128), (216, 129), (218, 130), (207, 131), (176, 132), (188, 133), (179, 134), (164, 135), (190, 136), (180, 137), (178, 138), (151, 139), (139, 140), (142, 141), (150, 142), (134, 143), (145, 144), (131, 145), (115, 146), (128, 147), (133, 148), (135, 149), (117, 150), (129, 151), (133, 152), (115, 153), (113, 154), (114, 155), (109, 156), (133, 157), (119, 158), (117, 159), (97, 160), (128, 161), (103, 162), (113, 163), (105, 164), (110, 165), (94, 166), (70, 167), (85, 168), (89, 169), (99, 170), (89, 171), (85, 172), (89, 173), (93, 174), (79, 175), (66, 176), (75, 177), (62, 178), (63, 179), (62, 180), (77, 181), (63, 182), (78, 183), (62, 184), (57, 185), (58, 186), (47, 187), (61, 188), (69, 189), (61, 190), (58, 191), (47, 192), (49, 193), (71, 194), (47, 195), (40, 196), (56, 197), (64, 198), (55, 199), (40, 200), (46, 201), (42, 202), (31, 203), (36, 204), (46, 205), (47, 206), (45, 207), (50, 208), (52, 209), (40, 210), (42, 211), (48, 212), (60, 213), (43, 214), (39, 215), (51, 216), (27, 217), (46, 218), (41, 219), (35, 220), (53, 221), (35, 222), (39, 223), (36, 224), (37, 225), (42, 226), (29, 227), (36, 228), (40, 229), (29, 230), (34, 231), (24, 232), (25, 233), (20, 234), (22, 235), (26, 236), (13, 237), (11, 238), (16, 239), (17, 240), (8, 241), (16, 242), (22, 243), (11, 244), (15, 245), (14, 246), (10, 247), (12, 248), (11, 249), (18, 250), (23, 251), (20, 252), (16, 253), (3, 254)]
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n02 Aug, 2019"
},
{
"code": null,
"e": 380,
"s": 53,
"text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images."
},
{
"code": null,
"e": 437,
"s": 380,
"text": "getcolors() Returns a list of colors used in this image."
},
{
"code": null,
"e": 476,
"s": 437,
"text": "Syntax: Image.getcolors(maxcolors=256)"
},
{
"code": null,
"e": 612,
"s": 476,
"text": "Parameters:maxcolors – Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors."
},
{
"code": null,
"e": 664,
"s": 612,
"text": "Returns: An unsorted list of (count, pixel) values."
},
{
"code": null,
"e": 676,
"s": 664,
"text": "Image Used:"
},
{
"code": " # importing Image module from PIL package from PIL import Image # opening a image im = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\lion.png\").convert(\"L\") # getting colors # multiband images (RBG) im1 = Image.Image.getcolors(im) print(im1) ",
"e": 925,
"s": 676,
"text": null
},
{
"code": null,
"e": 933,
"s": 925,
"text": "Output:"
},
{
"code": null,
"e": 1395,
"s": 933,
"text": "[(38510, 0), (27, 12), (17, 21), (2, 24), (34, 26), (46, 39), (30, 41), (18, 48), (42, 50), (58, 62), (27, 67), (37, 73), (51, 79), (46, 85), (57, 90), (58, 101), (21, 104), (41, 111), (30, 117), (48, 123), (50, 130), (42, 135), (60, 143), (63, 149), (63, 155), (49, 162), (25, 165), (65, 169), (58, 178), (67, 184), (61, 193), (61, 195), (65, 204), (61, 208), (61, 215), (50, 221), (59, 225), (49, 232), (81, 235), (80, 244), (56, 247), (64, 252), (9835, 255)]"
},
{
"code": null,
"e": 1432,
"s": 1395,
"text": "Another Example:Here changing image."
},
{
"code": null,
"e": 1444,
"s": 1432,
"text": "Image Used:"
},
{
"code": " # importing Image module from PIL package from PIL import Image # opening a image im = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\new.jpg\").convert(\"L\") # getting colors # multiband images (RBG) im1 = Image.Image.getcolors(im) print(im1) ",
"e": 1692,
"s": 1444,
"text": null
},
{
"code": null,
"e": 1700,
"s": 1692,
"text": "Output:"
},
{
"code": null,
"e": 4558,
"s": 1700,
"text": "[(97, 0), (158, 1), (243, 2), (207, 3), (258, 4), (259, 5), (179, 6), (270, 7), (248, 8), (270, 9), (246, 10), (255, 11), (298, 12), (271, 13), (283, 14), (335, 15), (248, 16), (353, 17), (311, 18), (265, 19), (353, 20), (314, 21), (330, 22), (342, 23), (313, 24), (359, 25), (337, 26), (303, 27), (375, 28), (305, 29), (358, 30), (370, 31), (346, 32), (394, 33), (372, 34), (332, 35), (400, 36), (367, 37), (370, 38), (400, 39), (406, 40), (423, 41), (371, 42), (366, 43), (362, 44), (391, 45), (397, 46), (403, 47), (439, 48), (397, 49), (433, 50), (407, 51), (424, 52), (383, 53), (426, 54), (398, 55), (407, 56), (405, 57), (411, 58), (428, 59), (394, 60), (401, 61), (372, 62), (394, 63), (393, 64), (384, 65), (374, 66), (380, 67), (399, 68), (368, 69), (375, 70), (365, 71), (323, 72), (363, 73), (348, 74), (355, 75), (326, 76), (345, 77), (332, 78), (332, 79), (324, 80), (314, 81), (348, 82), (322, 83), (335, 84), (343, 85), (330, 86), (326, 87), (296, 88), (327, 89), (315, 90), (322, 91), (275, 92), (305, 93), (278, 94), (286, 95), (284, 96), (256, 97), (253, 98), (292, 99), (258, 100), (286, 101), (295, 102), (280, 103), (269, 104), (259, 105), (259, 106), (312, 107), (254, 108), (265, 109), (278, 110), (265, 111), (263, 112), (265, 113), (255, 114), (264, 115), (273, 116), (255, 117), (245, 118), (250, 119), (240, 120), (244, 121), (242, 122), (247, 123), (224, 124), (240, 125), (209, 126), (240, 127), (200, 128), (216, 129), (218, 130), (207, 131), (176, 132), (188, 133), (179, 134), (164, 135), (190, 136), (180, 137), (178, 138), (151, 139), (139, 140), (142, 141), (150, 142), (134, 143), (145, 144), (131, 145), (115, 146), (128, 147), (133, 148), (135, 149), (117, 150), (129, 151), (133, 152), (115, 153), (113, 154), (114, 155), (109, 156), (133, 157), (119, 158), (117, 159), (97, 160), (128, 161), (103, 162), (113, 163), (105, 164), (110, 165), (94, 166), (70, 167), (85, 168), (89, 169), (99, 170), (89, 171), (85, 172), (89, 173), (93, 174), (79, 175), (66, 176), (75, 177), (62, 178), (63, 179), (62, 180), (77, 181), (63, 182), (78, 183), (62, 184), (57, 185), (58, 186), (47, 187), (61, 188), (69, 189), (61, 190), (58, 191), (47, 192), (49, 193), (71, 194), (47, 195), (40, 196), (56, 197), (64, 198), (55, 199), (40, 200), (46, 201), (42, 202), (31, 203), (36, 204), (46, 205), (47, 206), (45, 207), (50, 208), (52, 209), (40, 210), (42, 211), (48, 212), (60, 213), (43, 214), (39, 215), (51, 216), (27, 217), (46, 218), (41, 219), (35, 220), (53, 221), (35, 222), (39, 223), (36, 224), (37, 225), (42, 226), (29, 227), (36, 228), (40, 229), (29, 230), (34, 231), (24, 232), (25, 233), (20, 234), (22, 235), (26, 236), (13, 237), (11, 238), (16, 239), (17, 240), (8, 241), (16, 242), (22, 243), (11, 244), (15, 245), (14, 246), (10, 247), (12, 248), (11, 249), (18, 250), (23, 251), (20, 252), (16, 253), (3, 254)]"
},
{
"code": null,
"e": 4569,
"s": 4558,
"text": "Python-pil"
},
{
"code": null,
"e": 4576,
"s": 4569,
"text": "Python"
},
{
"code": null,
"e": 4674,
"s": 4576,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4692,
"s": 4674,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4734,
"s": 4692,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4756,
"s": 4734,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4791,
"s": 4756,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4817,
"s": 4791,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4849,
"s": 4817,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4878,
"s": 4849,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4908,
"s": 4878,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 4935,
"s": 4908,
"text": "Python Classes and Objects"
}
] |
How to Create Image Hovered Detail using HTML & CSS ? | 12 May, 2021
In this article, we will learn how to create a type of hover effect over an image to get its complete detail. This is can be achieved by using simple HTML & CSS.
Overview Of Our Project:
Approach:
We will first create an HTML file in which we are going to add an image for our image hanger.
We will then create a CSS style to give animation effects to the element containing the image.
We will start by defining the HTML and CSS sections of the page as given below.
HTML Section: In this section, the structure of the page is defined.
We will first create an HTML file.
We are then going to write out the boilerplate code required for an HTML page.
We will next link the CSS file or directly add the required CSS that provides all the animation effects.
In the body section, we will add an image source so that we can display our image.
index.html
<!DOCTYPE html><html lang="en"> <head> <link rel="stylesheet" href="style.css"></head> <body> <h1>hover over gfg logo --)</h1> <div class="main_box"> <div class="circle"></div> <div class="content"> <h2>GeeksForGeeks</h2> <br> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and much more.. </p> <br> <a href="#">Contact Us</a> </div> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210223165952/gfglogo.png"> </div></body> </html>
CSS Section: In this section, we will define the CSS of the page. Using CSS we will give different types of animations and effects to our HTML page so that it looks interactive to all users.
We will first reset all the browser effects so that everything is consistent on all browsers.
Then we will define the styling to be given to the elements which include the size and position.
We will use clip-path function to give specific shapes to our objects.
style.css
*{ box-sizing: border-box; margin: 0; padding: 0; color: #000;} body{ background-color: rgb(71, 69, 69); display: flex; justify-content: center; align-items: center; min-height: 100vh;} .main_box{ position: relative; width: 42em; height: 25em; display: flex; align-items: center; border-radius: 1.5em; transition: .5s;} .main_box .circle{ position: absolute; top: 6%; left: 0; width: 100%; height: 100%; border-radius: 1.5em; overflow: hidden;} .main_box .circle::before{ content: ''; position: absolute; top: 0%; left: 0; width: 100%; height: 100%; clip-path: circle(7.5em at center); transition: .4s;} h1{ margin-right: 1em ;} .main_box:hover .circle::before{ clip-path: circle(30em at center); background: rgb(20, 220, 43);} .main_box img{ top: 50%; left: 50%; height: 5.75em; transform: translate(-50%,-50%); position: absolute; pointer-events: none; transition: 0.4s;}.main_box:hover img{ left: 80%; top: 12.25em; height: 10em;} .main_box .content{ position: relative; width: 50%; background: rgb(20, 220, 43); padding: 1.25em 1.25em 1.25em 2.5em; transition: .5s; opacity: 0; visibility: hidden;} .main_box:hover .content{ left: 10%; opacity: 1; visibility: visible;} .main_box .content h2{ text-transform: uppercase; font-size: 2em; line-height: 1em;} .main_box .content p{ color: #fff;} .main_box .content a{ position: relative; text-decoration: none; color: rgb(186, 14, 14); padding: .6em 1.25em; margin-top: 0.6em; display: inline-block; }
Output:
CSS-Properties
CSS-Questions
HTML-Questions
HTML-Tags
CSS
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 May, 2021"
},
{
"code": null,
"e": 190,
"s": 28,
"text": "In this article, we will learn how to create a type of hover effect over an image to get its complete detail. This is can be achieved by using simple HTML & CSS."
},
{
"code": null,
"e": 215,
"s": 190,
"text": "Overview Of Our Project:"
},
{
"code": null,
"e": 225,
"s": 215,
"text": "Approach:"
},
{
"code": null,
"e": 319,
"s": 225,
"text": "We will first create an HTML file in which we are going to add an image for our image hanger."
},
{
"code": null,
"e": 414,
"s": 319,
"text": "We will then create a CSS style to give animation effects to the element containing the image."
},
{
"code": null,
"e": 494,
"s": 414,
"text": "We will start by defining the HTML and CSS sections of the page as given below."
},
{
"code": null,
"e": 563,
"s": 494,
"text": "HTML Section: In this section, the structure of the page is defined."
},
{
"code": null,
"e": 598,
"s": 563,
"text": "We will first create an HTML file."
},
{
"code": null,
"e": 677,
"s": 598,
"text": "We are then going to write out the boilerplate code required for an HTML page."
},
{
"code": null,
"e": 782,
"s": 677,
"text": "We will next link the CSS file or directly add the required CSS that provides all the animation effects."
},
{
"code": null,
"e": 865,
"s": 782,
"text": "In the body section, we will add an image source so that we can display our image."
},
{
"code": null,
"e": 876,
"s": 865,
"text": "index.html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <link rel=\"stylesheet\" href=\"style.css\"></head> <body> <h1>hover over gfg logo --)</h1> <div class=\"main_box\"> <div class=\"circle\"></div> <div class=\"content\"> <h2>GeeksForGeeks</h2> <br> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and much more.. </p> <br> <a href=\"#\">Contact Us</a> </div> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210223165952/gfglogo.png\"> </div></body> </html>",
"e": 1609,
"s": 876,
"text": null
},
{
"code": null,
"e": 1801,
"s": 1609,
"text": "CSS Section: In this section, we will define the CSS of the page. Using CSS we will give different types of animations and effects to our HTML page so that it looks interactive to all users. "
},
{
"code": null,
"e": 1895,
"s": 1801,
"text": "We will first reset all the browser effects so that everything is consistent on all browsers."
},
{
"code": null,
"e": 1992,
"s": 1895,
"text": "Then we will define the styling to be given to the elements which include the size and position."
},
{
"code": null,
"e": 2063,
"s": 1992,
"text": "We will use clip-path function to give specific shapes to our objects."
},
{
"code": null,
"e": 2073,
"s": 2063,
"text": "style.css"
},
{
"code": "*{ box-sizing: border-box; margin: 0; padding: 0; color: #000;} body{ background-color: rgb(71, 69, 69); display: flex; justify-content: center; align-items: center; min-height: 100vh;} .main_box{ position: relative; width: 42em; height: 25em; display: flex; align-items: center; border-radius: 1.5em; transition: .5s;} .main_box .circle{ position: absolute; top: 6%; left: 0; width: 100%; height: 100%; border-radius: 1.5em; overflow: hidden;} .main_box .circle::before{ content: ''; position: absolute; top: 0%; left: 0; width: 100%; height: 100%; clip-path: circle(7.5em at center); transition: .4s;} h1{ margin-right: 1em ;} .main_box:hover .circle::before{ clip-path: circle(30em at center); background: rgb(20, 220, 43);} .main_box img{ top: 50%; left: 50%; height: 5.75em; transform: translate(-50%,-50%); position: absolute; pointer-events: none; transition: 0.4s;}.main_box:hover img{ left: 80%; top: 12.25em; height: 10em;} .main_box .content{ position: relative; width: 50%; background: rgb(20, 220, 43); padding: 1.25em 1.25em 1.25em 2.5em; transition: .5s; opacity: 0; visibility: hidden;} .main_box:hover .content{ left: 10%; opacity: 1; visibility: visible;} .main_box .content h2{ text-transform: uppercase; font-size: 2em; line-height: 1em;} .main_box .content p{ color: #fff;} .main_box .content a{ position: relative; text-decoration: none; color: rgb(186, 14, 14); padding: .6em 1.25em; margin-top: 0.6em; display: inline-block; }",
"e": 3733,
"s": 2073,
"text": null
},
{
"code": null,
"e": 3741,
"s": 3733,
"text": "Output:"
},
{
"code": null,
"e": 3756,
"s": 3741,
"text": "CSS-Properties"
},
{
"code": null,
"e": 3770,
"s": 3756,
"text": "CSS-Questions"
},
{
"code": null,
"e": 3785,
"s": 3770,
"text": "HTML-Questions"
},
{
"code": null,
"e": 3795,
"s": 3785,
"text": "HTML-Tags"
},
{
"code": null,
"e": 3799,
"s": 3795,
"text": "CSS"
},
{
"code": null,
"e": 3804,
"s": 3799,
"text": "HTML"
},
{
"code": null,
"e": 3821,
"s": 3804,
"text": "Web Technologies"
},
{
"code": null,
"e": 3826,
"s": 3821,
"text": "HTML"
},
{
"code": null,
"e": 3924,
"s": 3826,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3972,
"s": 3924,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 4034,
"s": 3972,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4084,
"s": 4034,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 4142,
"s": 4084,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 4192,
"s": 4142,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 4240,
"s": 4192,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 4302,
"s": 4240,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4352,
"s": 4302,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 4376,
"s": 4352,
"text": "REST API (Introduction)"
}
] |
Expression Evaluation | 21 Jun, 2022
Evaluate an expression represented by a String. The expression can contain parentheses, you can assume parentheses are well-matched. For simplicity, you can assume only binary operations allowed are +, -, *, and /. Arithmetic Expressions can be written in one of three forms:
Infix Notation: Operators are written between the operands they operate on, e.g. 3 + 4.
Prefix Notation: Operators are written before the operands, e.g + 3 4
Postfix Notation: Operators are written after operands.
Infix Expressions are harder for Computers to evaluate because of the additional work needed to decide precedence. Infix notation is how expressions are written and recognized by humans and, generally, input to programs. Given that they are harder to evaluate, they are generally converted to one of the two remaining forms. A very well known algorithm for converting an infix notation to a postfix notation is Shunting Yard Algorithm by Edgar Dijkstra.
This algorithm takes as input an Infix Expression and produces a queue that has this expression converted to postfix notation. The same algorithm can be modified so that it outputs the result of the evaluation of expression instead of a queue. The trick is using two stacks instead of one, one for operands, and one for operators.
1. While there are still tokens to be read in,
1.1 Get the next token.
1.2 If the token is:
1.2.1 A number: push it onto the value stack.
1.2.2 A variable: get its value, and push onto the value stack.
1.2.3 A left parenthesis: push it onto the operator stack.
1.2.4 A right parenthesis:
1 While the thing on top of the operator stack is not a
left parenthesis,
1 Pop the operator from the operator stack.
2 Pop the value stack twice, getting two operands.
3 Apply the operator to the operands, in the correct order.
4 Push the result onto the value stack.
2 Pop the left parenthesis from the operator stack, and discard it.
1.2.5 An operator (call it thisOp):
1 While the operator stack is not empty, and the top thing on the
operator stack has the same or greater precedence as thisOp,
1 Pop the operator from the operator stack.
2 Pop the value stack twice, getting two operands.
3 Apply the operator to the operands, in the correct order.
4 Push the result onto the value stack.
2 Push thisOp onto the operator stack.
2. While the operator stack is not empty,
1 Pop the operator from the operator stack.
2 Pop the value stack twice, getting two operands.
3 Apply the operator to the operands, in the correct order.
4 Push the result onto the value stack.
3. At this point the operator stack should be empty, and the value
stack should have only one value in it, which is the final result.
Implementation: It should be clear that this algorithm runs in linear time – each number or operator is pushed onto and popped from Stack only once.
C++
Java
Python3
C#
Javascript
// CPP program to evaluate a given// expression where tokens are// separated by space.#include <bits/stdc++.h>using namespace std; // Function to find precedence of// operators.int precedence(char op){ if(op == '+'||op == '-') return 1; if(op == '*'||op == '/') return 2; return 0;} // Function to perform arithmetic operations.int applyOp(int a, int b, char op){ switch(op){ case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; }} // Function that returns value of// expression after evaluation.int evaluate(string tokens){ int i; // stack to store integer values. stack <int> values; // stack to store operators. stack <char> ops; for(i = 0; i < tokens.length(); i++){ // Current token is a whitespace, // skip it. if(tokens[i] == ' ') continue; // Current token is an opening // brace, push it to 'ops' else if(tokens[i] == '('){ ops.push(tokens[i]); } // Current token is a number, push // it to stack for numbers. else if(isdigit(tokens[i])){ int val = 0; // There may be more than one // digits in number. while(i < tokens.length() && isdigit(tokens[i])) { val = (val*10) + (tokens[i]-'0'); i++; } values.push(val); // right now the i points to // the character next to the digit, // since the for loop also increases // the i, we would skip one // token position; we need to // decrease the value of i by 1 to // correct the offset. i--; } // Closing brace encountered, solve // entire brace. else if(tokens[i] == ')') { while(!ops.empty() && ops.top() != '(') { int val2 = values.top(); values.pop(); int val1 = values.top(); values.pop(); char op = ops.top(); ops.pop(); values.push(applyOp(val1, val2, op)); } // pop opening brace. if(!ops.empty()) ops.pop(); } // Current token is an operator. else { // While top of 'ops' has same or greater // precedence to current token, which // is an operator. Apply operator on top // of 'ops' to top two elements in values stack. while(!ops.empty() && precedence(ops.top()) >= precedence(tokens[i])){ int val2 = values.top(); values.pop(); int val1 = values.top(); values.pop(); char op = ops.top(); ops.pop(); values.push(applyOp(val1, val2, op)); } // Push current token to 'ops'. ops.push(tokens[i]); } } // Entire expression has been parsed at this // point, apply remaining ops to remaining // values. while(!ops.empty()){ int val2 = values.top(); values.pop(); int val1 = values.top(); values.pop(); char op = ops.top(); ops.pop(); values.push(applyOp(val1, val2, op)); } // Top of 'values' contains result, return it. return values.top();} int main() { cout << evaluate("10 + 2 * 6") << "\n"; cout << evaluate("100 * 2 + 12") << "\n"; cout << evaluate("100 * ( 2 + 12 )") << "\n"; cout << evaluate("100 * ( 2 + 12 ) / 14"); return 0;} // This code is contributed by Nikhil jindal.
/* A Java program to evaluate a given expression where tokens are separated by space.*/import java.util.Stack; public class EvaluateString{ public static int evaluate(String expression) { char[] tokens = expression.toCharArray(); // Stack for numbers: 'values' Stack<Integer> values = new Stack<Integer>(); // Stack for Operators: 'ops' Stack<Character> ops = new Stack<Character>(); for (int i = 0; i < tokens.length; i++) { // Current token is a // whitespace, skip it if (tokens[i] == ' ') continue; // Current token is a number, // push it to stack for numbers if (tokens[i] >= '0' && tokens[i] <= '9') { StringBuffer sbuf = new StringBuffer(); // There may be more than one // digits in number while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9') sbuf.append(tokens[i++]); values.push(Integer.parseInt(sbuf. toString())); // right now the i points to // the character next to the digit, // since the for loop also increases // the i, we would skip one // token position; we need to // decrease the value of i by 1 to // correct the offset. i--; } // Current token is an opening brace, // push it to 'ops' else if (tokens[i] == '(') ops.push(tokens[i]); // Closing brace encountered, // solve entire brace else if (tokens[i] == ')') { while (ops.peek() != '(') values.push(applyOp(ops.pop(), values.pop(), values.pop())); ops.pop(); } // Current token is an operator. else if (tokens[i] == '+' || tokens[i] == '-' || tokens[i] == '*' || tokens[i] == '/') { // While top of 'ops' has same // or greater precedence to current // token, which is an operator. // Apply operator on top of 'ops' // to top two elements in values stack while (!ops.empty() && hasPrecedence(tokens[i], ops.peek())) values.push(applyOp(ops.pop(), values.pop(), values.pop())); // Push current token to 'ops'. ops.push(tokens[i]); } } // Entire expression has been // parsed at this point, apply remaining // ops to remaining values while (!ops.empty()) values.push(applyOp(ops.pop(), values.pop(), values.pop())); // Top of 'values' contains // result, return it return values.pop(); } // Returns true if 'op2' has higher // or same precedence as 'op1', // otherwise returns false. public static boolean hasPrecedence( char op1, char op2) { if (op2 == '(' || op2 == ')') return false; if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) return false; else return true; } // A utility method to apply an // operator 'op' on operands 'a' // and 'b'. Return the result. public static int applyOp(char op, int b, int a) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': if (b == 0) throw new UnsupportedOperationException( "Cannot divide by zero"); return a / b; } return 0; } // Driver method to test above methods public static void main(String[] args) { System.out.println(EvaluateString. evaluate("10 + 2 * 6")); System.out.println(EvaluateString. evaluate("100 * 2 + 12")); System.out.println(EvaluateString. evaluate("100 * ( 2 + 12 )")); System.out.println(EvaluateString. evaluate("100 * ( 2 + 12 ) / 14")); }}
# Python3 program to evaluate a given# expression where tokens are# separated by space. # Function to find precedence# of operators.def precedence(op): if op == '+' or op == '-': return 1 if op == '*' or op == '/': return 2 return 0 # Function to perform arithmetic# operations.def applyOp(a, b, op): if op == '+': return a + b if op == '-': return a - b if op == '*': return a * b if op == '/': return a // b # Function that returns value of# expression after evaluation.def evaluate(tokens): # stack to store integer values. values = [] # stack to store operators. ops = [] i = 0 while i < len(tokens): # Current token is a whitespace, # skip it. if tokens[i] == ' ': i += 1 continue # Current token is an opening # brace, push it to 'ops' elif tokens[i] == '(': ops.append(tokens[i]) # Current token is a number, push # it to stack for numbers. elif tokens[i].isdigit(): val = 0 # There may be more than one # digits in the number. while (i < len(tokens) and tokens[i].isdigit()): val = (val * 10) + int(tokens[i]) i += 1 values.append(val) # right now the i points to # the character next to the digit, # since the for loop also increases # the i, we would skip one # token position; we need to # decrease the value of i by 1 to # correct the offset. i-=1 # Closing brace encountered, # solve entire brace. elif tokens[i] == ')': while len(ops) != 0 and ops[-1] != '(': val2 = values.pop() val1 = values.pop() op = ops.pop() values.append(applyOp(val1, val2, op)) # pop opening brace. ops.pop() # Current token is an operator. else: # While top of 'ops' has same or # greater precedence to current # token, which is an operator. # Apply operator on top of 'ops' # to top two elements in values stack. while (len(ops) != 0 and precedence(ops[-1]) >= precedence(tokens[i])): val2 = values.pop() val1 = values.pop() op = ops.pop() values.append(applyOp(val1, val2, op)) # Push current token to 'ops'. ops.append(tokens[i]) i += 1 # Entire expression has been parsed # at this point, apply remaining ops # to remaining values. while len(ops) != 0: val2 = values.pop() val1 = values.pop() op = ops.pop() values.append(applyOp(val1, val2, op)) # Top of 'values' contains result, # return it. return values[-1] # Driver Codeif __name__ == "__main__": print(evaluate("10 + 2 * 6")) print(evaluate("100 * 2 + 12")) print(evaluate("100 * ( 2 + 12 )")) print(evaluate("100 * ( 2 + 12 ) / 14")) # This code is contributed# by Rituraj Jain
/* A C# program to evaluate a given expression where tokens are separated by space.*/using System;using System.Collections.Generic;using System.Text; public class EvaluateString{ public static int evaluate(string expression) { char[] tokens = expression.ToCharArray(); // Stack for numbers: 'values' Stack<int> values = new Stack<int>(); // Stack for Operators: 'ops' Stack<char> ops = new Stack<char>(); for (int i = 0; i < tokens.Length; i++) { // Current token is a whitespace, skip it if (tokens[i] == ' ') { continue; } // Current token is a number, // push it to stack for numbers if (tokens[i] >= '0' && tokens[i] <= '9') { StringBuilder sbuf = new StringBuilder(); // There may be more than // one digits in number while (i < tokens.Length && tokens[i] >= '0' && tokens[i] <= '9') { sbuf.Append(tokens[i++]); } values.Push(int.Parse(sbuf.ToString())); // Right now the i points to // the character next to the digit, // since the for loop also increases // the i, we would skip one // token position; we need to // decrease the value of i by 1 to // correct the offset. i--; } // Current token is an opening // brace, push it to 'ops' else if (tokens[i] == '(') { ops.Push(tokens[i]); } // Closing brace encountered, // solve entire brace else if (tokens[i] == ')') { while (ops.Peek() != '(') { values.Push(applyOp(ops.Pop(), values.Pop(), values.Pop())); } ops.Pop(); } // Current token is an operator. else if (tokens[i] == '+' || tokens[i] == '-' || tokens[i] == '*' || tokens[i] == '/') { // While top of 'ops' has same // or greater precedence to current // token, which is an operator. // Apply operator on top of 'ops' // to top two elements in values stack while (ops.Count > 0 && hasPrecedence(tokens[i], ops.Peek())) { values.Push(applyOp(ops.Pop(), values.Pop(), values.Pop())); } // Push current token to 'ops'. ops.Push(tokens[i]); } } // Entire expression has been // parsed at this point, apply remaining // ops to remaining values while (ops.Count > 0) { values.Push(applyOp(ops.Pop(), values.Pop(), values.Pop())); } // Top of 'values' contains // result, return it return values.Pop(); } // Returns true if 'op2' has // higher or same precedence as 'op1', // otherwise returns false. public static bool hasPrecedence(char op1, char op2) { if (op2 == '(' || op2 == ')') { return false; } if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) { return false; } else { return true; } } // A utility method to apply an // operator 'op' on operands 'a' // and 'b'. Return the result. public static int applyOp(char op, int b, int a) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': if (b == 0) { throw new System.NotSupportedException( "Cannot divide by zero"); } return a / b; } return 0; } // Driver method to test above methods public static void Main(string[] args) { Console.WriteLine(EvaluateString. evaluate("10 + 2 * 6")); Console.WriteLine(EvaluateString. evaluate("100 * 2 + 12")); Console.WriteLine(EvaluateString. evaluate("100 * ( 2 + 12 )")); Console.WriteLine(EvaluateString. evaluate("100 * ( 2 + 12 ) / 14")); }} // This code is contributed by Shrikant13
<script> /* A Javascript program to evaluate a given expression where tokens are separated by space. */ function evaluate(expression) { let tokens = expression.split(''); // Stack for numbers: 'values' let values = []; // Stack for Operators: 'ops' let ops = []; for (let i = 0; i < tokens.length; i++) { // Current token is a whitespace, skip it if (tokens[i] == ' ') { continue; } // Current token is a number, // push it to stack for numbers if (tokens[i] >= '0' && tokens[i] <= '9') { let sbuf = ""; // There may be more than // one digits in number while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9') { sbuf = sbuf + tokens[i++]; } values.push(parseInt(sbuf, 10)); // Right now the i points to // the character next to the digit, // since the for loop also increases // the i, we would skip one // token position; we need to // decrease the value of i by 1 to // correct the offset. i--; } // Current token is an opening // brace, push it to 'ops' else if (tokens[i] == '(') { ops.push(tokens[i]); } // Closing brace encountered, // solve entire brace else if (tokens[i] == ')') { while (ops[ops.length - 1] != '(') { values.push(applyOp(ops.pop(), values.pop(), values.pop())); } ops.pop(); } // Current token is an operator. else if (tokens[i] == '+' || tokens[i] == '-' || tokens[i] == '*' || tokens[i] == '/') { // While top of 'ops' has same // or greater precedence to current // token, which is an operator. // Apply operator on top of 'ops' // to top two elements in values stack while (ops.length > 0 && hasPrecedence(tokens[i], ops[ops.length - 1])) { values.push(applyOp(ops.pop(), values.pop(), values.pop())); } // Push current token to 'ops'. ops.push(tokens[i]); } } // Entire expression has been // parsed at this point, apply remaining // ops to remaining values while (ops.length > 0) { values.push(applyOp(ops.pop(), values.pop(), values.pop())); } // Top of 'values' contains // result, return it return values.pop(); } // Returns true if 'op2' has // higher or same precedence as 'op1', // otherwise returns false. function hasPrecedence(op1, op2) { if (op2 == '(' || op2 == ')') { return false; } if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) { return false; } else { return true; } } // A utility method to apply an // operator 'op' on operands 'a' // and 'b'. Return the result. function applyOp(op, b, a) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': if (b == 0) { document.write("Cannot divide by zero"); } return parseInt(a / b, 10); } return 0; } document.write(evaluate("10 + 2 * 6") + "</br>"); document.write(evaluate("100 * 2 + 12") + "</br>"); document.write(evaluate("100 * ( 2 + 12 )") + "</br>"); document.write(evaluate("100 * ( 2 + 12 ) / 14") + "</br>"); // This code is contributed by decode2207.</script>
22
212
1400
100
Time Complexity: O(n) Space Complexity: O(n)See this for a sample run with more test cases.
nik1996
shrikanth13
rituraj_jain
harshitSingh_11
rishabh_malhotra
decode2207
hardikkoriintern
Oracle
Mathematical
Stack
Oracle
Mathematical
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
Stack in Python
Stack Class in Java
Check for Balanced Brackets in an expression (well-formedness) using Stack
Introduction to Data Structures
Stack | Set 2 (Infix to Postfix) | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 330,
"s": 54,
"text": "Evaluate an expression represented by a String. The expression can contain parentheses, you can assume parentheses are well-matched. For simplicity, you can assume only binary operations allowed are +, -, *, and /. Arithmetic Expressions can be written in one of three forms:"
},
{
"code": null,
"e": 418,
"s": 330,
"text": "Infix Notation: Operators are written between the operands they operate on, e.g. 3 + 4."
},
{
"code": null,
"e": 488,
"s": 418,
"text": "Prefix Notation: Operators are written before the operands, e.g + 3 4"
},
{
"code": null,
"e": 544,
"s": 488,
"text": "Postfix Notation: Operators are written after operands."
},
{
"code": null,
"e": 999,
"s": 544,
"text": "Infix Expressions are harder for Computers to evaluate because of the additional work needed to decide precedence. Infix notation is how expressions are written and recognized by humans and, generally, input to programs. Given that they are harder to evaluate, they are generally converted to one of the two remaining forms. A very well known algorithm for converting an infix notation to a postfix notation is Shunting Yard Algorithm by Edgar Dijkstra. "
},
{
"code": null,
"e": 1331,
"s": 999,
"text": "This algorithm takes as input an Infix Expression and produces a queue that has this expression converted to postfix notation. The same algorithm can be modified so that it outputs the result of the evaluation of expression instead of a queue. The trick is using two stacks instead of one, one for operands, and one for operators. "
},
{
"code": null,
"e": 2939,
"s": 1331,
"text": "1. While there are still tokens to be read in,\n 1.1 Get the next token.\n 1.2 If the token is:\n 1.2.1 A number: push it onto the value stack.\n 1.2.2 A variable: get its value, and push onto the value stack.\n 1.2.3 A left parenthesis: push it onto the operator stack.\n 1.2.4 A right parenthesis:\n 1 While the thing on top of the operator stack is not a \n left parenthesis,\n 1 Pop the operator from the operator stack.\n 2 Pop the value stack twice, getting two operands.\n 3 Apply the operator to the operands, in the correct order.\n 4 Push the result onto the value stack.\n 2 Pop the left parenthesis from the operator stack, and discard it.\n 1.2.5 An operator (call it thisOp):\n 1 While the operator stack is not empty, and the top thing on the\n operator stack has the same or greater precedence as thisOp,\n 1 Pop the operator from the operator stack.\n 2 Pop the value stack twice, getting two operands.\n 3 Apply the operator to the operands, in the correct order.\n 4 Push the result onto the value stack.\n 2 Push thisOp onto the operator stack.\n2. While the operator stack is not empty,\n 1 Pop the operator from the operator stack.\n 2 Pop the value stack twice, getting two operands.\n 3 Apply the operator to the operands, in the correct order.\n 4 Push the result onto the value stack.\n3. At this point the operator stack should be empty, and the value\n stack should have only one value in it, which is the final result."
},
{
"code": null,
"e": 3089,
"s": 2939,
"text": "Implementation: It should be clear that this algorithm runs in linear time – each number or operator is pushed onto and popped from Stack only once. "
},
{
"code": null,
"e": 3093,
"s": 3089,
"text": "C++"
},
{
"code": null,
"e": 3098,
"s": 3093,
"text": "Java"
},
{
"code": null,
"e": 3106,
"s": 3098,
"text": "Python3"
},
{
"code": null,
"e": 3109,
"s": 3106,
"text": "C#"
},
{
"code": null,
"e": 3120,
"s": 3109,
"text": "Javascript"
},
{
"code": "// CPP program to evaluate a given// expression where tokens are// separated by space.#include <bits/stdc++.h>using namespace std; // Function to find precedence of// operators.int precedence(char op){ if(op == '+'||op == '-') return 1; if(op == '*'||op == '/') return 2; return 0;} // Function to perform arithmetic operations.int applyOp(int a, int b, char op){ switch(op){ case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; }} // Function that returns value of// expression after evaluation.int evaluate(string tokens){ int i; // stack to store integer values. stack <int> values; // stack to store operators. stack <char> ops; for(i = 0; i < tokens.length(); i++){ // Current token is a whitespace, // skip it. if(tokens[i] == ' ') continue; // Current token is an opening // brace, push it to 'ops' else if(tokens[i] == '('){ ops.push(tokens[i]); } // Current token is a number, push // it to stack for numbers. else if(isdigit(tokens[i])){ int val = 0; // There may be more than one // digits in number. while(i < tokens.length() && isdigit(tokens[i])) { val = (val*10) + (tokens[i]-'0'); i++; } values.push(val); // right now the i points to // the character next to the digit, // since the for loop also increases // the i, we would skip one // token position; we need to // decrease the value of i by 1 to // correct the offset. i--; } // Closing brace encountered, solve // entire brace. else if(tokens[i] == ')') { while(!ops.empty() && ops.top() != '(') { int val2 = values.top(); values.pop(); int val1 = values.top(); values.pop(); char op = ops.top(); ops.pop(); values.push(applyOp(val1, val2, op)); } // pop opening brace. if(!ops.empty()) ops.pop(); } // Current token is an operator. else { // While top of 'ops' has same or greater // precedence to current token, which // is an operator. Apply operator on top // of 'ops' to top two elements in values stack. while(!ops.empty() && precedence(ops.top()) >= precedence(tokens[i])){ int val2 = values.top(); values.pop(); int val1 = values.top(); values.pop(); char op = ops.top(); ops.pop(); values.push(applyOp(val1, val2, op)); } // Push current token to 'ops'. ops.push(tokens[i]); } } // Entire expression has been parsed at this // point, apply remaining ops to remaining // values. while(!ops.empty()){ int val2 = values.top(); values.pop(); int val1 = values.top(); values.pop(); char op = ops.top(); ops.pop(); values.push(applyOp(val1, val2, op)); } // Top of 'values' contains result, return it. return values.top();} int main() { cout << evaluate(\"10 + 2 * 6\") << \"\\n\"; cout << evaluate(\"100 * 2 + 12\") << \"\\n\"; cout << evaluate(\"100 * ( 2 + 12 )\") << \"\\n\"; cout << evaluate(\"100 * ( 2 + 12 ) / 14\"); return 0;} // This code is contributed by Nikhil jindal.",
"e": 7127,
"s": 3120,
"text": null
},
{
"code": "/* A Java program to evaluate a given expression where tokens are separated by space.*/import java.util.Stack; public class EvaluateString{ public static int evaluate(String expression) { char[] tokens = expression.toCharArray(); // Stack for numbers: 'values' Stack<Integer> values = new Stack<Integer>(); // Stack for Operators: 'ops' Stack<Character> ops = new Stack<Character>(); for (int i = 0; i < tokens.length; i++) { // Current token is a // whitespace, skip it if (tokens[i] == ' ') continue; // Current token is a number, // push it to stack for numbers if (tokens[i] >= '0' && tokens[i] <= '9') { StringBuffer sbuf = new StringBuffer(); // There may be more than one // digits in number while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9') sbuf.append(tokens[i++]); values.push(Integer.parseInt(sbuf. toString())); // right now the i points to // the character next to the digit, // since the for loop also increases // the i, we would skip one // token position; we need to // decrease the value of i by 1 to // correct the offset. i--; } // Current token is an opening brace, // push it to 'ops' else if (tokens[i] == '(') ops.push(tokens[i]); // Closing brace encountered, // solve entire brace else if (tokens[i] == ')') { while (ops.peek() != '(') values.push(applyOp(ops.pop(), values.pop(), values.pop())); ops.pop(); } // Current token is an operator. else if (tokens[i] == '+' || tokens[i] == '-' || tokens[i] == '*' || tokens[i] == '/') { // While top of 'ops' has same // or greater precedence to current // token, which is an operator. // Apply operator on top of 'ops' // to top two elements in values stack while (!ops.empty() && hasPrecedence(tokens[i], ops.peek())) values.push(applyOp(ops.pop(), values.pop(), values.pop())); // Push current token to 'ops'. ops.push(tokens[i]); } } // Entire expression has been // parsed at this point, apply remaining // ops to remaining values while (!ops.empty()) values.push(applyOp(ops.pop(), values.pop(), values.pop())); // Top of 'values' contains // result, return it return values.pop(); } // Returns true if 'op2' has higher // or same precedence as 'op1', // otherwise returns false. public static boolean hasPrecedence( char op1, char op2) { if (op2 == '(' || op2 == ')') return false; if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) return false; else return true; } // A utility method to apply an // operator 'op' on operands 'a' // and 'b'. Return the result. public static int applyOp(char op, int b, int a) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': if (b == 0) throw new UnsupportedOperationException( \"Cannot divide by zero\"); return a / b; } return 0; } // Driver method to test above methods public static void main(String[] args) { System.out.println(EvaluateString. evaluate(\"10 + 2 * 6\")); System.out.println(EvaluateString. evaluate(\"100 * 2 + 12\")); System.out.println(EvaluateString. evaluate(\"100 * ( 2 + 12 )\")); System.out.println(EvaluateString. evaluate(\"100 * ( 2 + 12 ) / 14\")); }}",
"e": 11951,
"s": 7127,
"text": null
},
{
"code": "# Python3 program to evaluate a given# expression where tokens are# separated by space. # Function to find precedence# of operators.def precedence(op): if op == '+' or op == '-': return 1 if op == '*' or op == '/': return 2 return 0 # Function to perform arithmetic# operations.def applyOp(a, b, op): if op == '+': return a + b if op == '-': return a - b if op == '*': return a * b if op == '/': return a // b # Function that returns value of# expression after evaluation.def evaluate(tokens): # stack to store integer values. values = [] # stack to store operators. ops = [] i = 0 while i < len(tokens): # Current token is a whitespace, # skip it. if tokens[i] == ' ': i += 1 continue # Current token is an opening # brace, push it to 'ops' elif tokens[i] == '(': ops.append(tokens[i]) # Current token is a number, push # it to stack for numbers. elif tokens[i].isdigit(): val = 0 # There may be more than one # digits in the number. while (i < len(tokens) and tokens[i].isdigit()): val = (val * 10) + int(tokens[i]) i += 1 values.append(val) # right now the i points to # the character next to the digit, # since the for loop also increases # the i, we would skip one # token position; we need to # decrease the value of i by 1 to # correct the offset. i-=1 # Closing brace encountered, # solve entire brace. elif tokens[i] == ')': while len(ops) != 0 and ops[-1] != '(': val2 = values.pop() val1 = values.pop() op = ops.pop() values.append(applyOp(val1, val2, op)) # pop opening brace. ops.pop() # Current token is an operator. else: # While top of 'ops' has same or # greater precedence to current # token, which is an operator. # Apply operator on top of 'ops' # to top two elements in values stack. while (len(ops) != 0 and precedence(ops[-1]) >= precedence(tokens[i])): val2 = values.pop() val1 = values.pop() op = ops.pop() values.append(applyOp(val1, val2, op)) # Push current token to 'ops'. ops.append(tokens[i]) i += 1 # Entire expression has been parsed # at this point, apply remaining ops # to remaining values. while len(ops) != 0: val2 = values.pop() val1 = values.pop() op = ops.pop() values.append(applyOp(val1, val2, op)) # Top of 'values' contains result, # return it. return values[-1] # Driver Codeif __name__ == \"__main__\": print(evaluate(\"10 + 2 * 6\")) print(evaluate(\"100 * 2 + 12\")) print(evaluate(\"100 * ( 2 + 12 )\")) print(evaluate(\"100 * ( 2 + 12 ) / 14\")) # This code is contributed# by Rituraj Jain",
"e": 15387,
"s": 11951,
"text": null
},
{
"code": "/* A C# program to evaluate a given expression where tokens are separated by space.*/using System;using System.Collections.Generic;using System.Text; public class EvaluateString{ public static int evaluate(string expression) { char[] tokens = expression.ToCharArray(); // Stack for numbers: 'values' Stack<int> values = new Stack<int>(); // Stack for Operators: 'ops' Stack<char> ops = new Stack<char>(); for (int i = 0; i < tokens.Length; i++) { // Current token is a whitespace, skip it if (tokens[i] == ' ') { continue; } // Current token is a number, // push it to stack for numbers if (tokens[i] >= '0' && tokens[i] <= '9') { StringBuilder sbuf = new StringBuilder(); // There may be more than // one digits in number while (i < tokens.Length && tokens[i] >= '0' && tokens[i] <= '9') { sbuf.Append(tokens[i++]); } values.Push(int.Parse(sbuf.ToString())); // Right now the i points to // the character next to the digit, // since the for loop also increases // the i, we would skip one // token position; we need to // decrease the value of i by 1 to // correct the offset. i--; } // Current token is an opening // brace, push it to 'ops' else if (tokens[i] == '(') { ops.Push(tokens[i]); } // Closing brace encountered, // solve entire brace else if (tokens[i] == ')') { while (ops.Peek() != '(') { values.Push(applyOp(ops.Pop(), values.Pop(), values.Pop())); } ops.Pop(); } // Current token is an operator. else if (tokens[i] == '+' || tokens[i] == '-' || tokens[i] == '*' || tokens[i] == '/') { // While top of 'ops' has same // or greater precedence to current // token, which is an operator. // Apply operator on top of 'ops' // to top two elements in values stack while (ops.Count > 0 && hasPrecedence(tokens[i], ops.Peek())) { values.Push(applyOp(ops.Pop(), values.Pop(), values.Pop())); } // Push current token to 'ops'. ops.Push(tokens[i]); } } // Entire expression has been // parsed at this point, apply remaining // ops to remaining values while (ops.Count > 0) { values.Push(applyOp(ops.Pop(), values.Pop(), values.Pop())); } // Top of 'values' contains // result, return it return values.Pop(); } // Returns true if 'op2' has // higher or same precedence as 'op1', // otherwise returns false. public static bool hasPrecedence(char op1, char op2) { if (op2 == '(' || op2 == ')') { return false; } if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) { return false; } else { return true; } } // A utility method to apply an // operator 'op' on operands 'a' // and 'b'. Return the result. public static int applyOp(char op, int b, int a) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': if (b == 0) { throw new System.NotSupportedException( \"Cannot divide by zero\"); } return a / b; } return 0; } // Driver method to test above methods public static void Main(string[] args) { Console.WriteLine(EvaluateString. evaluate(\"10 + 2 * 6\")); Console.WriteLine(EvaluateString. evaluate(\"100 * 2 + 12\")); Console.WriteLine(EvaluateString. evaluate(\"100 * ( 2 + 12 )\")); Console.WriteLine(EvaluateString. evaluate(\"100 * ( 2 + 12 ) / 14\")); }} // This code is contributed by Shrikant13",
"e": 20384,
"s": 15387,
"text": null
},
{
"code": "<script> /* A Javascript program to evaluate a given expression where tokens are separated by space. */ function evaluate(expression) { let tokens = expression.split(''); // Stack for numbers: 'values' let values = []; // Stack for Operators: 'ops' let ops = []; for (let i = 0; i < tokens.length; i++) { // Current token is a whitespace, skip it if (tokens[i] == ' ') { continue; } // Current token is a number, // push it to stack for numbers if (tokens[i] >= '0' && tokens[i] <= '9') { let sbuf = \"\"; // There may be more than // one digits in number while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9') { sbuf = sbuf + tokens[i++]; } values.push(parseInt(sbuf, 10)); // Right now the i points to // the character next to the digit, // since the for loop also increases // the i, we would skip one // token position; we need to // decrease the value of i by 1 to // correct the offset. i--; } // Current token is an opening // brace, push it to 'ops' else if (tokens[i] == '(') { ops.push(tokens[i]); } // Closing brace encountered, // solve entire brace else if (tokens[i] == ')') { while (ops[ops.length - 1] != '(') { values.push(applyOp(ops.pop(), values.pop(), values.pop())); } ops.pop(); } // Current token is an operator. else if (tokens[i] == '+' || tokens[i] == '-' || tokens[i] == '*' || tokens[i] == '/') { // While top of 'ops' has same // or greater precedence to current // token, which is an operator. // Apply operator on top of 'ops' // to top two elements in values stack while (ops.length > 0 && hasPrecedence(tokens[i], ops[ops.length - 1])) { values.push(applyOp(ops.pop(), values.pop(), values.pop())); } // Push current token to 'ops'. ops.push(tokens[i]); } } // Entire expression has been // parsed at this point, apply remaining // ops to remaining values while (ops.length > 0) { values.push(applyOp(ops.pop(), values.pop(), values.pop())); } // Top of 'values' contains // result, return it return values.pop(); } // Returns true if 'op2' has // higher or same precedence as 'op1', // otherwise returns false. function hasPrecedence(op1, op2) { if (op2 == '(' || op2 == ')') { return false; } if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) { return false; } else { return true; } } // A utility method to apply an // operator 'op' on operands 'a' // and 'b'. Return the result. function applyOp(op, b, a) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': if (b == 0) { document.write(\"Cannot divide by zero\"); } return parseInt(a / b, 10); } return 0; } document.write(evaluate(\"10 + 2 * 6\") + \"</br>\"); document.write(evaluate(\"100 * 2 + 12\") + \"</br>\"); document.write(evaluate(\"100 * ( 2 + 12 )\") + \"</br>\"); document.write(evaluate(\"100 * ( 2 + 12 ) / 14\") + \"</br>\"); // This code is contributed by decode2207.</script>",
"e": 24900,
"s": 20384,
"text": null
},
{
"code": null,
"e": 24916,
"s": 24900,
"text": "22\n212\n1400\n100"
},
{
"code": null,
"e": 25008,
"s": 24916,
"text": "Time Complexity: O(n) Space Complexity: O(n)See this for a sample run with more test cases."
},
{
"code": null,
"e": 25016,
"s": 25008,
"text": "nik1996"
},
{
"code": null,
"e": 25028,
"s": 25016,
"text": "shrikanth13"
},
{
"code": null,
"e": 25041,
"s": 25028,
"text": "rituraj_jain"
},
{
"code": null,
"e": 25057,
"s": 25041,
"text": "harshitSingh_11"
},
{
"code": null,
"e": 25074,
"s": 25057,
"text": "rishabh_malhotra"
},
{
"code": null,
"e": 25085,
"s": 25074,
"text": "decode2207"
},
{
"code": null,
"e": 25102,
"s": 25085,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 25109,
"s": 25102,
"text": "Oracle"
},
{
"code": null,
"e": 25122,
"s": 25109,
"text": "Mathematical"
},
{
"code": null,
"e": 25128,
"s": 25122,
"text": "Stack"
},
{
"code": null,
"e": 25135,
"s": 25128,
"text": "Oracle"
},
{
"code": null,
"e": 25148,
"s": 25135,
"text": "Mathematical"
},
{
"code": null,
"e": 25154,
"s": 25148,
"text": "Stack"
},
{
"code": null,
"e": 25252,
"s": 25154,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25282,
"s": 25252,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 25325,
"s": 25282,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 25385,
"s": 25325,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 25400,
"s": 25385,
"text": "C++ Data Types"
},
{
"code": null,
"e": 25424,
"s": 25400,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 25440,
"s": 25424,
"text": "Stack in Python"
},
{
"code": null,
"e": 25460,
"s": 25440,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 25535,
"s": 25460,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 25567,
"s": 25535,
"text": "Introduction to Data Structures"
}
] |
Query Optimization in Relational Algebra | 04 Jul, 2022
Query: A query is a request for information from a database.
Query Plans: A query plan (or query execution plan) is an ordered set of steps used to access data in a SQL relational database management system.
Query Optimization: A single query can be executed through different algorithms or re-written in different forms and structures. Hence, the question of query optimization comes into the picture – Which of these forms or pathways is the most optimal? The query optimizer attempts to determine the most efficient way to execute a given query by considering the possible query plans.
Importance: The goal of query optimization is to reduce the system resources required to fulfill a query, and ultimately provide the user with the correct result set faster.
First, it provides the user with faster results, which makes the application seem faster to the user.
Secondly, it allows the system to service more queries in the same amount of time, because each request takes less time than unoptimized queries.
Thirdly, query optimization ultimately reduces the amount of wear on the hardware (e.g. disk drives), and allows the server to run more efficiently (e.g. lower power consumption, less memory usage).
There are broadly two ways a query can be optimized:
Analyze and transform equivalent relational expressions: Try to minimize the tuple and column counts of the intermediate and final query processes (discussed here).Using different algorithms for each operation: These underlying algorithms determine how tuples are accessed from the data structures they are stored in, indexing, hashing, data retrieval and hence influence the number of disk and block accesses (discussed in query processing).
Analyze and transform equivalent relational expressions: Try to minimize the tuple and column counts of the intermediate and final query processes (discussed here).
Using different algorithms for each operation: These underlying algorithms determine how tuples are accessed from the data structures they are stored in, indexing, hashing, data retrieval and hence influence the number of disk and block accesses (discussed in query processing).
Analyze and transform equivalent relational expressions.Here, we shall talk about generating minimal equivalent expressions. To analyze equivalent expression, listed are a set of equivalence rules. These generate equivalent expressions for a query written in relational algebra. To optimize a query, we must convert the query into its equivalent form as long as an equivalence rule is satisfied.
Conjunctive selection operations can be written as a sequence of individual selections. This is called a sigma-cascade. Explanation: Applying condition intersection is expensive. Instead, filter out tuples satisfying condition (inner selection) and then apply condition (outer selection) to the then resulting fewer tuples. This leaves us with less tuples to process the second time. This can be extended for two or more intersecting selections. Since we are breaking a single condition into a series of selections or cascades, it is called a “cascade”. Selection is commutative. Explanation: condition is commutative in nature. This means, it does not matter whether we apply first or first. In practice, it is better and more optimal to apply that selection first which yields a fewer number of tuples. This saves time on our outer selection. All following projections can be omitted, only the first projection is required. This is called a pi-cascade. Explanation: A cascade or a series of projections is meaningless. This is because in the end, we are only selecting those columns which are specified in the last, or the outermost projection. Hence, it is better to collapse all the projections into just one i.e. the outermost projection. Selections on Cartesian Products can be re-written as Theta Joins. Equivalence 1 Explanation: The cross product operation is known to be very expensive. This is because it matches each tuple of E1 (total m tuples) with each tuple of E2 (total n tuples). This yields m*n entries. If we apply a selection operation after that, we would have to scan through m*n entries to find the suitable tuples which satisfy the condition . Instead of doing all of this, it is more optimal to use the Theta Join, a join specifically designed to select only those entries in the cross product which satisfy the Theta condition, without evaluating the entire cross product first. Equivalence 2 Explanation: Theta Join radically decreases the number of resulting tuples, so if we apply an intersection of both the join conditions i.e. and into the Theta Join itself, we get fewer scans to do. On the other hand, a condition outside unnecessarily increases the tuples to scan. Theta Joins are commutative. Explanation: Theta Joins are commutative, and the query processing time depends to some extent which table is used as the outer loop and which one is used as the inner loop during the join process (based on the indexing structures and blocks). Join operations are associative. Natural Join Explanation: Joins are all commutative as well as associative, so one must join those two tables first which yield less number of entries, and then apply the other join. Theta Join Explanation: Theta Joins are associative in the above manner, where involves attributes from only E2 and E3. Selection operation can be distributed. Equivalence 1 Explanation: Applying a selection after doing the Theta Join causes all the tuples returned by the Theta Join to be monitored after the join. If this selection contains attributes from only E1, it is better to apply this selection to E1 (hence resulting in a fewer number of tuples) and then join it with E2. Equivalence 2 Explanation: This can be extended to two selection conditions, and , where Theta1 contains the attributes of only E1 and contains attributes of only E2. Hence, we can individually apply the selection criteria before joining, to drastically reduce the number of tuples joined. Projection distributes over the Theta Join. Equivalence 1 Explanation: The idea discussed for selection can be used for projection as well. Here, if L1 is a projection that involves columns of only E1, and L2 another projection that involves the columns of only E2, then it is better to individually apply the projections on both the tables before joining. This leaves us with a fewer number of columns on either side, hence contributing to an easier join. Equivalence 2 Explanation: Here, when applying projections L1 and L2 on the join, where L1 contains columns of only E1 and L2 contains columns of only E2, we can introduce another column E3 (which is common between both the tables). Then, we can apply projections L1 and L2 on E1 and E2 respectively, along with the added column L3. L3 enables us to do the join. Union and Intersection are commutative. Explanation: Union and intersection are both distributive; we can enclose any tables in parentheses according to requirement and ease of access. Union and Intersection are associative. Explanation: Union and intersection are both distributive; we can enclose any tables in parentheses according to requirement and ease of access. Selection operation distributes over the union, intersection, and difference operations. Explanation: In set difference, we know that only those tuples are shown which belong to table E1 and do not belong to table E2. So, applying a selection condition on the entire set difference is equivalent to applying the selection condition on the individual tables and then applying set difference. This will reduce the number of comparisons in the set difference step. Projection operation distributes over the union operation. Explanation: Applying individual projections before computing the union of E1 and E2 is more optimal than the left expression, i.e. applying projection after the union step.
Conjunctive selection operations can be written as a sequence of individual selections. This is called a sigma-cascade. Explanation: Applying condition intersection is expensive. Instead, filter out tuples satisfying condition (inner selection) and then apply condition (outer selection) to the then resulting fewer tuples. This leaves us with less tuples to process the second time. This can be extended for two or more intersecting selections. Since we are breaking a single condition into a series of selections or cascades, it is called a “cascade”.
Explanation: Applying condition intersection is expensive. Instead, filter out tuples satisfying condition (inner selection) and then apply condition (outer selection) to the then resulting fewer tuples. This leaves us with less tuples to process the second time. This can be extended for two or more intersecting selections. Since we are breaking a single condition into a series of selections or cascades, it is called a “cascade”.
Selection is commutative. Explanation: condition is commutative in nature. This means, it does not matter whether we apply first or first. In practice, it is better and more optimal to apply that selection first which yields a fewer number of tuples. This saves time on our outer selection.
Explanation: condition is commutative in nature. This means, it does not matter whether we apply first or first. In practice, it is better and more optimal to apply that selection first which yields a fewer number of tuples. This saves time on our outer selection.
All following projections can be omitted, only the first projection is required. This is called a pi-cascade. Explanation: A cascade or a series of projections is meaningless. This is because in the end, we are only selecting those columns which are specified in the last, or the outermost projection. Hence, it is better to collapse all the projections into just one i.e. the outermost projection.
Explanation: A cascade or a series of projections is meaningless. This is because in the end, we are only selecting those columns which are specified in the last, or the outermost projection. Hence, it is better to collapse all the projections into just one i.e. the outermost projection.
Selections on Cartesian Products can be re-written as Theta Joins. Equivalence 1 Explanation: The cross product operation is known to be very expensive. This is because it matches each tuple of E1 (total m tuples) with each tuple of E2 (total n tuples). This yields m*n entries. If we apply a selection operation after that, we would have to scan through m*n entries to find the suitable tuples which satisfy the condition . Instead of doing all of this, it is more optimal to use the Theta Join, a join specifically designed to select only those entries in the cross product which satisfy the Theta condition, without evaluating the entire cross product first. Equivalence 2 Explanation: Theta Join radically decreases the number of resulting tuples, so if we apply an intersection of both the join conditions i.e. and into the Theta Join itself, we get fewer scans to do. On the other hand, a condition outside unnecessarily increases the tuples to scan.
Equivalence 1 Explanation: The cross product operation is known to be very expensive. This is because it matches each tuple of E1 (total m tuples) with each tuple of E2 (total n tuples). This yields m*n entries. If we apply a selection operation after that, we would have to scan through m*n entries to find the suitable tuples which satisfy the condition . Instead of doing all of this, it is more optimal to use the Theta Join, a join specifically designed to select only those entries in the cross product which satisfy the Theta condition, without evaluating the entire cross product first.
Explanation: The cross product operation is known to be very expensive. This is because it matches each tuple of E1 (total m tuples) with each tuple of E2 (total n tuples). This yields m*n entries. If we apply a selection operation after that, we would have to scan through m*n entries to find the suitable tuples which satisfy the condition . Instead of doing all of this, it is more optimal to use the Theta Join, a join specifically designed to select only those entries in the cross product which satisfy the Theta condition, without evaluating the entire cross product first.
Equivalence 2 Explanation: Theta Join radically decreases the number of resulting tuples, so if we apply an intersection of both the join conditions i.e. and into the Theta Join itself, we get fewer scans to do. On the other hand, a condition outside unnecessarily increases the tuples to scan.
Explanation: Theta Join radically decreases the number of resulting tuples, so if we apply an intersection of both the join conditions i.e. and into the Theta Join itself, we get fewer scans to do. On the other hand, a condition outside unnecessarily increases the tuples to scan.
Theta Joins are commutative. Explanation: Theta Joins are commutative, and the query processing time depends to some extent which table is used as the outer loop and which one is used as the inner loop during the join process (based on the indexing structures and blocks).
Explanation: Theta Joins are commutative, and the query processing time depends to some extent which table is used as the outer loop and which one is used as the inner loop during the join process (based on the indexing structures and blocks).
Join operations are associative. Natural Join Explanation: Joins are all commutative as well as associative, so one must join those two tables first which yield less number of entries, and then apply the other join. Theta Join Explanation: Theta Joins are associative in the above manner, where involves attributes from only E2 and E3.
Natural Join Explanation: Joins are all commutative as well as associative, so one must join those two tables first which yield less number of entries, and then apply the other join.
Explanation: Joins are all commutative as well as associative, so one must join those two tables first which yield less number of entries, and then apply the other join.
Theta Join Explanation: Theta Joins are associative in the above manner, where involves attributes from only E2 and E3.
Explanation: Theta Joins are associative in the above manner, where involves attributes from only E2 and E3.
Selection operation can be distributed. Equivalence 1 Explanation: Applying a selection after doing the Theta Join causes all the tuples returned by the Theta Join to be monitored after the join. If this selection contains attributes from only E1, it is better to apply this selection to E1 (hence resulting in a fewer number of tuples) and then join it with E2. Equivalence 2 Explanation: This can be extended to two selection conditions, and , where Theta1 contains the attributes of only E1 and contains attributes of only E2. Hence, we can individually apply the selection criteria before joining, to drastically reduce the number of tuples joined.
Equivalence 1 Explanation: Applying a selection after doing the Theta Join causes all the tuples returned by the Theta Join to be monitored after the join. If this selection contains attributes from only E1, it is better to apply this selection to E1 (hence resulting in a fewer number of tuples) and then join it with E2.
Explanation: Applying a selection after doing the Theta Join causes all the tuples returned by the Theta Join to be monitored after the join. If this selection contains attributes from only E1, it is better to apply this selection to E1 (hence resulting in a fewer number of tuples) and then join it with E2.
Equivalence 2 Explanation: This can be extended to two selection conditions, and , where Theta1 contains the attributes of only E1 and contains attributes of only E2. Hence, we can individually apply the selection criteria before joining, to drastically reduce the number of tuples joined.
Explanation: This can be extended to two selection conditions, and , where Theta1 contains the attributes of only E1 and contains attributes of only E2. Hence, we can individually apply the selection criteria before joining, to drastically reduce the number of tuples joined.
Projection distributes over the Theta Join. Equivalence 1 Explanation: The idea discussed for selection can be used for projection as well. Here, if L1 is a projection that involves columns of only E1, and L2 another projection that involves the columns of only E2, then it is better to individually apply the projections on both the tables before joining. This leaves us with a fewer number of columns on either side, hence contributing to an easier join. Equivalence 2 Explanation: Here, when applying projections L1 and L2 on the join, where L1 contains columns of only E1 and L2 contains columns of only E2, we can introduce another column E3 (which is common between both the tables). Then, we can apply projections L1 and L2 on E1 and E2 respectively, along with the added column L3. L3 enables us to do the join.
Equivalence 1 Explanation: The idea discussed for selection can be used for projection as well. Here, if L1 is a projection that involves columns of only E1, and L2 another projection that involves the columns of only E2, then it is better to individually apply the projections on both the tables before joining. This leaves us with a fewer number of columns on either side, hence contributing to an easier join.
Explanation: The idea discussed for selection can be used for projection as well. Here, if L1 is a projection that involves columns of only E1, and L2 another projection that involves the columns of only E2, then it is better to individually apply the projections on both the tables before joining. This leaves us with a fewer number of columns on either side, hence contributing to an easier join.
Equivalence 2 Explanation: Here, when applying projections L1 and L2 on the join, where L1 contains columns of only E1 and L2 contains columns of only E2, we can introduce another column E3 (which is common between both the tables). Then, we can apply projections L1 and L2 on E1 and E2 respectively, along with the added column L3. L3 enables us to do the join.
Explanation: Here, when applying projections L1 and L2 on the join, where L1 contains columns of only E1 and L2 contains columns of only E2, we can introduce another column E3 (which is common between both the tables). Then, we can apply projections L1 and L2 on E1 and E2 respectively, along with the added column L3. L3 enables us to do the join.
Union and Intersection are commutative. Explanation: Union and intersection are both distributive; we can enclose any tables in parentheses according to requirement and ease of access.
Explanation: Union and intersection are both distributive; we can enclose any tables in parentheses according to requirement and ease of access.
Union and Intersection are associative. Explanation: Union and intersection are both distributive; we can enclose any tables in parentheses according to requirement and ease of access.
Explanation: Union and intersection are both distributive; we can enclose any tables in parentheses according to requirement and ease of access.
Selection operation distributes over the union, intersection, and difference operations. Explanation: In set difference, we know that only those tuples are shown which belong to table E1 and do not belong to table E2. So, applying a selection condition on the entire set difference is equivalent to applying the selection condition on the individual tables and then applying set difference. This will reduce the number of comparisons in the set difference step.
Explanation: In set difference, we know that only those tuples are shown which belong to table E1 and do not belong to table E2. So, applying a selection condition on the entire set difference is equivalent to applying the selection condition on the individual tables and then applying set difference. This will reduce the number of comparisons in the set difference step.
Projection operation distributes over the union operation. Explanation: Applying individual projections before computing the union of E1 and E2 is more optimal than the left expression, i.e. applying projection after the union step.
Explanation: Applying individual projections before computing the union of E1 and E2 is more optimal than the left expression, i.e. applying projection after the union step.
Minimality –A set of equivalence rules is said to be minimal if no rule can be derived from any combination of the others. A query is said to be optimal when it is minimal.
Examples –Assume the following tables:
instructor(ID, name, dept_name, salary)
teaches(ID, course_id, sec_id, semester, year)
course(course_id, title, dept_name, credits)
Query 1: Find the names of all instructors in the Music department, along with the titles of the courses that they teach
Here, dept_name is a field of only the instructor table. Hence, we can select out the Music instructors before joining the tables, hence reducing query time.
Optimized Query: Using rule 7a, and Performing the selection as early as possible reduces the size of the relation to be joined.
Query 2: Find the names of all instructors in the CSE department who have taught a course in 2009, along with the titles of the courses that they taught
Optimized Query: We can perform an “early selection”, hence the optimized query becomes:
This article is contributed by Anannya Uberoi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
kapilyadavgfg
dhruvgp18
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
SQL Trigger | Student Database
Introduction of B-Tree
SQL Interview Questions
SQL | Views
Introduction of ER Model
Difference between DELETE, DROP and TRUNCATE
Difference between SQL and NoSQL | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 Jul, 2022"
},
{
"code": null,
"e": 116,
"s": 54,
"text": "Query: A query is a request for information from a database. "
},
{
"code": null,
"e": 264,
"s": 116,
"text": "Query Plans: A query plan (or query execution plan) is an ordered set of steps used to access data in a SQL relational database management system. "
},
{
"code": null,
"e": 646,
"s": 264,
"text": "Query Optimization: A single query can be executed through different algorithms or re-written in different forms and structures. Hence, the question of query optimization comes into the picture – Which of these forms or pathways is the most optimal? The query optimizer attempts to determine the most efficient way to execute a given query by considering the possible query plans. "
},
{
"code": null,
"e": 821,
"s": 646,
"text": "Importance: The goal of query optimization is to reduce the system resources required to fulfill a query, and ultimately provide the user with the correct result set faster. "
},
{
"code": null,
"e": 924,
"s": 821,
"text": "First, it provides the user with faster results, which makes the application seem faster to the user. "
},
{
"code": null,
"e": 1071,
"s": 924,
"text": "Secondly, it allows the system to service more queries in the same amount of time, because each request takes less time than unoptimized queries. "
},
{
"code": null,
"e": 1272,
"s": 1071,
"text": "Thirdly, query optimization ultimately reduces the amount of wear on the hardware (e.g. disk drives), and allows the server to run more efficiently (e.g. lower power consumption, less memory usage). "
},
{
"code": null,
"e": 1326,
"s": 1272,
"text": "There are broadly two ways a query can be optimized: "
},
{
"code": null,
"e": 1769,
"s": 1326,
"text": "Analyze and transform equivalent relational expressions: Try to minimize the tuple and column counts of the intermediate and final query processes (discussed here).Using different algorithms for each operation: These underlying algorithms determine how tuples are accessed from the data structures they are stored in, indexing, hashing, data retrieval and hence influence the number of disk and block accesses (discussed in query processing)."
},
{
"code": null,
"e": 1934,
"s": 1769,
"text": "Analyze and transform equivalent relational expressions: Try to minimize the tuple and column counts of the intermediate and final query processes (discussed here)."
},
{
"code": null,
"e": 2213,
"s": 1934,
"text": "Using different algorithms for each operation: These underlying algorithms determine how tuples are accessed from the data structures they are stored in, indexing, hashing, data retrieval and hence influence the number of disk and block accesses (discussed in query processing)."
},
{
"code": null,
"e": 2610,
"s": 2213,
"text": "Analyze and transform equivalent relational expressions.Here, we shall talk about generating minimal equivalent expressions. To analyze equivalent expression, listed are a set of equivalence rules. These generate equivalent expressions for a query written in relational algebra. To optimize a query, we must convert the query into its equivalent form as long as an equivalence rule is satisfied. "
},
{
"code": null,
"e": 7977,
"s": 2612,
"text": "Conjunctive selection operations can be written as a sequence of individual selections. This is called a sigma-cascade. Explanation: Applying condition intersection is expensive. Instead, filter out tuples satisfying condition (inner selection) and then apply condition (outer selection) to the then resulting fewer tuples. This leaves us with less tuples to process the second time. This can be extended for two or more intersecting selections. Since we are breaking a single condition into a series of selections or cascades, it is called a “cascade”. Selection is commutative. Explanation: condition is commutative in nature. This means, it does not matter whether we apply first or first. In practice, it is better and more optimal to apply that selection first which yields a fewer number of tuples. This saves time on our outer selection. All following projections can be omitted, only the first projection is required. This is called a pi-cascade. Explanation: A cascade or a series of projections is meaningless. This is because in the end, we are only selecting those columns which are specified in the last, or the outermost projection. Hence, it is better to collapse all the projections into just one i.e. the outermost projection. Selections on Cartesian Products can be re-written as Theta Joins. Equivalence 1 Explanation: The cross product operation is known to be very expensive. This is because it matches each tuple of E1 (total m tuples) with each tuple of E2 (total n tuples). This yields m*n entries. If we apply a selection operation after that, we would have to scan through m*n entries to find the suitable tuples which satisfy the condition . Instead of doing all of this, it is more optimal to use the Theta Join, a join specifically designed to select only those entries in the cross product which satisfy the Theta condition, without evaluating the entire cross product first. Equivalence 2 Explanation: Theta Join radically decreases the number of resulting tuples, so if we apply an intersection of both the join conditions i.e. and into the Theta Join itself, we get fewer scans to do. On the other hand, a condition outside unnecessarily increases the tuples to scan. Theta Joins are commutative. Explanation: Theta Joins are commutative, and the query processing time depends to some extent which table is used as the outer loop and which one is used as the inner loop during the join process (based on the indexing structures and blocks). Join operations are associative. Natural Join Explanation: Joins are all commutative as well as associative, so one must join those two tables first which yield less number of entries, and then apply the other join. Theta Join Explanation: Theta Joins are associative in the above manner, where involves attributes from only E2 and E3. Selection operation can be distributed. Equivalence 1 Explanation: Applying a selection after doing the Theta Join causes all the tuples returned by the Theta Join to be monitored after the join. If this selection contains attributes from only E1, it is better to apply this selection to E1 (hence resulting in a fewer number of tuples) and then join it with E2. Equivalence 2 Explanation: This can be extended to two selection conditions, and , where Theta1 contains the attributes of only E1 and contains attributes of only E2. Hence, we can individually apply the selection criteria before joining, to drastically reduce the number of tuples joined. Projection distributes over the Theta Join. Equivalence 1 Explanation: The idea discussed for selection can be used for projection as well. Here, if L1 is a projection that involves columns of only E1, and L2 another projection that involves the columns of only E2, then it is better to individually apply the projections on both the tables before joining. This leaves us with a fewer number of columns on either side, hence contributing to an easier join. Equivalence 2 Explanation: Here, when applying projections L1 and L2 on the join, where L1 contains columns of only E1 and L2 contains columns of only E2, we can introduce another column E3 (which is common between both the tables). Then, we can apply projections L1 and L2 on E1 and E2 respectively, along with the added column L3. L3 enables us to do the join. Union and Intersection are commutative. Explanation: Union and intersection are both distributive; we can enclose any tables in parentheses according to requirement and ease of access. Union and Intersection are associative. Explanation: Union and intersection are both distributive; we can enclose any tables in parentheses according to requirement and ease of access. Selection operation distributes over the union, intersection, and difference operations. Explanation: In set difference, we know that only those tuples are shown which belong to table E1 and do not belong to table E2. So, applying a selection condition on the entire set difference is equivalent to applying the selection condition on the individual tables and then applying set difference. This will reduce the number of comparisons in the set difference step. Projection operation distributes over the union operation. Explanation: Applying individual projections before computing the union of E1 and E2 is more optimal than the left expression, i.e. applying projection after the union step. "
},
{
"code": null,
"e": 8533,
"s": 7977,
"text": "Conjunctive selection operations can be written as a sequence of individual selections. This is called a sigma-cascade. Explanation: Applying condition intersection is expensive. Instead, filter out tuples satisfying condition (inner selection) and then apply condition (outer selection) to the then resulting fewer tuples. This leaves us with less tuples to process the second time. This can be extended for two or more intersecting selections. Since we are breaking a single condition into a series of selections or cascades, it is called a “cascade”. "
},
{
"code": null,
"e": 8968,
"s": 8533,
"text": "Explanation: Applying condition intersection is expensive. Instead, filter out tuples satisfying condition (inner selection) and then apply condition (outer selection) to the then resulting fewer tuples. This leaves us with less tuples to process the second time. This can be extended for two or more intersecting selections. Since we are breaking a single condition into a series of selections or cascades, it is called a “cascade”. "
},
{
"code": null,
"e": 9263,
"s": 8970,
"text": "Selection is commutative. Explanation: condition is commutative in nature. This means, it does not matter whether we apply first or first. In practice, it is better and more optimal to apply that selection first which yields a fewer number of tuples. This saves time on our outer selection. "
},
{
"code": null,
"e": 9529,
"s": 9263,
"text": "Explanation: condition is commutative in nature. This means, it does not matter whether we apply first or first. In practice, it is better and more optimal to apply that selection first which yields a fewer number of tuples. This saves time on our outer selection. "
},
{
"code": null,
"e": 9932,
"s": 9531,
"text": "All following projections can be omitted, only the first projection is required. This is called a pi-cascade. Explanation: A cascade or a series of projections is meaningless. This is because in the end, we are only selecting those columns which are specified in the last, or the outermost projection. Hence, it is better to collapse all the projections into just one i.e. the outermost projection. "
},
{
"code": null,
"e": 10222,
"s": 9932,
"text": "Explanation: A cascade or a series of projections is meaningless. This is because in the end, we are only selecting those columns which are specified in the last, or the outermost projection. Hence, it is better to collapse all the projections into just one i.e. the outermost projection. "
},
{
"code": null,
"e": 11184,
"s": 10224,
"text": "Selections on Cartesian Products can be re-written as Theta Joins. Equivalence 1 Explanation: The cross product operation is known to be very expensive. This is because it matches each tuple of E1 (total m tuples) with each tuple of E2 (total n tuples). This yields m*n entries. If we apply a selection operation after that, we would have to scan through m*n entries to find the suitable tuples which satisfy the condition . Instead of doing all of this, it is more optimal to use the Theta Join, a join specifically designed to select only those entries in the cross product which satisfy the Theta condition, without evaluating the entire cross product first. Equivalence 2 Explanation: Theta Join radically decreases the number of resulting tuples, so if we apply an intersection of both the join conditions i.e. and into the Theta Join itself, we get fewer scans to do. On the other hand, a condition outside unnecessarily increases the tuples to scan. "
},
{
"code": null,
"e": 11781,
"s": 11184,
"text": "Equivalence 1 Explanation: The cross product operation is known to be very expensive. This is because it matches each tuple of E1 (total m tuples) with each tuple of E2 (total n tuples). This yields m*n entries. If we apply a selection operation after that, we would have to scan through m*n entries to find the suitable tuples which satisfy the condition . Instead of doing all of this, it is more optimal to use the Theta Join, a join specifically designed to select only those entries in the cross product which satisfy the Theta condition, without evaluating the entire cross product first. "
},
{
"code": null,
"e": 12363,
"s": 11781,
"text": "Explanation: The cross product operation is known to be very expensive. This is because it matches each tuple of E1 (total m tuples) with each tuple of E2 (total n tuples). This yields m*n entries. If we apply a selection operation after that, we would have to scan through m*n entries to find the suitable tuples which satisfy the condition . Instead of doing all of this, it is more optimal to use the Theta Join, a join specifically designed to select only those entries in the cross product which satisfy the Theta condition, without evaluating the entire cross product first. "
},
{
"code": null,
"e": 12662,
"s": 12365,
"text": "Equivalence 2 Explanation: Theta Join radically decreases the number of resulting tuples, so if we apply an intersection of both the join conditions i.e. and into the Theta Join itself, we get fewer scans to do. On the other hand, a condition outside unnecessarily increases the tuples to scan. "
},
{
"code": null,
"e": 12944,
"s": 12662,
"text": "Explanation: Theta Join radically decreases the number of resulting tuples, so if we apply an intersection of both the join conditions i.e. and into the Theta Join itself, we get fewer scans to do. On the other hand, a condition outside unnecessarily increases the tuples to scan. "
},
{
"code": null,
"e": 13221,
"s": 12946,
"text": "Theta Joins are commutative. Explanation: Theta Joins are commutative, and the query processing time depends to some extent which table is used as the outer loop and which one is used as the inner loop during the join process (based on the indexing structures and blocks). "
},
{
"code": null,
"e": 13466,
"s": 13221,
"text": "Explanation: Theta Joins are commutative, and the query processing time depends to some extent which table is used as the outer loop and which one is used as the inner loop during the join process (based on the indexing structures and blocks). "
},
{
"code": null,
"e": 13807,
"s": 13468,
"text": "Join operations are associative. Natural Join Explanation: Joins are all commutative as well as associative, so one must join those two tables first which yield less number of entries, and then apply the other join. Theta Join Explanation: Theta Joins are associative in the above manner, where involves attributes from only E2 and E3. "
},
{
"code": null,
"e": 13992,
"s": 13807,
"text": "Natural Join Explanation: Joins are all commutative as well as associative, so one must join those two tables first which yield less number of entries, and then apply the other join. "
},
{
"code": null,
"e": 14163,
"s": 13992,
"text": "Explanation: Joins are all commutative as well as associative, so one must join those two tables first which yield less number of entries, and then apply the other join. "
},
{
"code": null,
"e": 14287,
"s": 14165,
"text": "Theta Join Explanation: Theta Joins are associative in the above manner, where involves attributes from only E2 and E3. "
},
{
"code": null,
"e": 14397,
"s": 14287,
"text": "Explanation: Theta Joins are associative in the above manner, where involves attributes from only E2 and E3. "
},
{
"code": null,
"e": 15055,
"s": 14399,
"text": "Selection operation can be distributed. Equivalence 1 Explanation: Applying a selection after doing the Theta Join causes all the tuples returned by the Theta Join to be monitored after the join. If this selection contains attributes from only E1, it is better to apply this selection to E1 (hence resulting in a fewer number of tuples) and then join it with E2. Equivalence 2 Explanation: This can be extended to two selection conditions, and , where Theta1 contains the attributes of only E1 and contains attributes of only E2. Hence, we can individually apply the selection criteria before joining, to drastically reduce the number of tuples joined. "
},
{
"code": null,
"e": 15380,
"s": 15055,
"text": "Equivalence 1 Explanation: Applying a selection after doing the Theta Join causes all the tuples returned by the Theta Join to be monitored after the join. If this selection contains attributes from only E1, it is better to apply this selection to E1 (hence resulting in a fewer number of tuples) and then join it with E2. "
},
{
"code": null,
"e": 15690,
"s": 15380,
"text": "Explanation: Applying a selection after doing the Theta Join causes all the tuples returned by the Theta Join to be monitored after the join. If this selection contains attributes from only E1, it is better to apply this selection to E1 (hence resulting in a fewer number of tuples) and then join it with E2. "
},
{
"code": null,
"e": 15984,
"s": 15692,
"text": "Equivalence 2 Explanation: This can be extended to two selection conditions, and , where Theta1 contains the attributes of only E1 and contains attributes of only E2. Hence, we can individually apply the selection criteria before joining, to drastically reduce the number of tuples joined. "
},
{
"code": null,
"e": 16261,
"s": 15984,
"text": "Explanation: This can be extended to two selection conditions, and , where Theta1 contains the attributes of only E1 and contains attributes of only E2. Hence, we can individually apply the selection criteria before joining, to drastically reduce the number of tuples joined. "
},
{
"code": null,
"e": 17086,
"s": 16263,
"text": "Projection distributes over the Theta Join. Equivalence 1 Explanation: The idea discussed for selection can be used for projection as well. Here, if L1 is a projection that involves columns of only E1, and L2 another projection that involves the columns of only E2, then it is better to individually apply the projections on both the tables before joining. This leaves us with a fewer number of columns on either side, hence contributing to an easier join. Equivalence 2 Explanation: Here, when applying projections L1 and L2 on the join, where L1 contains columns of only E1 and L2 contains columns of only E2, we can introduce another column E3 (which is common between both the tables). Then, we can apply projections L1 and L2 on E1 and E2 respectively, along with the added column L3. L3 enables us to do the join. "
},
{
"code": null,
"e": 17501,
"s": 17086,
"text": "Equivalence 1 Explanation: The idea discussed for selection can be used for projection as well. Here, if L1 is a projection that involves columns of only E1, and L2 another projection that involves the columns of only E2, then it is better to individually apply the projections on both the tables before joining. This leaves us with a fewer number of columns on either side, hence contributing to an easier join. "
},
{
"code": null,
"e": 17901,
"s": 17501,
"text": "Explanation: The idea discussed for selection can be used for projection as well. Here, if L1 is a projection that involves columns of only E1, and L2 another projection that involves the columns of only E2, then it is better to individually apply the projections on both the tables before joining. This leaves us with a fewer number of columns on either side, hence contributing to an easier join. "
},
{
"code": null,
"e": 18268,
"s": 17903,
"text": "Equivalence 2 Explanation: Here, when applying projections L1 and L2 on the join, where L1 contains columns of only E1 and L2 contains columns of only E2, we can introduce another column E3 (which is common between both the tables). Then, we can apply projections L1 and L2 on E1 and E2 respectively, along with the added column L3. L3 enables us to do the join. "
},
{
"code": null,
"e": 18618,
"s": 18268,
"text": "Explanation: Here, when applying projections L1 and L2 on the join, where L1 contains columns of only E1 and L2 contains columns of only E2, we can introduce another column E3 (which is common between both the tables). Then, we can apply projections L1 and L2 on E1 and E2 respectively, along with the added column L3. L3 enables us to do the join. "
},
{
"code": null,
"e": 18807,
"s": 18620,
"text": "Union and Intersection are commutative. Explanation: Union and intersection are both distributive; we can enclose any tables in parentheses according to requirement and ease of access. "
},
{
"code": null,
"e": 18953,
"s": 18807,
"text": "Explanation: Union and intersection are both distributive; we can enclose any tables in parentheses according to requirement and ease of access. "
},
{
"code": null,
"e": 19142,
"s": 18955,
"text": "Union and Intersection are associative. Explanation: Union and intersection are both distributive; we can enclose any tables in parentheses according to requirement and ease of access. "
},
{
"code": null,
"e": 19288,
"s": 19142,
"text": "Explanation: Union and intersection are both distributive; we can enclose any tables in parentheses according to requirement and ease of access. "
},
{
"code": null,
"e": 19754,
"s": 19290,
"text": "Selection operation distributes over the union, intersection, and difference operations. Explanation: In set difference, we know that only those tuples are shown which belong to table E1 and do not belong to table E2. So, applying a selection condition on the entire set difference is equivalent to applying the selection condition on the individual tables and then applying set difference. This will reduce the number of comparisons in the set difference step. "
},
{
"code": null,
"e": 20128,
"s": 19754,
"text": "Explanation: In set difference, we know that only those tuples are shown which belong to table E1 and do not belong to table E2. So, applying a selection condition on the entire set difference is equivalent to applying the selection condition on the individual tables and then applying set difference. This will reduce the number of comparisons in the set difference step. "
},
{
"code": null,
"e": 20365,
"s": 20130,
"text": "Projection operation distributes over the union operation. Explanation: Applying individual projections before computing the union of E1 and E2 is more optimal than the left expression, i.e. applying projection after the union step. "
},
{
"code": null,
"e": 20541,
"s": 20365,
"text": "Explanation: Applying individual projections before computing the union of E1 and E2 is more optimal than the left expression, i.e. applying projection after the union step. "
},
{
"code": null,
"e": 20715,
"s": 20541,
"text": "Minimality –A set of equivalence rules is said to be minimal if no rule can be derived from any combination of the others. A query is said to be optimal when it is minimal. "
},
{
"code": null,
"e": 20758,
"s": 20717,
"text": "Examples –Assume the following tables: "
},
{
"code": null,
"e": 20890,
"s": 20758,
"text": "instructor(ID, name, dept_name, salary)\nteaches(ID, course_id, sec_id, semester, year)\ncourse(course_id, title, dept_name, credits)"
},
{
"code": null,
"e": 21012,
"s": 20890,
"text": "Query 1: Find the names of all instructors in the Music department, along with the titles of the courses that they teach "
},
{
"code": null,
"e": 21171,
"s": 21012,
"text": "Here, dept_name is a field of only the instructor table. Hence, we can select out the Music instructors before joining the tables, hence reducing query time. "
},
{
"code": null,
"e": 21301,
"s": 21171,
"text": "Optimized Query: Using rule 7a, and Performing the selection as early as possible reduces the size of the relation to be joined. "
},
{
"code": null,
"e": 21455,
"s": 21301,
"text": "Query 2: Find the names of all instructors in the CSE department who have taught a course in 2009, along with the titles of the courses that they taught "
},
{
"code": null,
"e": 21545,
"s": 21455,
"text": "Optimized Query: We can perform an “early selection”, hence the optimized query becomes: "
},
{
"code": null,
"e": 21850,
"s": 21545,
"text": " This article is contributed by Anannya Uberoi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 21976,
"s": 21850,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 21989,
"s": 21976,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 22003,
"s": 21989,
"text": "kapilyadavgfg"
},
{
"code": null,
"e": 22013,
"s": 22003,
"text": "dhruvgp18"
},
{
"code": null,
"e": 22018,
"s": 22013,
"text": "DBMS"
},
{
"code": null,
"e": 22023,
"s": 22018,
"text": "DBMS"
},
{
"code": null,
"e": 22121,
"s": 22023,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 22132,
"s": 22121,
"text": "CTE in SQL"
},
{
"code": null,
"e": 22185,
"s": 22132,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 22243,
"s": 22185,
"text": "Introduction of DBMS (Database Management System) | Set 1"
},
{
"code": null,
"e": 22274,
"s": 22243,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 22297,
"s": 22274,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 22321,
"s": 22297,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 22333,
"s": 22321,
"text": "SQL | Views"
},
{
"code": null,
"e": 22358,
"s": 22333,
"text": "Introduction of ER Model"
},
{
"code": null,
"e": 22403,
"s": 22358,
"text": "Difference between DELETE, DROP and TRUNCATE"
}
] |
SQL Query to Remove Decimal Values | 23 Sep, 2021
Decimal values are those values that have “float” as a datatype.
There are various methods to remove decimal values in SQL:
Using ROUND() function: This function in SQL Server is used to round off a specified number to a specified decimal places
Using FLOOR() function: It returns the largest integer value that is less than or equal to a number.
Using CAST() function: The explicit conversion has to be done in SQL Server using Cast or Convert function.
STEP 1: Creating a database
Use the below SQL statement to create a database called geeks:
Query:
CREATE DATABASE geeks;
Step 2: Using the database
Use the below SQL statement to switch the database context to geeks:
Query:
USE geeks;
Step 3: Table definition
We have the following geeks for geeks table in our geek’s database.
Query:
CREATE TABLE geeksforgeeks(
NAME VARCHAR(10),
MARKS float);
Step 4: Insert data into a table
Query:
INSERT INTO geeksforgeeks VALUES ('ROMY',80.9),('MEENAKSHI',86.89),('SHALINI',85.9),('SAMBHAVI', 89.45);
Step 5:Check value of the table
Content of the table can be viewed using the SELECT command.
Query:
SELECT * FROM geeksforgeeks;
Step 6:Use function to remove decimal values
ROUND(): This function rounds a number to the specified decimal places. If we want to remove all the decimal values, we will round it to decimal place 0.
Syntax:
ROUND(Value, decimal_place)
Query:
SELECT NAME, ROUND(MARKS,0) AS MARKS FROM geeksforgeeks;
Output:
80.0 is rounded to 81 as 81 is the nearest integer value.
FLOOR(): This function returns the largest integer value which is less than or equal to the value used as a parameter.
Syntax:
FLOOR(value)
Query:
SELECT NAME, FLOOR(MARKS) AS MARKS FROM geeksforgeeks;
Output:
Here, 80.9 gets converted to 80, as FLOOR() returns a value less than or equal to the given value but can not return the value greater than the given one.
CAST(): This function is used to convert the value into a specific data type.
Syntax:
CAST( value as datatype)
Query:
SELECT NAME, CAST(MARKS as INT) AS MARKS FROM geeksforgeeks;
Output:
This gives results similar to the FLOOR() function. Results vary slightly according to the function used. One should choose according to the need.
Blogathon-2021
Picked
SQL-Server
Blogathon
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Consensus Problem of Distributed Systems
Scraping Reddit using Python
Ccat – Colorize Cat Command Output command in Linux with Examples
Wired Communication Media
How to Build a Simple Auto-Login Bot with Python
SQL | DDL, DQL, DML, DCL and TCL Commands
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
Difference between DELETE, DROP and TRUNCATE
CTE in SQL | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 93,
"s": 28,
"text": "Decimal values are those values that have “float” as a datatype."
},
{
"code": null,
"e": 152,
"s": 93,
"text": "There are various methods to remove decimal values in SQL:"
},
{
"code": null,
"e": 274,
"s": 152,
"text": "Using ROUND() function: This function in SQL Server is used to round off a specified number to a specified decimal places"
},
{
"code": null,
"e": 376,
"s": 274,
"text": "Using FLOOR() function: It returns the largest integer value that is less than or equal to a number. "
},
{
"code": null,
"e": 484,
"s": 376,
"text": "Using CAST() function: The explicit conversion has to be done in SQL Server using Cast or Convert function."
},
{
"code": null,
"e": 512,
"s": 484,
"text": "STEP 1: Creating a database"
},
{
"code": null,
"e": 575,
"s": 512,
"text": "Use the below SQL statement to create a database called geeks:"
},
{
"code": null,
"e": 583,
"s": 575,
"text": "Query: "
},
{
"code": null,
"e": 606,
"s": 583,
"text": "CREATE DATABASE geeks;"
},
{
"code": null,
"e": 635,
"s": 606,
"text": "Step 2: Using the database "
},
{
"code": null,
"e": 704,
"s": 635,
"text": "Use the below SQL statement to switch the database context to geeks:"
},
{
"code": null,
"e": 711,
"s": 704,
"text": "Query:"
},
{
"code": null,
"e": 722,
"s": 711,
"text": "USE geeks;"
},
{
"code": null,
"e": 747,
"s": 722,
"text": "Step 3: Table definition"
},
{
"code": null,
"e": 815,
"s": 747,
"text": "We have the following geeks for geeks table in our geek’s database."
},
{
"code": null,
"e": 822,
"s": 815,
"text": "Query:"
},
{
"code": null,
"e": 882,
"s": 822,
"text": "CREATE TABLE geeksforgeeks(\nNAME VARCHAR(10),\nMARKS float);"
},
{
"code": null,
"e": 915,
"s": 882,
"text": "Step 4: Insert data into a table"
},
{
"code": null,
"e": 922,
"s": 915,
"text": "Query:"
},
{
"code": null,
"e": 1027,
"s": 922,
"text": "INSERT INTO geeksforgeeks VALUES ('ROMY',80.9),('MEENAKSHI',86.89),('SHALINI',85.9),('SAMBHAVI', 89.45);"
},
{
"code": null,
"e": 1059,
"s": 1027,
"text": "Step 5:Check value of the table"
},
{
"code": null,
"e": 1120,
"s": 1059,
"text": "Content of the table can be viewed using the SELECT command."
},
{
"code": null,
"e": 1127,
"s": 1120,
"text": "Query:"
},
{
"code": null,
"e": 1156,
"s": 1127,
"text": "SELECT * FROM geeksforgeeks;"
},
{
"code": null,
"e": 1201,
"s": 1156,
"text": "Step 6:Use function to remove decimal values"
},
{
"code": null,
"e": 1355,
"s": 1201,
"text": "ROUND(): This function rounds a number to the specified decimal places. If we want to remove all the decimal values, we will round it to decimal place 0."
},
{
"code": null,
"e": 1363,
"s": 1355,
"text": "Syntax:"
},
{
"code": null,
"e": 1391,
"s": 1363,
"text": "ROUND(Value, decimal_place)"
},
{
"code": null,
"e": 1398,
"s": 1391,
"text": "Query:"
},
{
"code": null,
"e": 1455,
"s": 1398,
"text": "SELECT NAME, ROUND(MARKS,0) AS MARKS FROM geeksforgeeks;"
},
{
"code": null,
"e": 1463,
"s": 1455,
"text": "Output:"
},
{
"code": null,
"e": 1521,
"s": 1463,
"text": "80.0 is rounded to 81 as 81 is the nearest integer value."
},
{
"code": null,
"e": 1640,
"s": 1521,
"text": "FLOOR(): This function returns the largest integer value which is less than or equal to the value used as a parameter."
},
{
"code": null,
"e": 1648,
"s": 1640,
"text": "Syntax:"
},
{
"code": null,
"e": 1662,
"s": 1648,
"text": " FLOOR(value)"
},
{
"code": null,
"e": 1669,
"s": 1662,
"text": "Query:"
},
{
"code": null,
"e": 1724,
"s": 1669,
"text": "SELECT NAME, FLOOR(MARKS) AS MARKS FROM geeksforgeeks;"
},
{
"code": null,
"e": 1732,
"s": 1724,
"text": "Output:"
},
{
"code": null,
"e": 1888,
"s": 1732,
"text": "Here, 80.9 gets converted to 80, as FLOOR() returns a value less than or equal to the given value but can not return the value greater than the given one. "
},
{
"code": null,
"e": 1966,
"s": 1888,
"text": "CAST(): This function is used to convert the value into a specific data type."
},
{
"code": null,
"e": 1974,
"s": 1966,
"text": "Syntax:"
},
{
"code": null,
"e": 1999,
"s": 1974,
"text": "CAST( value as datatype)"
},
{
"code": null,
"e": 2006,
"s": 1999,
"text": "Query:"
},
{
"code": null,
"e": 2067,
"s": 2006,
"text": "SELECT NAME, CAST(MARKS as INT) AS MARKS FROM geeksforgeeks;"
},
{
"code": null,
"e": 2075,
"s": 2067,
"text": "Output:"
},
{
"code": null,
"e": 2222,
"s": 2075,
"text": "This gives results similar to the FLOOR() function. Results vary slightly according to the function used. One should choose according to the need."
},
{
"code": null,
"e": 2237,
"s": 2222,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 2244,
"s": 2237,
"text": "Picked"
},
{
"code": null,
"e": 2255,
"s": 2244,
"text": "SQL-Server"
},
{
"code": null,
"e": 2265,
"s": 2255,
"text": "Blogathon"
},
{
"code": null,
"e": 2269,
"s": 2265,
"text": "SQL"
},
{
"code": null,
"e": 2273,
"s": 2269,
"text": "SQL"
},
{
"code": null,
"e": 2371,
"s": 2273,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2412,
"s": 2371,
"text": "Consensus Problem of Distributed Systems"
},
{
"code": null,
"e": 2441,
"s": 2412,
"text": "Scraping Reddit using Python"
},
{
"code": null,
"e": 2507,
"s": 2441,
"text": "Ccat – Colorize Cat Command Output command in Linux with Examples"
},
{
"code": null,
"e": 2533,
"s": 2507,
"text": "Wired Communication Media"
},
{
"code": null,
"e": 2582,
"s": 2533,
"text": "How to Build a Simple Auto-Login Bot with Python"
},
{
"code": null,
"e": 2624,
"s": 2582,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 2671,
"s": 2624,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 2689,
"s": 2671,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 2734,
"s": 2689,
"text": "Difference between DELETE, DROP and TRUNCATE"
}
] |
How to Fix: NameError name ‘pd’ is not defined | 28 Nov, 2021
In this article we will discuss how to fix NameError pd is not defined in Python.
When we imported pandas module without alias and used pd in the code, the error comes up.
Example: Code to depict error
Python3
# import pandas moduleimport pandas # create dataframedata = pd.DataFrame({'a': [1, 2], 'b': [3, 4]}) # displaydata
Output:
—————————————————————————
NameError Traceback (most recent call last)
<ipython-input-1-a37aacbaa7a7> in <module>()
3
4 #create dataframe
—-> 5 data=pd.DataFrame({‘a’:[1,2],’b’:[3,4]})
6
7 #display
NameError: name ‘pd’ is not defined
Here pd is an alias of the pandas module so we can either import pandas module with alias or import pandas without the alias and use the name directly.
we can use alias at the time of import to resolve the error
Syntax:
import pandas as pd
Example: Program to import pandas as alias
Python3
# import pandas moduleimport pandas as pd # create dataframedata = pd.DataFrame({'a': [1, 2], 'b': [3, 4]}) # displaydata
Output:
a b
0 1 3
1 2 4
We can use pandas module directly to use in a data structure.
Syntax:
import pandas
Example: Using Pandas directly
Python3
# import pandas moduleimport pandas # create dataframedata = pandas.DataFrame({'a': [1, 2], 'b': [3, 4]}) # displaydata
Output:
a b
0 1 3
1 2 4
Picked
Python How-to-fix
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 110,
"s": 28,
"text": "In this article we will discuss how to fix NameError pd is not defined in Python."
},
{
"code": null,
"e": 200,
"s": 110,
"text": "When we imported pandas module without alias and used pd in the code, the error comes up."
},
{
"code": null,
"e": 230,
"s": 200,
"text": "Example: Code to depict error"
},
{
"code": null,
"e": 238,
"s": 230,
"text": "Python3"
},
{
"code": "# import pandas moduleimport pandas # create dataframedata = pd.DataFrame({'a': [1, 2], 'b': [3, 4]}) # displaydata",
"e": 356,
"s": 238,
"text": null
},
{
"code": null,
"e": 364,
"s": 356,
"text": "Output:"
},
{
"code": null,
"e": 390,
"s": 364,
"text": "—————————————————————————"
},
{
"code": null,
"e": 466,
"s": 390,
"text": "NameError Traceback (most recent call last)"
},
{
"code": null,
"e": 511,
"s": 466,
"text": "<ipython-input-1-a37aacbaa7a7> in <module>()"
},
{
"code": null,
"e": 520,
"s": 511,
"text": " 3 "
},
{
"code": null,
"e": 546,
"s": 520,
"text": " 4 #create dataframe"
},
{
"code": null,
"e": 593,
"s": 546,
"text": "—-> 5 data=pd.DataFrame({‘a’:[1,2],’b’:[3,4]})"
},
{
"code": null,
"e": 602,
"s": 593,
"text": " 6 "
},
{
"code": null,
"e": 619,
"s": 602,
"text": " 7 #display"
},
{
"code": null,
"e": 655,
"s": 619,
"text": "NameError: name ‘pd’ is not defined"
},
{
"code": null,
"e": 807,
"s": 655,
"text": "Here pd is an alias of the pandas module so we can either import pandas module with alias or import pandas without the alias and use the name directly."
},
{
"code": null,
"e": 867,
"s": 807,
"text": "we can use alias at the time of import to resolve the error"
},
{
"code": null,
"e": 875,
"s": 867,
"text": "Syntax:"
},
{
"code": null,
"e": 895,
"s": 875,
"text": "import pandas as pd"
},
{
"code": null,
"e": 938,
"s": 895,
"text": "Example: Program to import pandas as alias"
},
{
"code": null,
"e": 946,
"s": 938,
"text": "Python3"
},
{
"code": "# import pandas moduleimport pandas as pd # create dataframedata = pd.DataFrame({'a': [1, 2], 'b': [3, 4]}) # displaydata",
"e": 1070,
"s": 946,
"text": null
},
{
"code": null,
"e": 1078,
"s": 1070,
"text": "Output:"
},
{
"code": null,
"e": 1113,
"s": 1078,
"text": " a b\n0 1 3\n1 2 4"
},
{
"code": null,
"e": 1175,
"s": 1113,
"text": "We can use pandas module directly to use in a data structure."
},
{
"code": null,
"e": 1183,
"s": 1175,
"text": "Syntax:"
},
{
"code": null,
"e": 1197,
"s": 1183,
"text": "import pandas"
},
{
"code": null,
"e": 1228,
"s": 1197,
"text": "Example: Using Pandas directly"
},
{
"code": null,
"e": 1236,
"s": 1228,
"text": "Python3"
},
{
"code": "# import pandas moduleimport pandas # create dataframedata = pandas.DataFrame({'a': [1, 2], 'b': [3, 4]}) # displaydata",
"e": 1358,
"s": 1236,
"text": null
},
{
"code": null,
"e": 1366,
"s": 1358,
"text": "Output:"
},
{
"code": null,
"e": 1401,
"s": 1366,
"text": " a b\n0 1 3\n1 2 4"
},
{
"code": null,
"e": 1408,
"s": 1401,
"text": "Picked"
},
{
"code": null,
"e": 1426,
"s": 1408,
"text": "Python How-to-fix"
},
{
"code": null,
"e": 1433,
"s": 1426,
"text": "Python"
}
] |
How to Find Size of an Array in C/C++ Without Using sizeof() Operator? | 23 May, 2022
In C++, we use sizeof() operator to find the size of desired data type, variables, and constants. It is a compile-time execution operator. We can find the size of an array using the sizeof() operator as shown:
// Finds size of arr[] and stores in 'size'
int size = sizeof(arr)/sizeof(arr[0]);
Can we do the same without using the sizeof() operator?
Given an array (you don’t know the type of elements in the array), find the total number of elements in the array without using the sizeof() operator?
Approach 1: Implement our own sizeof
CPP
// C++ program to find size of// an array by writing our// own sizeof operator#include <bits/stdc++.h>using namespace std; // User defined sizeof macro# define my_sizeof(type) ((char *)(&type+1)-(char*)(&type)) int main(){ int arr[] = {1, 2, 3, 4, 5, 6}; int size = my_sizeof(arr)/my_sizeof(arr[0]); cout << "Number of elements in arr[] is " << size; return 0;}
Output:
Number of elements in arr[] is 6
Approach 2: Using a pointer hack
The following solution is very short when compared to the above solution. The number of elements in an array A can be found using the expression:
int size = *(&arr + 1) - arr; // &arr returns a pointer
CPP
// C++ program to find size // of an array by using a // pointer hack#include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int size = *(&arr + 1) - arr; cout << "Number of elements in arr[] is " << size; return 0;}
Output:
Number of elements in arr[] is 6
How does this work?
Here the pointer arithmetic does its part. We don’t need to explicitly convert each of the locations to character pointers.
&arr – Pointer to an array of 6 elements. [See this for difference between &arr and arr]
(&arr + 1) – Address of 6 integers ahead as pointer type is a pointer to an array of 6 integers. In simple words, (&arr + 1) is the address of integers ahead.
*(&arr + 1) – Same address as (&arr + 1), but type of pointer is “int *”.
*(&arr + 1) – arr – Since *(&arr + 1) points to the address 6 integers ahead of arr, the difference between two is 6.
This article is contributed by Nikhil Chakravartula. If you like GeeksforGeeks and would like to contribute, you can also write an article on write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above
harsh_shokeen
cpp-array
cpp-operator
cpp-sizeof
C Language
C++
cpp-operator
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 May, 2022"
},
{
"code": null,
"e": 262,
"s": 52,
"text": "In C++, we use sizeof() operator to find the size of desired data type, variables, and constants. It is a compile-time execution operator. We can find the size of an array using the sizeof() operator as shown:"
},
{
"code": null,
"e": 345,
"s": 262,
"text": "// Finds size of arr[] and stores in 'size'\nint size = sizeof(arr)/sizeof(arr[0]);"
},
{
"code": null,
"e": 402,
"s": 345,
"text": "Can we do the same without using the sizeof() operator? "
},
{
"code": null,
"e": 553,
"s": 402,
"text": "Given an array (you don’t know the type of elements in the array), find the total number of elements in the array without using the sizeof() operator?"
},
{
"code": null,
"e": 590,
"s": 553,
"text": "Approach 1: Implement our own sizeof"
},
{
"code": null,
"e": 594,
"s": 590,
"text": "CPP"
},
{
"code": "// C++ program to find size of// an array by writing our// own sizeof operator#include <bits/stdc++.h>using namespace std; // User defined sizeof macro# define my_sizeof(type) ((char *)(&type+1)-(char*)(&type)) int main(){ int arr[] = {1, 2, 3, 4, 5, 6}; int size = my_sizeof(arr)/my_sizeof(arr[0]); cout << \"Number of elements in arr[] is \" << size; return 0;}",
"e": 981,
"s": 594,
"text": null
},
{
"code": null,
"e": 989,
"s": 981,
"text": "Output:"
},
{
"code": null,
"e": 1022,
"s": 989,
"text": "Number of elements in arr[] is 6"
},
{
"code": null,
"e": 1055,
"s": 1022,
"text": "Approach 2: Using a pointer hack"
},
{
"code": null,
"e": 1202,
"s": 1055,
"text": " The following solution is very short when compared to the above solution. The number of elements in an array A can be found using the expression:"
},
{
"code": null,
"e": 1259,
"s": 1202,
"text": "int size = *(&arr + 1) - arr; // &arr returns a pointer "
},
{
"code": null,
"e": 1263,
"s": 1259,
"text": "CPP"
},
{
"code": "// C++ program to find size // of an array by using a // pointer hack#include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int size = *(&arr + 1) - arr; cout << \"Number of elements in arr[] is \" << size; return 0;}",
"e": 1528,
"s": 1263,
"text": null
},
{
"code": null,
"e": 1536,
"s": 1528,
"text": "Output:"
},
{
"code": null,
"e": 1569,
"s": 1536,
"text": "Number of elements in arr[] is 6"
},
{
"code": null,
"e": 1590,
"s": 1569,
"text": "How does this work? "
},
{
"code": null,
"e": 1714,
"s": 1590,
"text": "Here the pointer arithmetic does its part. We don’t need to explicitly convert each of the locations to character pointers."
},
{
"code": null,
"e": 1803,
"s": 1714,
"text": "&arr – Pointer to an array of 6 elements. [See this for difference between &arr and arr]"
},
{
"code": null,
"e": 1962,
"s": 1803,
"text": "(&arr + 1) – Address of 6 integers ahead as pointer type is a pointer to an array of 6 integers. In simple words, (&arr + 1) is the address of integers ahead."
},
{
"code": null,
"e": 2036,
"s": 1962,
"text": "*(&arr + 1) – Same address as (&arr + 1), but type of pointer is “int *”."
},
{
"code": null,
"e": 2154,
"s": 2036,
"text": "*(&arr + 1) – arr – Since *(&arr + 1) points to the address 6 integers ahead of arr, the difference between two is 6."
},
{
"code": null,
"e": 2528,
"s": 2154,
"text": "This article is contributed by Nikhil Chakravartula. If you like GeeksforGeeks and would like to contribute, you can also write an article on write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 2542,
"s": 2528,
"text": "harsh_shokeen"
},
{
"code": null,
"e": 2552,
"s": 2542,
"text": "cpp-array"
},
{
"code": null,
"e": 2565,
"s": 2552,
"text": "cpp-operator"
},
{
"code": null,
"e": 2576,
"s": 2565,
"text": "cpp-sizeof"
},
{
"code": null,
"e": 2587,
"s": 2576,
"text": "C Language"
},
{
"code": null,
"e": 2591,
"s": 2587,
"text": "C++"
},
{
"code": null,
"e": 2604,
"s": 2591,
"text": "cpp-operator"
},
{
"code": null,
"e": 2608,
"s": 2604,
"text": "CPP"
}
] |
numpy.ndarray.itemsize() method | Python | 26 Mar, 2020
numpy.ndarray.itemsize() function return the length of one array element in bytes.
Syntax : numpy.ndarray.itemsize(arr)
Parameters :arr : [array_like] Input array.
Return : [int] The length of one array element in bytes
Code #1 :
# Python program explaining# numpy.ndarray.itemsize() function # importing numpy as geek import numpy as geek arr = geek.array([1, 2, 3, 4], dtype = geek.float64) gfg = arr.itemsize print (gfg)
Output :
8
Code #2 :
# Python program explaining# numpy.ndarray.itemsize() function # importing numpy as geek import numpy as geek arr = geek.array([1, 2, 3, 4], dtype = geek.complex128) gfg = arr.itemsize print (gfg)
Output :
16
Python numpy-ndarray
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
reduce() in Python
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 111,
"s": 28,
"text": "numpy.ndarray.itemsize() function return the length of one array element in bytes."
},
{
"code": null,
"e": 148,
"s": 111,
"text": "Syntax : numpy.ndarray.itemsize(arr)"
},
{
"code": null,
"e": 192,
"s": 148,
"text": "Parameters :arr : [array_like] Input array."
},
{
"code": null,
"e": 248,
"s": 192,
"text": "Return : [int] The length of one array element in bytes"
},
{
"code": null,
"e": 258,
"s": 248,
"text": "Code #1 :"
},
{
"code": "# Python program explaining# numpy.ndarray.itemsize() function # importing numpy as geek import numpy as geek arr = geek.array([1, 2, 3, 4], dtype = geek.float64) gfg = arr.itemsize print (gfg)",
"e": 456,
"s": 258,
"text": null
},
{
"code": null,
"e": 465,
"s": 456,
"text": "Output :"
},
{
"code": null,
"e": 468,
"s": 465,
"text": "8\n"
},
{
"code": null,
"e": 479,
"s": 468,
"text": " Code #2 :"
},
{
"code": "# Python program explaining# numpy.ndarray.itemsize() function # importing numpy as geek import numpy as geek arr = geek.array([1, 2, 3, 4], dtype = geek.complex128) gfg = arr.itemsize print (gfg)",
"e": 681,
"s": 479,
"text": null
},
{
"code": null,
"e": 690,
"s": 681,
"text": "Output :"
},
{
"code": null,
"e": 694,
"s": 690,
"text": "16\n"
},
{
"code": null,
"e": 715,
"s": 694,
"text": "Python numpy-ndarray"
},
{
"code": null,
"e": 728,
"s": 715,
"text": "Python-numpy"
},
{
"code": null,
"e": 735,
"s": 728,
"text": "Python"
},
{
"code": null,
"e": 833,
"s": 735,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 878,
"s": 833,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 928,
"s": 878,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 944,
"s": 928,
"text": "Deque in Python"
},
{
"code": null,
"e": 960,
"s": 944,
"text": "Queue in Python"
},
{
"code": null,
"e": 982,
"s": 960,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1024,
"s": 982,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1051,
"s": 1024,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1074,
"s": 1051,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 1093,
"s": 1074,
"text": "reduce() in Python"
}
] |
GATE | GATE-CS-2015 (Set 1) | Question 20 - GeeksforGeeks | 28 Jun, 2021
Which of the following is/are correct inorder traversal sequence(s) of binary search tree(s)?
1. 3, 5, 7, 8, 15, 19, 25
2. 5, 8, 9, 12, 10, 15, 25
3. 2, 7, 10, 8, 14, 16, 20
4. 4, 6, 7, 9, 18, 20, 25
(A) 1 and 4 only(B) 2 and 3 only(C) 2 and 4 only(D) 2 onlyAnswer: (A)Explanation: An Inorder traversal of a Binary Search Tree must be in increasing order.Quiz of this Question
GATE-CS-2015 (Set 1)
GATE-GATE-CS-2015 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90 | [
{
"code": null,
"e": 25695,
"s": 25667,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25789,
"s": 25695,
"text": "Which of the following is/are correct inorder traversal sequence(s) of binary search tree(s)?"
},
{
"code": null,
"e": 25896,
"s": 25789,
"text": "1. 3, 5, 7, 8, 15, 19, 25\n2. 5, 8, 9, 12, 10, 15, 25\n3. 2, 7, 10, 8, 14, 16, 20\n4. 4, 6, 7, 9, 18, 20, 25 "
},
{
"code": null,
"e": 26073,
"s": 25896,
"text": "(A) 1 and 4 only(B) 2 and 3 only(C) 2 and 4 only(D) 2 onlyAnswer: (A)Explanation: An Inorder traversal of a Binary Search Tree must be in increasing order.Quiz of this Question"
},
{
"code": null,
"e": 26094,
"s": 26073,
"text": "GATE-CS-2015 (Set 1)"
},
{
"code": null,
"e": 26120,
"s": 26094,
"text": "GATE-GATE-CS-2015 (Set 1)"
},
{
"code": null,
"e": 26125,
"s": 26120,
"text": "GATE"
},
{
"code": null,
"e": 26223,
"s": 26125,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26257,
"s": 26223,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 26291,
"s": 26257,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 26325,
"s": 26291,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 26358,
"s": 26325,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 26394,
"s": 26358,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 26430,
"s": 26394,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 26464,
"s": 26430,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 26498,
"s": 26464,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 26532,
"s": 26498,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
Higher Order Functions in Python - GeeksforGeeks | 30 Jan, 2020
A function is called Higher Order Function if it contains other functions as a parameter or returns a function as an output i.e, the functions that operate with another function are known as Higher order Functions. It is worth knowing that this higher order function is applicable for functions and methods as well that takes functions as a parameter or returns a function as a result. Python too supports the concepts of higher order functions.
Properties of higher-order functions:
A function is an instance of the Object type.
You can store the function in a variable.
You can pass the function as a parameter to another function.
You can return the function from a function.
You can store them in data structures such as hash tables, lists, ...
In Python, a function can be assigned to a variable. This assignment does not call the function, instead a reference to that function is created. Consider the below example, for better understanding.
Example:
# Python program to illustrate functions # can be treated as objects def shout(text): return text.upper() print(shout('Hello')) # Assigning function to a variableyell = shout print(yell('Hello'))
Output:
HELLO
HELLO
In the above example, a function object referenced by shout and creates a second name pointing to it, yell.
Functions are like objects in Python, therefore, they can be passed as argument to other functions. Consider the below example, where we have created a function greet which takes a function as an argument.
Example:
# Python program to illustrate functions # can be passed as arguments to other functions def shout(text): return text.upper() def whisper(text): return text.lower() def greet(func): # storing the function in a variable greeting = func("Hi, I am created by a function \ passed as an argument.") print(greeting) greet(shout) greet(whisper)
Output:
HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
hi, i am created by a function passed as an argument.
As functions are objects, we can also return a function from another function. In the below example, the create_adder function returns adder function.
Example:
# Python program to illustrate functions # Functions can return another function def create_adder(x): def adder(y): return x + y return adder add_15 = create_adder(15) print(add_15(10))
Output:
25
Decorators are the most common use of higher-order functions in Python. It allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of wrapped function, without permanently modifying it. In Decorators, functions are taken as the argument into another function and then called inside the wrapper function.
Syntax:
@gfg_decorator
def hello_decorator():
.
.
.
The above code is equivalent to –
def hello_decorator():
.
.
.
hello_decorator = gfg_decorator(hello_decorator)
In the above code, gfg_decorator is a callable function, will add some code on the top of some another callable function, hello_decorator function and return the wrapper function.
Example:
# defining a decorator def hello_decorator(func): # inner1 is a Wrapper function in # which the argument is called # inner function can access the outer local # functions like in this case "func" def inner1(): print("Hello, this is before function execution") # calling the actual function now # inside the wrapper function. func() print("This is after function execution") return inner1 # defining a function, to be called inside wrapper def function_to_be_used(): print("This is inside the function !!") # passing 'function_to_be_used' inside the # decorator to control its behavior function_to_be_used = hello_decorator(function_to_be_used) # calling the function function_to_be_used()
Output:
Hello, this is before function execution
This is inside the function !!
This is after function execution
Note: For more information, refer to Decorators in Python.
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n30 Jan, 2020"
},
{
"code": null,
"e": 25983,
"s": 25537,
"text": "A function is called Higher Order Function if it contains other functions as a parameter or returns a function as an output i.e, the functions that operate with another function are known as Higher order Functions. It is worth knowing that this higher order function is applicable for functions and methods as well that takes functions as a parameter or returns a function as a result. Python too supports the concepts of higher order functions."
},
{
"code": null,
"e": 26021,
"s": 25983,
"text": "Properties of higher-order functions:"
},
{
"code": null,
"e": 26067,
"s": 26021,
"text": "A function is an instance of the Object type."
},
{
"code": null,
"e": 26109,
"s": 26067,
"text": "You can store the function in a variable."
},
{
"code": null,
"e": 26171,
"s": 26109,
"text": "You can pass the function as a parameter to another function."
},
{
"code": null,
"e": 26216,
"s": 26171,
"text": "You can return the function from a function."
},
{
"code": null,
"e": 26286,
"s": 26216,
"text": "You can store them in data structures such as hash tables, lists, ..."
},
{
"code": null,
"e": 26486,
"s": 26286,
"text": "In Python, a function can be assigned to a variable. This assignment does not call the function, instead a reference to that function is created. Consider the below example, for better understanding."
},
{
"code": null,
"e": 26495,
"s": 26486,
"text": "Example:"
},
{
"code": "# Python program to illustrate functions # can be treated as objects def shout(text): return text.upper() print(shout('Hello')) # Assigning function to a variableyell = shout print(yell('Hello'))",
"e": 26707,
"s": 26495,
"text": null
},
{
"code": null,
"e": 26715,
"s": 26707,
"text": "Output:"
},
{
"code": null,
"e": 26728,
"s": 26715,
"text": "HELLO\nHELLO\n"
},
{
"code": null,
"e": 26836,
"s": 26728,
"text": "In the above example, a function object referenced by shout and creates a second name pointing to it, yell."
},
{
"code": null,
"e": 27042,
"s": 26836,
"text": "Functions are like objects in Python, therefore, they can be passed as argument to other functions. Consider the below example, where we have created a function greet which takes a function as an argument."
},
{
"code": null,
"e": 27051,
"s": 27042,
"text": "Example:"
},
{
"code": "# Python program to illustrate functions # can be passed as arguments to other functions def shout(text): return text.upper() def whisper(text): return text.lower() def greet(func): # storing the function in a variable greeting = func(\"Hi, I am created by a function \\ passed as an argument.\") print(greeting) greet(shout) greet(whisper)",
"e": 27425,
"s": 27051,
"text": null
},
{
"code": null,
"e": 27433,
"s": 27425,
"text": "Output:"
},
{
"code": null,
"e": 27542,
"s": 27433,
"text": "HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.\nhi, i am created by a function passed as an argument.\n"
},
{
"code": null,
"e": 27693,
"s": 27542,
"text": "As functions are objects, we can also return a function from another function. In the below example, the create_adder function returns adder function."
},
{
"code": null,
"e": 27702,
"s": 27693,
"text": "Example:"
},
{
"code": "# Python program to illustrate functions # Functions can return another function def create_adder(x): def adder(y): return x + y return adder add_15 = create_adder(15) print(add_15(10))",
"e": 27920,
"s": 27702,
"text": null
},
{
"code": null,
"e": 27928,
"s": 27920,
"text": "Output:"
},
{
"code": null,
"e": 27932,
"s": 27928,
"text": "25\n"
},
{
"code": null,
"e": 28321,
"s": 27932,
"text": "Decorators are the most common use of higher-order functions in Python. It allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of wrapped function, without permanently modifying it. In Decorators, functions are taken as the argument into another function and then called inside the wrapper function."
},
{
"code": null,
"e": 28329,
"s": 28321,
"text": "Syntax:"
},
{
"code": null,
"e": 28387,
"s": 28329,
"text": "@gfg_decorator\ndef hello_decorator(): \n .\n .\n .\n"
},
{
"code": null,
"e": 28421,
"s": 28387,
"text": "The above code is equivalent to –"
},
{
"code": null,
"e": 28521,
"s": 28421,
"text": "\ndef hello_decorator(): \n .\n .\n .\n \nhello_decorator = gfg_decorator(hello_decorator)\n"
},
{
"code": null,
"e": 28701,
"s": 28521,
"text": "In the above code, gfg_decorator is a callable function, will add some code on the top of some another callable function, hello_decorator function and return the wrapper function."
},
{
"code": null,
"e": 28710,
"s": 28701,
"text": "Example:"
},
{
"code": "# defining a decorator def hello_decorator(func): # inner1 is a Wrapper function in # which the argument is called # inner function can access the outer local # functions like in this case \"func\" def inner1(): print(\"Hello, this is before function execution\") # calling the actual function now # inside the wrapper function. func() print(\"This is after function execution\") return inner1 # defining a function, to be called inside wrapper def function_to_be_used(): print(\"This is inside the function !!\") # passing 'function_to_be_used' inside the # decorator to control its behavior function_to_be_used = hello_decorator(function_to_be_used) # calling the function function_to_be_used() ",
"e": 29525,
"s": 28710,
"text": null
},
{
"code": null,
"e": 29533,
"s": 29525,
"text": "Output:"
},
{
"code": null,
"e": 29639,
"s": 29533,
"text": "Hello, this is before function execution\nThis is inside the function !!\nThis is after function execution\n"
},
{
"code": null,
"e": 29698,
"s": 29639,
"text": "Note: For more information, refer to Decorators in Python."
},
{
"code": null,
"e": 29715,
"s": 29698,
"text": "Python-Functions"
},
{
"code": null,
"e": 29722,
"s": 29715,
"text": "Python"
},
{
"code": null,
"e": 29820,
"s": 29722,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29852,
"s": 29820,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29894,
"s": 29852,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29936,
"s": 29894,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29992,
"s": 29936,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30019,
"s": 29992,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30050,
"s": 30019,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30089,
"s": 30050,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30118,
"s": 30089,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 30140,
"s": 30118,
"text": "Defaultdict in Python"
}
] |
How to get median of an array of numbers in JavaScript ? - GeeksforGeeks | 22 Apr, 2021
In this article, we will see how to find the median of an array using JavaScript.
Examples:
Input arr1 : [1 4 7 9]
Output : 5.5
Explanation : The median of the two sorted array is
the middle elements which is 5 if the
arrayLength =arr1.length + arr2.length is odd
if the array length is even then it will be
the average of two number
Input: arr1 : [5 3 1 8 90]
Output: 5
Explanation : The median is average of two number
because the array.length is even for this case.
Approach: Here we first sort the array and then will find the array length. If the array length is even then median will be arr[(arr.length)/2] +arr[((arr.length)/2)+1]. If the array length is odd then the median will be a middle element.
Javascript
<script> function medianof2Arr(arr1) { var concat = arr1; concat = concat.sort( function (a, b) { return a - b }); console.log(concat); var length = concat.length; if (length % 2 == 1) { // If length is odd console.log(concat[(length / 2) - .5]) return concat[(length / 2) - .5] } else { console.log((concat[length / 2] + concat[(length / 2) - 1]) / 2); return (concat[length / 2] + concat[(length / 2) - 1]) / 2; } } arr1 = [1, 4, 7, 9] medianof2Arr(arr1)</script>
Output:
5.5
Time Complexity:
O(n + m)
Approach 2: Here we have first made the variable middle which has the middle value irrespective of length whether array length will be odd and even. Now after that we sort the array by avoiding mutation. Mutation means changing the object name with another object name or passing the object to another object called mutation.
It can be done with reference data types which are arrays, Object So For now avoid this. After that if the length of array is even then we have the two value in array at pos arr((arr.length)/2) + arr(((arr.length)/2) +1). Then take the mean of these two number and return as a median.
Javascript
<script> function median_of_arr(arr) { const middle = (arr.length + 1) / 2; // Avoid mutating when sorting const sorted = [...arr].sort((a, b) => a - b); const isEven = sorted.length % 2 === 0; return isEven ? (sorted[middle - 1.5] + sorted[middle - 0.5]) / 2 : sorted[middle - 1]; } var arr = [1, 4, 7, 9]; console.log(median_of_arr(arr)); </script>
Output:
5.5
Time Complexity:
O(n+m)
javascript-math
JavaScript-Methods
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 39215,
"s": 39187,
"text": "\n22 Apr, 2021"
},
{
"code": null,
"e": 39297,
"s": 39215,
"text": "In this article, we will see how to find the median of an array using JavaScript."
},
{
"code": null,
"e": 39307,
"s": 39297,
"text": "Examples:"
},
{
"code": null,
"e": 39770,
"s": 39307,
"text": "Input arr1 : [1 4 7 9]\nOutput : 5.5\nExplanation : The median of the two sorted array is \n the middle elements which is 5 if the \n arrayLength =arr1.length + arr2.length is odd \n if the array length is even then it will be \n the average of two number \n\nInput: arr1 : [5 3 1 8 90]\n \nOutput: 5\nExplanation : The median is average of two number \n because the array.length is even for this case."
},
{
"code": null,
"e": 40009,
"s": 39770,
"text": "Approach: Here we first sort the array and then will find the array length. If the array length is even then median will be arr[(arr.length)/2] +arr[((arr.length)/2)+1]. If the array length is odd then the median will be a middle element."
},
{
"code": null,
"e": 40020,
"s": 40009,
"text": "Javascript"
},
{
"code": "<script> function medianof2Arr(arr1) { var concat = arr1; concat = concat.sort( function (a, b) { return a - b }); console.log(concat); var length = concat.length; if (length % 2 == 1) { // If length is odd console.log(concat[(length / 2) - .5]) return concat[(length / 2) - .5] } else { console.log((concat[length / 2] + concat[(length / 2) - 1]) / 2); return (concat[length / 2] + concat[(length / 2) - 1]) / 2; } } arr1 = [1, 4, 7, 9] medianof2Arr(arr1)</script>",
"e": 40682,
"s": 40020,
"text": null
},
{
"code": null,
"e": 40690,
"s": 40682,
"text": "Output:"
},
{
"code": null,
"e": 40694,
"s": 40690,
"text": "5.5"
},
{
"code": null,
"e": 40711,
"s": 40694,
"text": "Time Complexity:"
},
{
"code": null,
"e": 40720,
"s": 40711,
"text": "O(n + m)"
},
{
"code": null,
"e": 41046,
"s": 40720,
"text": "Approach 2: Here we have first made the variable middle which has the middle value irrespective of length whether array length will be odd and even. Now after that we sort the array by avoiding mutation. Mutation means changing the object name with another object name or passing the object to another object called mutation."
},
{
"code": null,
"e": 41331,
"s": 41046,
"text": "It can be done with reference data types which are arrays, Object So For now avoid this. After that if the length of array is even then we have the two value in array at pos arr((arr.length)/2) + arr(((arr.length)/2) +1). Then take the mean of these two number and return as a median."
},
{
"code": null,
"e": 41342,
"s": 41331,
"text": "Javascript"
},
{
"code": "<script> function median_of_arr(arr) { const middle = (arr.length + 1) / 2; // Avoid mutating when sorting const sorted = [...arr].sort((a, b) => a - b); const isEven = sorted.length % 2 === 0; return isEven ? (sorted[middle - 1.5] + sorted[middle - 0.5]) / 2 : sorted[middle - 1]; } var arr = [1, 4, 7, 9]; console.log(median_of_arr(arr)); </script>",
"e": 41767,
"s": 41342,
"text": null
},
{
"code": null,
"e": 41776,
"s": 41767,
"text": "Output: "
},
{
"code": null,
"e": 41780,
"s": 41776,
"text": "5.5"
},
{
"code": null,
"e": 41797,
"s": 41780,
"text": "Time Complexity:"
},
{
"code": null,
"e": 41804,
"s": 41797,
"text": "O(n+m)"
},
{
"code": null,
"e": 41820,
"s": 41804,
"text": "javascript-math"
},
{
"code": null,
"e": 41839,
"s": 41820,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 41860,
"s": 41839,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 41867,
"s": 41860,
"text": "Picked"
},
{
"code": null,
"e": 41878,
"s": 41867,
"text": "JavaScript"
},
{
"code": null,
"e": 41895,
"s": 41878,
"text": "Web Technologies"
},
{
"code": null,
"e": 41993,
"s": 41895,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42033,
"s": 41993,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 42078,
"s": 42033,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 42139,
"s": 42078,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 42211,
"s": 42139,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 42280,
"s": 42211,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 42320,
"s": 42280,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 42353,
"s": 42320,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 42398,
"s": 42353,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 42441,
"s": 42398,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
COVID-19 Data Visualization using matplotlib in Python - GeeksforGeeks | 14 Feb, 2022
It feels surreal to imagine how the virus began to spread from one person that is patient zero to four million today. It was possible because of the transport system. Earlier back in the days, we didn’t have a fraction of the transportation system we have today.
Well, what good practices you can follow for now is to sanitize your grocery products and keep them idle for a day or two. Until we find a vaccine that could be years away from us, keeping social distance in public places is the only way to reduce the number of cases. Make sure you take vitamin C in the form of additional tablets or the form of food. Well, it’s not going to prevent you from getting corona, but at least if you get infected, your immunity is going to be stronger than the person who didn’t take it to fight the virus. The last practice is to replace your handshakes with Namaste or Wakanda Salute.
We will be going through some basic plots available in matplotlib and make it more aesthetically pleasing.
Here are the Visualizations we’ll be designing using matplotlib
Simple Plot?—?Date handling
Pie Chart
Bar Plot
Link to the datasets (CSV): Click here
Importing Dataset on Covid-19 India case time series
data = pd.read_csv('case_time_series.csv')
case_time_series.csv dataset has 7 column. We will be collecting Daily Confirmed Daily Recovered and Daily Deceased in variables as array.
Y = data.iloc[61:,1].values #Stores Daily Confirmed
R = data.iloc[61:,3].values #Stores Daily Recovered
D = data.iloc[61:,5].values #Stores Daily Deceased
X = data.iloc[61:,0] #Stores Date
‘Y’ variable stores the ‘Daily Confirmed’ corona virus cases
‘R’ variable stores the ‘Daily Recovered’ corona virus cases
‘D’ variable stores the ‘Daily Deceased’ corona virus cases
And ‘X’ variable stores the ‘Date’ column
We’ll be following the object-oriented method for plotting. The plot function takes two arguments that are X-axis values and Y-axis values plot. In this case, we will pass the ‘X’ variable which has ‘Dates’ and ‘Y’ variable which has ‘Daily Confirmed’ to plot.
Example:
Python3
import numpy as npimport pandas as pdimport matplotlib.pyplot as plt data = pd.read_csv('case_time_series.csv') Y = data.iloc[61:,1].valuesR = data.iloc[61:,3].valuesD = data.iloc[61:,5].valuesX = data.iloc[61:,0] plt.plot(X,Y)
Output:
We get a Simple Plot on the execution of above code which looks like this where X-axis has Dates and Y-axis has Number of Confirmed cases. But this is not the best representation for large dataset values along the axes as you can see the ‘Dates’ are overlapping on X-axis. To overcome this challenge we will introduce some new functions to take more control over the aesthetics of the graph.
To have control over the aesthetics of the graph such as labels, titles, color and size we shall apply more functions as shown below.
plt.figure(figsize=(25,8))
This creates a canvas for the graph where the first value ‘25’ is the width argument position and ‘8’ is the height argument position of the graph.
ax = plt.axes()
Let’s create an object of the axes of the graph as ‘ax’ so it becomes easier to implement functions.
ax.grid(linewidth=0.4, color='#8f8f8f')
‘.grid’ function lets you create grid lines across the graph. The width of the grid lines can be adjusted by simply passing an argument ‘linewidth’ and changing its color by passing ‘color’ argument.
ax.set_facecolor("black")
ax.set_xlabel('\nDate',size=25,
color='#4bb4f2')
ax.set_ylabel('Number of Confirmed Cases\n',
size=25,color='#4bb4f2')
‘.set_facecolor’ lets you set the background color of the graph which over here is black. ‘.set_xlabel’ and ‘.set_ylabel’ lets you set the label along both axes whose size and color can be altered .
ax.plot(X,Y,
color='#1F77B4',
marker='o',
linewidth=4,
markersize=15,
markeredgecolor='#035E9B')
Now we plot the graph again with ‘X’ as Dates and ‘Y’ as Daily Confirmed by calling plot function. The plotting line , marker and color can be altered by passing color, linewidth?—?to change color and adjust the width of plotting line and marker, markersize, markeredgecolor?—?to create marker which is the circle in this case, adjust the size of the marker and define marker’s edge color.
Complete Code:
Python3
import numpy as npimport pandas as pdimport matplotlib.pyplot as plt data = pd.read_csv('case_time_series.csv') Y = data.iloc[61:,1].valuesR = data.iloc[61:,3].valuesD = data.iloc[61:,5].valuesX = data.iloc[61:,0] plt.figure(figsize=(25,8)) ax = plt.axes()ax.grid(linewidth=0.4, color='#8f8f8f') ax.set_facecolor("black")ax.set_xlabel('\nDate',size=25,color='#4bb4f2')ax.set_ylabel('Number of Confirmed Cases\n', size=25,color='#4bb4f2') ax.plot(X,Y, color='#1F77B4', marker='o', linewidth=4, markersize=15, markeredgecolor='#035E9B')
Output:
Still as we can see the dates are overlapping and the labels along axes are not clear enough. So now we are going to change the ticks of the axes and also annotate the plots.
plt.xticks(rotation='vertical',size='20',color='white')
plt.yticks(size=20,color='white')
plt.tick_params(size=20,color='white')
‘.xticks’ and ‘.yticks’ lets you alter the Dates and Daily Confirmed font. For the Dates to not overlap with each other we are going to represent them vertically by passing ‘rotation = vertical’. To make the ticks easily readable we change the font color to white and size to 20.
‘.tick_params’ lets you alter the size and color of the dashes which look act like a bridge between the ticks and graph.
for i,j in zip(X,Y):
ax.annotate(str(j),xy=(i,j+100),
color='white',size='13')
‘.annotate’ lets you annotate on the graph. Over here we have written a code to annotate the plotted points by running a for loop which plots at the plotted points. The str(j) holds the ‘Y’ variable which is Daily Confirmed. Any string passed will be plotted. The XY is the coordinates where the string should be plotted. And finally the color and size can be defined. Note we have added +100 to j in XY coordinates so that the string doesn’t overlap with the marker and it is at the distance of 100 units on Y?—?axis.
ax.annotate('Second Lockdown 15th April',
xy=(15.2, 860),
xytext=(19.9,500),
color='white',
size='25',
arrowprops=dict(color='white',
linewidth=0.025))
To annotate an arrow pointing at a position in graph and its tail holding the string we can define ‘arrowprops’ argument along with its tail coordinates defined by ‘xytext’. Note that ‘arrowprops’ alteration can be done using a dictionary.
plt.title("COVID-19 IN : Daily Confirmed\n",
size=50,color='#28a9ff')
Finally we define a title by ‘.title’ and passing string ,its size and color.
Complete Code:
Python3
import numpy as npimport pandas as pdimport matplotlib.pyplot as plt data = pd.read_csv('case_time_series.csv') Y = data.iloc[61:,1].valuesR = data.iloc[61:,3].valuesD = data.iloc[61:,5].valuesX = data.iloc[61:,0] plt.figure(figsize=(25,8)) ax = plt.axes()ax.grid(linewidth=0.4, color='#8f8f8f') ax.set_facecolor("black")ax.set_xlabel('\nDate',size=25,color='#4bb4f2')ax.set_ylabel('Number of Confirmed Cases\n', size=25,color='#4bb4f2') plt.xticks(rotation='vertical',size='20',color='white')plt.yticks(size=20,color='white')plt.tick_params(size=20,color='white') for i,j in zip(X,Y): ax.annotate(str(j),xy=(i,j+100),color='white',size='13') ax.annotate('Second Lockdown 15th April', xy=(15.2, 860), xytext=(19.9,500), color='white', size='25', arrowprops=dict(color='white', linewidth=0.025)) plt.title("COVID-19 IN : Daily Confirmed\n", size=50,color='#28a9ff') ax.plot(X,Y, color='#1F77B4', marker='o', linewidth=4, markersize=15, markeredgecolor='#035E9B')
Output:
We’ll be plotting the Transmission Pie Chart to understand the how the virus is spreading based on Travel, Place Visit and Unknown reason.
slices = [62, 142, 195]
activities = ['Travel', 'Place Visit', 'Unknown']
So we have created list slices based on which our Pie Chart will be divided and the corresponding activities are it’s valued.
cols=['#4C8BE2','#00e061','#fe073a']
exp = [0.2,0.02,0.02]
plt.pie(slices,
labels=activities,
textprops=dict(size=25,color='black'),
radius=3,
colors=cols,
autopct='%2.2f%%',
explode=exp,
shadow=True,
startangle=90)
plt.title('Transmission\n\n\n\n',color='#4fb4f2',size=40)
To plot a Pie Chart we call ‘.pie’ function which takes x values which is ‘slices’ over here based on it the pie is divided followed by labels which have the corresponding string the values it represents. These string values can be altered by ‘textprops’. To change the radius or size of Pie we call ‘radius’. For the aesthetics we call ‘shadow’ as True and ‘startangle ’= 90. We can define colors to assign by passing a list of corresponding colors. To space out each piece of Pie we can pass on the list of corresponding values to ‘explode’. The ‘autopct’ defines the number of positions that are allowed to be shown. In this case, autopct allows 2 positions before and after the decimal place.
Complete Code:
Python3
slices = [62, 142, 195]activities = ['Travel', 'Place Visit', 'Unknown'] cols=['#4C8BE2','#00e061','#fe073a']exp = [0.2,0.02,0.02] plt.pie(slices,labels=activities, textprops=dict(size=25,color='black'), radius=3, colors=cols, autopct='%2.2f%%', explode=exp, shadow=True, startangle=90) plt.title('Transmission\n\n\n\n',color='#4fb4f2',size=40)
Output:
Now we are going to plot the most common type of graph which is a bar plot. Over here w will be plotting the district wise coronavirus cases for a state.
data = pd.read_csv('district.csv')
data.head()
re=data.iloc[:30,5].values
de=data.iloc[:30,4].values
co=data.iloc[:30,3].values
x=list(data.iloc[:30,0])
‘re’ stores Recovered corona patients count for all districts.
‘de’ stores Deceased corona patients count for all districts.
‘co’ stores Confirmed corona patients count for all districts.
‘x’ stored District names.
plt.figure(figsize=(25,10))
ax=plt.axes()
ax.set_facecolor('black')
ax.grid(linewidth=0.4, color='#8f8f8f')
plt.xticks(rotation='vertical',
size='20',
color='white')#ticks of X
plt.yticks(size='20',color='white')
ax.set_xlabel('\nDistrict',size=25,
color='#4bb4f2')
ax.set_ylabel('No. of cases\n',size=25,
color='#4bb4f2')
plt.tick_params(size=20,color='white')
ax.set_title('Maharashtra District wise breakdown\n',
size=50,color='#28a9ff')
The code for aesthetics will be the same as we saw in earlier plot. The Only thing that will change is calling for the bar function.
plt.bar(x,co,label='re')
plt.bar(x,re,label='re',color='green')
plt.bar(x,de,label='re',color='red')
for i,j in zip(x,co):
ax.annotate(str(int(j)),
xy=(i,j+3),
color='white',
size='15')
plt.legend(['Confirmed','Recovered','Deceased'],
fontsize=20)
To plot a bar graph we call ‘.bar’ and pass it x-axis and y-axis values. Over here we called the plot function three times for all three cases (i.e Recovered , Confirmed, Deceased) and all three values are plotted with respect to y-axis and x-axis being common for all three which is district names. As you can see we annotate only for Confirmed numbers by iterating over Confirmed cases value. Also, we have mentioned ‘.legend’ to indicate legends of the graph.
Complete Code:
Python3
data = pd.read_csv('district.csv')data.head() re=data.iloc[:30,5].valuesde=data.iloc[:30,4].valuesco=data.iloc[:30,3].valuesx=list(data.iloc[:30,0]) plt.figure(figsize=(25,10))ax=plt.axes() ax.set_facecolor('black')ax.grid(linewidth=0.4, color='#8f8f8f') plt.xticks(rotation='vertical', size='20', color='white')#ticks of X plt.yticks(size='20',color='white') ax.set_xlabel('\nDistrict',size=25, color='#4bb4f2')ax.set_ylabel('No. of cases\n',size=25, color='#4bb4f2') plt.tick_params(size=20,color='white') ax.set_title('Maharashtra District wise breakdown\n', size=50,color='#28a9ff') plt.bar(x,co,label='re')plt.bar(x,re,label='re',color='green')plt.bar(x,de,label='re',color='red') for i,j in zip(x,co): ax.annotate(str(int(j)), xy=(i,j+3), color='white', size='15') plt.legend(['Confirmed','Recovered','Deceased'], fontsize=20)
Output:
rkbhola5
sumitgumber28
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Different ways to create Pandas Dataframe | [
{
"code": null,
"e": 31572,
"s": 31544,
"text": "\n14 Feb, 2022"
},
{
"code": null,
"e": 31835,
"s": 31572,
"text": "It feels surreal to imagine how the virus began to spread from one person that is patient zero to four million today. It was possible because of the transport system. Earlier back in the days, we didn’t have a fraction of the transportation system we have today."
},
{
"code": null,
"e": 32452,
"s": 31835,
"text": "Well, what good practices you can follow for now is to sanitize your grocery products and keep them idle for a day or two. Until we find a vaccine that could be years away from us, keeping social distance in public places is the only way to reduce the number of cases. Make sure you take vitamin C in the form of additional tablets or the form of food. Well, it’s not going to prevent you from getting corona, but at least if you get infected, your immunity is going to be stronger than the person who didn’t take it to fight the virus. The last practice is to replace your handshakes with Namaste or Wakanda Salute."
},
{
"code": null,
"e": 32559,
"s": 32452,
"text": "We will be going through some basic plots available in matplotlib and make it more aesthetically pleasing."
},
{
"code": null,
"e": 32623,
"s": 32559,
"text": "Here are the Visualizations we’ll be designing using matplotlib"
},
{
"code": null,
"e": 32651,
"s": 32623,
"text": "Simple Plot?—?Date handling"
},
{
"code": null,
"e": 32661,
"s": 32651,
"text": "Pie Chart"
},
{
"code": null,
"e": 32672,
"s": 32661,
"text": "Bar Plot "
},
{
"code": null,
"e": 32711,
"s": 32672,
"text": "Link to the datasets (CSV): Click here"
},
{
"code": null,
"e": 32764,
"s": 32711,
"text": "Importing Dataset on Covid-19 India case time series"
},
{
"code": null,
"e": 32807,
"s": 32764,
"text": "data = pd.read_csv('case_time_series.csv')"
},
{
"code": null,
"e": 32947,
"s": 32807,
"text": "case_time_series.csv dataset has 7 column. We will be collecting Daily Confirmed Daily Recovered and Daily Deceased in variables as array."
},
{
"code": null,
"e": 33102,
"s": 32947,
"text": "Y = data.iloc[61:,1].values #Stores Daily Confirmed\nR = data.iloc[61:,3].values #Stores Daily Recovered\nD = data.iloc[61:,5].values #Stores Daily Deceased"
},
{
"code": null,
"e": 33136,
"s": 33102,
"text": "X = data.iloc[61:,0] #Stores Date"
},
{
"code": null,
"e": 33197,
"s": 33136,
"text": "‘Y’ variable stores the ‘Daily Confirmed’ corona virus cases"
},
{
"code": null,
"e": 33258,
"s": 33197,
"text": "‘R’ variable stores the ‘Daily Recovered’ corona virus cases"
},
{
"code": null,
"e": 33318,
"s": 33258,
"text": "‘D’ variable stores the ‘Daily Deceased’ corona virus cases"
},
{
"code": null,
"e": 33360,
"s": 33318,
"text": "And ‘X’ variable stores the ‘Date’ column"
},
{
"code": null,
"e": 33621,
"s": 33360,
"text": "We’ll be following the object-oriented method for plotting. The plot function takes two arguments that are X-axis values and Y-axis values plot. In this case, we will pass the ‘X’ variable which has ‘Dates’ and ‘Y’ variable which has ‘Daily Confirmed’ to plot."
},
{
"code": null,
"e": 33630,
"s": 33621,
"text": "Example:"
},
{
"code": null,
"e": 33638,
"s": 33630,
"text": "Python3"
},
{
"code": "import numpy as npimport pandas as pdimport matplotlib.pyplot as plt data = pd.read_csv('case_time_series.csv') Y = data.iloc[61:,1].valuesR = data.iloc[61:,3].valuesD = data.iloc[61:,5].valuesX = data.iloc[61:,0] plt.plot(X,Y)",
"e": 33867,
"s": 33638,
"text": null
},
{
"code": null,
"e": 33875,
"s": 33867,
"text": "Output:"
},
{
"code": null,
"e": 34269,
"s": 33877,
"text": "We get a Simple Plot on the execution of above code which looks like this where X-axis has Dates and Y-axis has Number of Confirmed cases. But this is not the best representation for large dataset values along the axes as you can see the ‘Dates’ are overlapping on X-axis. To overcome this challenge we will introduce some new functions to take more control over the aesthetics of the graph."
},
{
"code": null,
"e": 34403,
"s": 34269,
"text": "To have control over the aesthetics of the graph such as labels, titles, color and size we shall apply more functions as shown below."
},
{
"code": null,
"e": 34430,
"s": 34403,
"text": "plt.figure(figsize=(25,8))"
},
{
"code": null,
"e": 34578,
"s": 34430,
"text": "This creates a canvas for the graph where the first value ‘25’ is the width argument position and ‘8’ is the height argument position of the graph."
},
{
"code": null,
"e": 34594,
"s": 34578,
"text": "ax = plt.axes()"
},
{
"code": null,
"e": 34695,
"s": 34594,
"text": "Let’s create an object of the axes of the graph as ‘ax’ so it becomes easier to implement functions."
},
{
"code": null,
"e": 34736,
"s": 34695,
"text": "ax.grid(linewidth=0.4, color='#8f8f8f') "
},
{
"code": null,
"e": 34936,
"s": 34736,
"text": "‘.grid’ function lets you create grid lines across the graph. The width of the grid lines can be adjusted by simply passing an argument ‘linewidth’ and changing its color by passing ‘color’ argument."
},
{
"code": null,
"e": 35127,
"s": 34936,
"text": "ax.set_facecolor(\"black\") \n\nax.set_xlabel('\\nDate',size=25,\n color='#4bb4f2')\n \nax.set_ylabel('Number of Confirmed Cases\\n',\n size=25,color='#4bb4f2')"
},
{
"code": null,
"e": 35328,
"s": 35129,
"text": "‘.set_facecolor’ lets you set the background color of the graph which over here is black. ‘.set_xlabel’ and ‘.set_ylabel’ lets you set the label along both axes whose size and color can be altered ."
},
{
"code": null,
"e": 35465,
"s": 35328,
"text": "ax.plot(X,Y,\n color='#1F77B4',\n marker='o',\n linewidth=4,\n markersize=15,\n markeredgecolor='#035E9B')"
},
{
"code": null,
"e": 35855,
"s": 35465,
"text": "Now we plot the graph again with ‘X’ as Dates and ‘Y’ as Daily Confirmed by calling plot function. The plotting line , marker and color can be altered by passing color, linewidth?—?to change color and adjust the width of plotting line and marker, markersize, markeredgecolor?—?to create marker which is the circle in this case, adjust the size of the marker and define marker’s edge color."
},
{
"code": null,
"e": 35870,
"s": 35855,
"text": "Complete Code:"
},
{
"code": null,
"e": 35878,
"s": 35870,
"text": "Python3"
},
{
"code": "import numpy as npimport pandas as pdimport matplotlib.pyplot as plt data = pd.read_csv('case_time_series.csv') Y = data.iloc[61:,1].valuesR = data.iloc[61:,3].valuesD = data.iloc[61:,5].valuesX = data.iloc[61:,0] plt.figure(figsize=(25,8)) ax = plt.axes()ax.grid(linewidth=0.4, color='#8f8f8f') ax.set_facecolor(\"black\")ax.set_xlabel('\\nDate',size=25,color='#4bb4f2')ax.set_ylabel('Number of Confirmed Cases\\n', size=25,color='#4bb4f2') ax.plot(X,Y, color='#1F77B4', marker='o', linewidth=4, markersize=15, markeredgecolor='#035E9B')",
"e": 36461,
"s": 35878,
"text": null
},
{
"code": null,
"e": 36469,
"s": 36461,
"text": "Output:"
},
{
"code": null,
"e": 36646,
"s": 36471,
"text": "Still as we can see the dates are overlapping and the labels along axes are not clear enough. So now we are going to change the ticks of the axes and also annotate the plots."
},
{
"code": null,
"e": 36775,
"s": 36646,
"text": "plt.xticks(rotation='vertical',size='20',color='white')\nplt.yticks(size=20,color='white')\nplt.tick_params(size=20,color='white')"
},
{
"code": null,
"e": 37057,
"s": 36777,
"text": "‘.xticks’ and ‘.yticks’ lets you alter the Dates and Daily Confirmed font. For the Dates to not overlap with each other we are going to represent them vertically by passing ‘rotation = vertical’. To make the ticks easily readable we change the font color to white and size to 20."
},
{
"code": null,
"e": 37178,
"s": 37057,
"text": "‘.tick_params’ lets you alter the size and color of the dashes which look act like a bridge between the ticks and graph."
},
{
"code": null,
"e": 37277,
"s": 37178,
"text": "for i,j in zip(X,Y):\n ax.annotate(str(j),xy=(i,j+100),\n color='white',size='13')"
},
{
"code": null,
"e": 37796,
"s": 37277,
"text": "‘.annotate’ lets you annotate on the graph. Over here we have written a code to annotate the plotted points by running a for loop which plots at the plotted points. The str(j) holds the ‘Y’ variable which is Daily Confirmed. Any string passed will be plotted. The XY is the coordinates where the string should be plotted. And finally the color and size can be defined. Note we have added +100 to j in XY coordinates so that the string doesn’t overlap with the marker and it is at the distance of 100 units on Y?—?axis."
},
{
"code": null,
"e": 38036,
"s": 37796,
"text": "ax.annotate('Second Lockdown 15th April',\n xy=(15.2, 860),\n xytext=(19.9,500),\n color='white',\n size='25',\n arrowprops=dict(color='white',\n linewidth=0.025))"
},
{
"code": null,
"e": 38278,
"s": 38038,
"text": "To annotate an arrow pointing at a position in graph and its tail holding the string we can define ‘arrowprops’ argument along with its tail coordinates defined by ‘xytext’. Note that ‘arrowprops’ alteration can be done using a dictionary."
},
{
"code": null,
"e": 38358,
"s": 38278,
"text": "plt.title(\"COVID-19 IN : Daily Confirmed\\n\",\n size=50,color='#28a9ff')"
},
{
"code": null,
"e": 38436,
"s": 38358,
"text": "Finally we define a title by ‘.title’ and passing string ,its size and color."
},
{
"code": null,
"e": 38451,
"s": 38436,
"text": "Complete Code:"
},
{
"code": null,
"e": 38459,
"s": 38451,
"text": "Python3"
},
{
"code": "import numpy as npimport pandas as pdimport matplotlib.pyplot as plt data = pd.read_csv('case_time_series.csv') Y = data.iloc[61:,1].valuesR = data.iloc[61:,3].valuesD = data.iloc[61:,5].valuesX = data.iloc[61:,0] plt.figure(figsize=(25,8)) ax = plt.axes()ax.grid(linewidth=0.4, color='#8f8f8f') ax.set_facecolor(\"black\")ax.set_xlabel('\\nDate',size=25,color='#4bb4f2')ax.set_ylabel('Number of Confirmed Cases\\n', size=25,color='#4bb4f2') plt.xticks(rotation='vertical',size='20',color='white')plt.yticks(size=20,color='white')plt.tick_params(size=20,color='white') for i,j in zip(X,Y): ax.annotate(str(j),xy=(i,j+100),color='white',size='13') ax.annotate('Second Lockdown 15th April', xy=(15.2, 860), xytext=(19.9,500), color='white', size='25', arrowprops=dict(color='white', linewidth=0.025)) plt.title(\"COVID-19 IN : Daily Confirmed\\n\", size=50,color='#28a9ff') ax.plot(X,Y, color='#1F77B4', marker='o', linewidth=4, markersize=15, markeredgecolor='#035E9B')",
"e": 39567,
"s": 38459,
"text": null
},
{
"code": null,
"e": 39575,
"s": 39567,
"text": "Output:"
},
{
"code": null,
"e": 39714,
"s": 39575,
"text": "We’ll be plotting the Transmission Pie Chart to understand the how the virus is spreading based on Travel, Place Visit and Unknown reason."
},
{
"code": null,
"e": 39788,
"s": 39714,
"text": "slices = [62, 142, 195]\nactivities = ['Travel', 'Place Visit', 'Unknown']"
},
{
"code": null,
"e": 39914,
"s": 39788,
"text": "So we have created list slices based on which our Pie Chart will be divided and the corresponding activities are it’s valued."
},
{
"code": null,
"e": 39973,
"s": 39914,
"text": "cols=['#4C8BE2','#00e061','#fe073a']\nexp = [0.2,0.02,0.02]"
},
{
"code": null,
"e": 40131,
"s": 39973,
"text": "plt.pie(slices,\nlabels=activities, \ntextprops=dict(size=25,color='black'),\nradius=3,\ncolors=cols,\nautopct='%2.2f%%',\nexplode=exp,\nshadow=True,\nstartangle=90)"
},
{
"code": null,
"e": 40189,
"s": 40131,
"text": "plt.title('Transmission\\n\\n\\n\\n',color='#4fb4f2',size=40)"
},
{
"code": null,
"e": 40886,
"s": 40189,
"text": "To plot a Pie Chart we call ‘.pie’ function which takes x values which is ‘slices’ over here based on it the pie is divided followed by labels which have the corresponding string the values it represents. These string values can be altered by ‘textprops’. To change the radius or size of Pie we call ‘radius’. For the aesthetics we call ‘shadow’ as True and ‘startangle ’= 90. We can define colors to assign by passing a list of corresponding colors. To space out each piece of Pie we can pass on the list of corresponding values to ‘explode’. The ‘autopct’ defines the number of positions that are allowed to be shown. In this case, autopct allows 2 positions before and after the decimal place."
},
{
"code": null,
"e": 40901,
"s": 40886,
"text": "Complete Code:"
},
{
"code": null,
"e": 40909,
"s": 40901,
"text": "Python3"
},
{
"code": "slices = [62, 142, 195]activities = ['Travel', 'Place Visit', 'Unknown'] cols=['#4C8BE2','#00e061','#fe073a']exp = [0.2,0.02,0.02] plt.pie(slices,labels=activities, textprops=dict(size=25,color='black'), radius=3, colors=cols, autopct='%2.2f%%', explode=exp, shadow=True, startangle=90) plt.title('Transmission\\n\\n\\n\\n',color='#4fb4f2',size=40)",
"e": 41303,
"s": 40909,
"text": null
},
{
"code": null,
"e": 41311,
"s": 41303,
"text": "Output:"
},
{
"code": null,
"e": 41468,
"s": 41313,
"text": "Now we are going to plot the most common type of graph which is a bar plot. Over here w will be plotting the district wise coronavirus cases for a state. "
},
{
"code": null,
"e": 41515,
"s": 41468,
"text": "data = pd.read_csv('district.csv')\ndata.head()"
},
{
"code": null,
"e": 41621,
"s": 41515,
"text": "re=data.iloc[:30,5].values\nde=data.iloc[:30,4].values\nco=data.iloc[:30,3].values\nx=list(data.iloc[:30,0])"
},
{
"code": null,
"e": 41684,
"s": 41621,
"text": "‘re’ stores Recovered corona patients count for all districts."
},
{
"code": null,
"e": 41746,
"s": 41684,
"text": "‘de’ stores Deceased corona patients count for all districts."
},
{
"code": null,
"e": 41810,
"s": 41746,
"text": "‘co’ stores Confirmed corona patients count for all districts. "
},
{
"code": null,
"e": 41837,
"s": 41810,
"text": "‘x’ stored District names."
},
{
"code": null,
"e": 42351,
"s": 41837,
"text": "plt.figure(figsize=(25,10))\nax=plt.axes()\n\nax.set_facecolor('black')\nax.grid(linewidth=0.4, color='#8f8f8f')\n\n\nplt.xticks(rotation='vertical',\n size='20',\n color='white')#ticks of X\n\nplt.yticks(size='20',color='white')\n\n\nax.set_xlabel('\\nDistrict',size=25,\n color='#4bb4f2')\nax.set_ylabel('No. of cases\\n',size=25,\n color='#4bb4f2')\n\n\nplt.tick_params(size=20,color='white')\n\n\nax.set_title('Maharashtra District wise breakdown\\n',\n size=50,color='#28a9ff')"
},
{
"code": null,
"e": 42484,
"s": 42351,
"text": "The code for aesthetics will be the same as we saw in earlier plot. The Only thing that will change is calling for the bar function."
},
{
"code": null,
"e": 42797,
"s": 42484,
"text": "plt.bar(x,co,label='re')\nplt.bar(x,re,label='re',color='green')\nplt.bar(x,de,label='re',color='red')\n\nfor i,j in zip(x,co):\n ax.annotate(str(int(j)),\n xy=(i,j+3),\n color='white',\n size='15')\n\nplt.legend(['Confirmed','Recovered','Deceased'],\n fontsize=20)"
},
{
"code": null,
"e": 43260,
"s": 42797,
"text": "To plot a bar graph we call ‘.bar’ and pass it x-axis and y-axis values. Over here we called the plot function three times for all three cases (i.e Recovered , Confirmed, Deceased) and all three values are plotted with respect to y-axis and x-axis being common for all three which is district names. As you can see we annotate only for Confirmed numbers by iterating over Confirmed cases value. Also, we have mentioned ‘.legend’ to indicate legends of the graph."
},
{
"code": null,
"e": 43275,
"s": 43260,
"text": "Complete Code:"
},
{
"code": null,
"e": 43283,
"s": 43275,
"text": "Python3"
},
{
"code": "data = pd.read_csv('district.csv')data.head() re=data.iloc[:30,5].valuesde=data.iloc[:30,4].valuesco=data.iloc[:30,3].valuesx=list(data.iloc[:30,0]) plt.figure(figsize=(25,10))ax=plt.axes() ax.set_facecolor('black')ax.grid(linewidth=0.4, color='#8f8f8f') plt.xticks(rotation='vertical', size='20', color='white')#ticks of X plt.yticks(size='20',color='white') ax.set_xlabel('\\nDistrict',size=25, color='#4bb4f2')ax.set_ylabel('No. of cases\\n',size=25, color='#4bb4f2') plt.tick_params(size=20,color='white') ax.set_title('Maharashtra District wise breakdown\\n', size=50,color='#28a9ff') plt.bar(x,co,label='re')plt.bar(x,re,label='re',color='green')plt.bar(x,de,label='re',color='red') for i,j in zip(x,co): ax.annotate(str(int(j)), xy=(i,j+3), color='white', size='15') plt.legend(['Confirmed','Recovered','Deceased'], fontsize=20)",
"e": 44236,
"s": 43283,
"text": null
},
{
"code": null,
"e": 44244,
"s": 44236,
"text": "Output:"
},
{
"code": null,
"e": 44255,
"s": 44246,
"text": "rkbhola5"
},
{
"code": null,
"e": 44269,
"s": 44255,
"text": "sumitgumber28"
},
{
"code": null,
"e": 44287,
"s": 44269,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 44294,
"s": 44287,
"text": "Python"
},
{
"code": null,
"e": 44392,
"s": 44294,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44420,
"s": 44392,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 44470,
"s": 44420,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 44492,
"s": 44470,
"text": "Python map() function"
},
{
"code": null,
"e": 44536,
"s": 44492,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 44554,
"s": 44536,
"text": "Python Dictionary"
},
{
"code": null,
"e": 44577,
"s": 44554,
"text": "Taking input in Python"
},
{
"code": null,
"e": 44609,
"s": 44577,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 44644,
"s": 44609,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 44666,
"s": 44644,
"text": "Enumerate() in Python"
}
] |
Basics of Docker Networking - GeeksforGeeks | 31 Oct, 2020
Docker Networking allows you to create a Network of Docker Containers managed by a master node called the manager. Containers inside the Docker Network can talk to each other by sharing packets of information. In this article, we will discuss some basic commands that would help you get started with Docker Networking.
The Docker Network command is the main command that would allow you to create, manage, and configure your Docker Network. Let’s see what are the sub-commands that can be used with the Docker Network command.
sudo docker network
We will see all the Network sub-commands one by one.
The Create sub-command allows you to create a Docker Network.
sudo docker network create --driver <driver-name> <bridge-name>
Using Connect sub-command, you can connect a running Docker Container to an existing Network.
sudo docker network connect <network-name> <container-name or id>
In this example, we will connect an Ubuntu Container to the Bridge Network we created in the last step.
Using the Network Inspect command, you can find out the details of a Docker Network.
sudo docker network inspect <network-name>
You can also find the list of Containers that are connected to the Network.
To list all the Docker Networks, you can use the list sub-command.
sudo docker network ls
The disconnect sub-command can be used to remove a Container from the Network.
sudo docker network disconnect <network-name> <container-name>
You can remove a Docker Network using the rm sub-command.
sudo docker network rm <network-name>
Note that if you want to remove a network, you need to make sure that no container is currently referencing the network.
To remove all the unused Docker Networks, you can use the prune sub-command.
sudo docker network prune
Docker Container
linux
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Copying Files to and from Docker Containers
Markov Decision Process
Fuzzy Logic | Introduction
Q-Learning in Python
Principal Component Analysis with Python
Basics of API Testing Using Postman
ML | What is Machine Learning ?
OpenCV - Overview
Getting Started with System Design
Deep Learning | Introduction to Long Short Term Memory | [
{
"code": null,
"e": 25493,
"s": 25465,
"text": "\n31 Oct, 2020"
},
{
"code": null,
"e": 25812,
"s": 25493,
"text": "Docker Networking allows you to create a Network of Docker Containers managed by a master node called the manager. Containers inside the Docker Network can talk to each other by sharing packets of information. In this article, we will discuss some basic commands that would help you get started with Docker Networking."
},
{
"code": null,
"e": 26020,
"s": 25812,
"text": "The Docker Network command is the main command that would allow you to create, manage, and configure your Docker Network. Let’s see what are the sub-commands that can be used with the Docker Network command."
},
{
"code": null,
"e": 26041,
"s": 26020,
"text": "sudo docker network\n"
},
{
"code": null,
"e": 26094,
"s": 26041,
"text": "We will see all the Network sub-commands one by one."
},
{
"code": null,
"e": 26157,
"s": 26094,
"text": "The Create sub-command allows you to create a Docker Network. "
},
{
"code": null,
"e": 26222,
"s": 26157,
"text": "sudo docker network create --driver <driver-name> <bridge-name>\n"
},
{
"code": null,
"e": 26316,
"s": 26222,
"text": "Using Connect sub-command, you can connect a running Docker Container to an existing Network."
},
{
"code": null,
"e": 26383,
"s": 26316,
"text": "sudo docker network connect <network-name> <container-name or id>\n"
},
{
"code": null,
"e": 26487,
"s": 26383,
"text": "In this example, we will connect an Ubuntu Container to the Bridge Network we created in the last step."
},
{
"code": null,
"e": 26572,
"s": 26487,
"text": "Using the Network Inspect command, you can find out the details of a Docker Network."
},
{
"code": null,
"e": 26616,
"s": 26572,
"text": "sudo docker network inspect <network-name>\n"
},
{
"code": null,
"e": 26692,
"s": 26616,
"text": "You can also find the list of Containers that are connected to the Network."
},
{
"code": null,
"e": 26759,
"s": 26692,
"text": "To list all the Docker Networks, you can use the list sub-command."
},
{
"code": null,
"e": 26783,
"s": 26759,
"text": "sudo docker network ls\n"
},
{
"code": null,
"e": 26862,
"s": 26783,
"text": "The disconnect sub-command can be used to remove a Container from the Network."
},
{
"code": null,
"e": 26926,
"s": 26862,
"text": "sudo docker network disconnect <network-name> <container-name>\n"
},
{
"code": null,
"e": 26984,
"s": 26926,
"text": "You can remove a Docker Network using the rm sub-command."
},
{
"code": null,
"e": 27023,
"s": 26984,
"text": "sudo docker network rm <network-name>\n"
},
{
"code": null,
"e": 27144,
"s": 27023,
"text": "Note that if you want to remove a network, you need to make sure that no container is currently referencing the network."
},
{
"code": null,
"e": 27222,
"s": 27144,
"text": "To remove all the unused Docker Networks, you can use the prune sub-command. "
},
{
"code": null,
"e": 27249,
"s": 27222,
"text": "sudo docker network prune\n"
},
{
"code": null,
"e": 27266,
"s": 27249,
"text": "Docker Container"
},
{
"code": null,
"e": 27272,
"s": 27266,
"text": "linux"
},
{
"code": null,
"e": 27298,
"s": 27272,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 27396,
"s": 27298,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27440,
"s": 27396,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 27464,
"s": 27440,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 27491,
"s": 27464,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 27512,
"s": 27491,
"text": "Q-Learning in Python"
},
{
"code": null,
"e": 27553,
"s": 27512,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 27589,
"s": 27553,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 27621,
"s": 27589,
"text": "ML | What is Machine Learning ?"
},
{
"code": null,
"e": 27639,
"s": 27621,
"text": "OpenCV - Overview"
},
{
"code": null,
"e": 27674,
"s": 27639,
"text": "Getting Started with System Design"
}
] |
How to create Hex color generator using HTML CSS and JavaScript ? - GeeksforGeeks | 03 Feb, 2021
Hex color is a six-digit code representing the amount of red, green, and blue that makes up the color. Hex color generator gives the hex code of selected color.
Approach:
To select a color, we will use <input type=”color”> which creates a color picker.Get the value returned by color picker.(Color picker returns hex value)Set the color as background and display the hex code.
To select a color, we will use <input type=”color”> which creates a color picker.
Get the value returned by color picker.(Color picker returns hex value)
Set the color as background and display the hex code.
HTML
<!DOCTYPE html><html> <head> <title>Hex color generator</title> <style> body { margin: 0; padding: 0; display: grid; place-items: center; height: 100vh; font-size: 20px; } .main { height: 400px; width: 250px; background: #3A3A38; border-radius: 10px; display: grid; place-items: center; color: #fff; font-family: verdana; border-radius: 15px; } #colorPicker { background-color: none; outline: none; border: none; height: 40px; width: 60px; cursor: pointer; } #box { outline: none; border: 2px solid #333; border-radius: 50px; height: 40px; width: 120px; padding: 0 10px; } </style></head> <body> <h1>Hex Color Generator</h1> <div class="main"> <!-- To select the color --> Color Picker: <input type="color" id="colorPicker" value="#6a5acd"> <!-- To display hex code of the color --> Hex Code: <input type="text" id="box"> </div> <script> function myColor() { // Get the value return by color picker var color = document.getElementById('colorPicker').value; // Set the color as background document.body.style.backgroundColor = color; // Take the hex code document.getElementById('box').value = color; } // When user clicks over color picker, // myColor() function is called document.getElementById('colorPicker') .addEventListener('input', myColor); </script></body> </html>
Output:
CSS-Questions
HTML-Questions
JavaScript-Questions
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ? | [
{
"code": null,
"e": 26621,
"s": 26593,
"text": "\n03 Feb, 2021"
},
{
"code": null,
"e": 26782,
"s": 26621,
"text": "Hex color is a six-digit code representing the amount of red, green, and blue that makes up the color. Hex color generator gives the hex code of selected color."
},
{
"code": null,
"e": 26792,
"s": 26782,
"text": "Approach:"
},
{
"code": null,
"e": 26998,
"s": 26792,
"text": "To select a color, we will use <input type=”color”> which creates a color picker.Get the value returned by color picker.(Color picker returns hex value)Set the color as background and display the hex code."
},
{
"code": null,
"e": 27080,
"s": 26998,
"text": "To select a color, we will use <input type=”color”> which creates a color picker."
},
{
"code": null,
"e": 27152,
"s": 27080,
"text": "Get the value returned by color picker.(Color picker returns hex value)"
},
{
"code": null,
"e": 27206,
"s": 27152,
"text": "Set the color as background and display the hex code."
},
{
"code": null,
"e": 27211,
"s": 27206,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Hex color generator</title> <style> body { margin: 0; padding: 0; display: grid; place-items: center; height: 100vh; font-size: 20px; } .main { height: 400px; width: 250px; background: #3A3A38; border-radius: 10px; display: grid; place-items: center; color: #fff; font-family: verdana; border-radius: 15px; } #colorPicker { background-color: none; outline: none; border: none; height: 40px; width: 60px; cursor: pointer; } #box { outline: none; border: 2px solid #333; border-radius: 50px; height: 40px; width: 120px; padding: 0 10px; } </style></head> <body> <h1>Hex Color Generator</h1> <div class=\"main\"> <!-- To select the color --> Color Picker: <input type=\"color\" id=\"colorPicker\" value=\"#6a5acd\"> <!-- To display hex code of the color --> Hex Code: <input type=\"text\" id=\"box\"> </div> <script> function myColor() { // Get the value return by color picker var color = document.getElementById('colorPicker').value; // Set the color as background document.body.style.backgroundColor = color; // Take the hex code document.getElementById('box').value = color; } // When user clicks over color picker, // myColor() function is called document.getElementById('colorPicker') .addEventListener('input', myColor); </script></body> </html>",
"e": 29065,
"s": 27211,
"text": null
},
{
"code": null,
"e": 29073,
"s": 29065,
"text": "Output:"
},
{
"code": null,
"e": 29087,
"s": 29073,
"text": "CSS-Questions"
},
{
"code": null,
"e": 29102,
"s": 29087,
"text": "HTML-Questions"
},
{
"code": null,
"e": 29123,
"s": 29102,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 29127,
"s": 29123,
"text": "CSS"
},
{
"code": null,
"e": 29132,
"s": 29127,
"text": "HTML"
},
{
"code": null,
"e": 29143,
"s": 29132,
"text": "JavaScript"
},
{
"code": null,
"e": 29160,
"s": 29143,
"text": "Web Technologies"
},
{
"code": null,
"e": 29165,
"s": 29160,
"text": "HTML"
},
{
"code": null,
"e": 29263,
"s": 29165,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29302,
"s": 29263,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 29339,
"s": 29302,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29368,
"s": 29339,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29410,
"s": 29368,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 29445,
"s": 29410,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 29505,
"s": 29445,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 29558,
"s": 29505,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 29619,
"s": 29558,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 29643,
"s": 29619,
"text": "REST API (Introduction)"
}
] |
Get Enumeration Over Java ArrayList - GeeksforGeeks | 13 Jan, 2021
ArrayList class is a re-sizeable array that is present in java.util package. Unlike the built-in arrays, ArrayList can change their size dynamically where elements can be added and removed from an ArrayList.
In java version 1, enum was not present. With advancement to version, 1.5 enum was introduced in java which is not as same as seen in C/C++ so do the functionality differs. Enum is basically used to constrict the range for example moths, age, or be it a string (considering name of a company) which can not be changed as final values initially itself. In java version 1, enumeration was carried out by interfaces. After version 1.5 it was introduced in java as discussed so simply importing enum class makes working with enum easy simply by importing classes.
ArrayList can be of any type as shown below. The enumeration method of java.util.Collections class is used to return an enumeration over the specified collection.
An ArrayList of integer, string, double, etc.
ArrayList of ArrayLists, or simply an ArrayList of HashMaps.
An ArrayList of any user-defined objects.
Syntax: For declaring an enumeration
public static Enumeration enumeration(Collection c) ;
Method Used: hasMoreElements() Method
An object that implements the Enumeration interface generates a series of elements, one at a time. hasMoreElements() method of enumeration used to tests if this enumeration contains more elements. If enumeration contains more elements than it will return true else false.
Syntax:
boolean hasMoreElements() ;
Parameters: This method accepts nothing.
Return value: This method returns true if and only if this enumeration object contains at least one more element to provide; false otherwise.
Implementation:
Example 1
Java
// Getting Enumeration over Java ArrayList // Importing ArrayList,Collection and Enumeration class// from java.util packageimport java.util.ArrayList;import java.util.Collections;import java.util.Enumeration; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating object of ArrayList // String type here- shoppingList ArrayList<String> shoppingList = new ArrayList<>(); // Adding element to ArrayList // Custom inputs shoppingList.add("Perfume"); shoppingList.add("Clothes"); shoppingList.add("Sandal"); shoppingList.add("Jewellery"); shoppingList.add("Watch"); // Creating object of type Enumeration<String> Enumeration e = Collections.enumeration(shoppingList); // Condition check using hasMoreElements() method while (e.hasMoreElements()) // print the enumeration System.out.println(e.nextElement()); }}
Perfume
Clothes
Sandal
Jewellery
Watch
Example 2
Java
// Getting Enumeration over Java ArrayList // Importing ArrayList,Collection and Enumeration class// from java.util packageimport java.util.ArrayList;import java.util.Collections;import java.util.Enumeration; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating object of ArrayList<String ArrayList<String> LanguageList = new ArrayList<>(); // Adding element to LanguageList // Custom inputs LanguageList.add("Java"); LanguageList.add("C++"); LanguageList.add("Kotlin"); LanguageList.add("Scala"); LanguageList.add("Ruby"); LanguageList.add("Python"); LanguageList.add("C#"); // Creating object of type Enumeration<String> Enumeration e = Collections.enumeration(LanguageList); // Condition check using hasMoreElements() while (e.hasMoreElements()) // Print the enumeration System.out.println(e.nextElement()); }}
Java
C++
Kotlin
Scala
Ruby
Python
C#
Java-ArrayList
Java-Collections
Picked
Java
Java Programs
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
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character | [
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n13 Jan, 2021"
},
{
"code": null,
"e": 25434,
"s": 25225,
"text": "ArrayList class is a re-sizeable array that is present in java.util package. Unlike the built-in arrays, ArrayList can change their size dynamically where elements can be added and removed from an ArrayList. "
},
{
"code": null,
"e": 25994,
"s": 25434,
"text": "In java version 1, enum was not present. With advancement to version, 1.5 enum was introduced in java which is not as same as seen in C/C++ so do the functionality differs. Enum is basically used to constrict the range for example moths, age, or be it a string (considering name of a company) which can not be changed as final values initially itself. In java version 1, enumeration was carried out by interfaces. After version 1.5 it was introduced in java as discussed so simply importing enum class makes working with enum easy simply by importing classes."
},
{
"code": null,
"e": 26157,
"s": 25994,
"text": "ArrayList can be of any type as shown below. The enumeration method of java.util.Collections class is used to return an enumeration over the specified collection."
},
{
"code": null,
"e": 26203,
"s": 26157,
"text": "An ArrayList of integer, string, double, etc."
},
{
"code": null,
"e": 26264,
"s": 26203,
"text": "ArrayList of ArrayLists, or simply an ArrayList of HashMaps."
},
{
"code": null,
"e": 26306,
"s": 26264,
"text": "An ArrayList of any user-defined objects."
},
{
"code": null,
"e": 26343,
"s": 26306,
"text": "Syntax: For declaring an enumeration"
},
{
"code": null,
"e": 26398,
"s": 26343,
"text": "public static Enumeration enumeration(Collection c) ;"
},
{
"code": null,
"e": 26436,
"s": 26398,
"text": "Method Used: hasMoreElements() Method"
},
{
"code": null,
"e": 26708,
"s": 26436,
"text": "An object that implements the Enumeration interface generates a series of elements, one at a time. hasMoreElements() method of enumeration used to tests if this enumeration contains more elements. If enumeration contains more elements than it will return true else false."
},
{
"code": null,
"e": 26716,
"s": 26708,
"text": "Syntax:"
},
{
"code": null,
"e": 26744,
"s": 26716,
"text": "boolean hasMoreElements() ;"
},
{
"code": null,
"e": 26785,
"s": 26744,
"text": "Parameters: This method accepts nothing."
},
{
"code": null,
"e": 26927,
"s": 26785,
"text": "Return value: This method returns true if and only if this enumeration object contains at least one more element to provide; false otherwise."
},
{
"code": null,
"e": 26943,
"s": 26927,
"text": "Implementation:"
},
{
"code": null,
"e": 26953,
"s": 26943,
"text": "Example 1"
},
{
"code": null,
"e": 26958,
"s": 26953,
"text": "Java"
},
{
"code": "// Getting Enumeration over Java ArrayList // Importing ArrayList,Collection and Enumeration class// from java.util packageimport java.util.ArrayList;import java.util.Collections;import java.util.Enumeration; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating object of ArrayList // String type here- shoppingList ArrayList<String> shoppingList = new ArrayList<>(); // Adding element to ArrayList // Custom inputs shoppingList.add(\"Perfume\"); shoppingList.add(\"Clothes\"); shoppingList.add(\"Sandal\"); shoppingList.add(\"Jewellery\"); shoppingList.add(\"Watch\"); // Creating object of type Enumeration<String> Enumeration e = Collections.enumeration(shoppingList); // Condition check using hasMoreElements() method while (e.hasMoreElements()) // print the enumeration System.out.println(e.nextElement()); }}",
"e": 27967,
"s": 26958,
"text": null
},
{
"code": null,
"e": 28006,
"s": 27967,
"text": "Perfume\nClothes\nSandal\nJewellery\nWatch"
},
{
"code": null,
"e": 28016,
"s": 28006,
"text": "Example 2"
},
{
"code": null,
"e": 28021,
"s": 28016,
"text": "Java"
},
{
"code": "// Getting Enumeration over Java ArrayList // Importing ArrayList,Collection and Enumeration class// from java.util packageimport java.util.ArrayList;import java.util.Collections;import java.util.Enumeration; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating object of ArrayList<String ArrayList<String> LanguageList = new ArrayList<>(); // Adding element to LanguageList // Custom inputs LanguageList.add(\"Java\"); LanguageList.add(\"C++\"); LanguageList.add(\"Kotlin\"); LanguageList.add(\"Scala\"); LanguageList.add(\"Ruby\"); LanguageList.add(\"Python\"); LanguageList.add(\"C#\"); // Creating object of type Enumeration<String> Enumeration e = Collections.enumeration(LanguageList); // Condition check using hasMoreElements() while (e.hasMoreElements()) // Print the enumeration System.out.println(e.nextElement()); }}",
"e": 29052,
"s": 28021,
"text": null
},
{
"code": null,
"e": 29089,
"s": 29052,
"text": "Java\nC++\nKotlin\nScala\nRuby\nPython\nC#"
},
{
"code": null,
"e": 29104,
"s": 29089,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 29121,
"s": 29104,
"text": "Java-Collections"
},
{
"code": null,
"e": 29128,
"s": 29121,
"text": "Picked"
},
{
"code": null,
"e": 29133,
"s": 29128,
"text": "Java"
},
{
"code": null,
"e": 29147,
"s": 29133,
"text": "Java Programs"
},
{
"code": null,
"e": 29152,
"s": 29147,
"text": "Java"
},
{
"code": null,
"e": 29169,
"s": 29152,
"text": "Java-Collections"
},
{
"code": null,
"e": 29267,
"s": 29169,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29282,
"s": 29267,
"text": "Stream In Java"
},
{
"code": null,
"e": 29303,
"s": 29282,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29322,
"s": 29303,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29352,
"s": 29322,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29398,
"s": 29352,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29424,
"s": 29398,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 29458,
"s": 29424,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 29505,
"s": 29458,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 29537,
"s": 29505,
"text": "How to Iterate HashMap in Java?"
}
] |
Check if alphabetical order sum of given strings are equal or not - GeeksforGeeks | 06 Jan, 2022
Given two strings s1 and s2, the task is to check if the alphabetical order sum of characters of two given strings are equal or notExamples:
Input: s1= “geek”, s2=”abcdefg”Output: TrueExplanation: Alphabetical order sum of characters of both the strings are:
s1= 7+5+5+11 = 28
s2= 1+2+3+4+5+6+7 = 28
Input: s1= “bad”, s2=”good”Output: False
Approach: The task can be solved by finding the alphabetical order sum of characters by simply iterating over the string. For each character, add the ASCII value of the current character + 1 in the resultant answer.
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 check if both strings have the// same alphabetical order sum of charactersbool findTheSum(string s1, string s2){ int sum1 = 0; int sum2 = 0; int n = s1.length(); int m = s2.length(); // Add value of char in sum1 for (int i = 0; i < n; i++) { sum1 += s1[i] - 'a' + 1; } // Add value of char in sum2 for (int i = 0; i < m; i++) { sum2 += s2[i] - 'a' + 1; } // Check sum1 are equal to sum2 or not if (sum1 == sum2) { return true; } else { return false; }} // Driver Codeint main(){ string s1 = "geek"; string s2 = "abcdefg"; cout << (findTheSum(s1, s2) ? "True" : "False"); return 0;}
// Java code to implement above approachimport java.util.*;public class GFG { // Function to check if both strings have the // same alphabetical order sum of characters static boolean findTheSum(String s1, String s2) { int sum1 = 0; int sum2 = 0; int n = s1.length(); int m = s2.length(); // Add value of char in sum1 for (int i = 0; i < n; i++) { sum1 += s1.charAt(i) - 'a' + 1; } // Add value of char in sum2 for (int i = 0; i < m; i++) { sum2 += s2.charAt(i) - 'a' + 1; } // Check sum1 are equal to sum2 or not if (sum1 == sum2) { return true; } else { return false; } } // Driver code public static void main(String args[]) { String s1 = "geek"; String s2 = "abcdefg"; System.out.println((findTheSum(s1, s2) ? "True" : "False")); }} // This code is contributed by Samim Hossain Mondal.
# Python code for the above approach # Function to check if both strings have the# same alphabetical order sum of charactersdef findTheSum(s1, s2): sum1 = 0 sum2 = 0 n = len(s1) m = len(s2) # Add value of char in sum1 for i in range(n): sum1 += ord(s1[i]) - ord('a') + 1 # Add value of char in sum2 for i in range(m): sum2 += ord(s2[i]) - ord('a') + 1 # Check sum1 are equal to sum2 or not if (sum1 == sum2): return 1 else: return 0 # Driver Codes1 = "geek"s2 = "abcdefg"if findTheSum(s1, s2) == 1: print("True")else: print("False") # This code is contributed by Potta Lokesh
// C# code to implement above approachusing System;public class GFG { // Function to check if both strings have the // same alphabetical order sum of characters static bool findTheSum(String s1, String s2) { int sum1 = 0; int sum2 = 0; int n = s1.Length; int m = s2.Length; // Add value of char in sum1 for (int i = 0; i < n; i++) { sum1 += s1[i] - 'a' + 1; } // Add value of char in sum2 for (int i = 0; i < m; i++) { sum2 += s2[i] - 'a' + 1; } // Check sum1 are equal to sum2 or not if (sum1 == sum2) { return true; } else { return false; } } // Driver code public static void Main(String []args) { String s1 = "geek"; String s2 = "abcdefg"; Console.WriteLine((findTheSum(s1, s2) ? "True" : "False")); }} // This code is contributed by shikhasingrajput
<script> // JavaScript program for the above approach // Function to check if both strings have the // same alphabetical order sum of characters const findTheSum = (s1, s2) => { let sum1 = 0; let sum2 = 0; let n = s1.length; let m = s2.length; // Add value of char in sum1 for (let i = 0; i < n; i++) { sum1 += s1.charCodeAt(i) - 'a'.charCodeAt(0) + 1; } // Add value of char in sum2 for (let i = 0; i < m; i++) { sum2 += s2.charCodeAt(i) - 'a'.charCodeAt(0) + 1; } // Check sum1 are equal to sum2 or not if (sum1 == sum2) { return true; } else { return false; } } // Driver Code let s1 = "geek"; let s2 = "abcdefg"; if (findTheSum(s1, s2)) document.write("True"); else document.write("False"); // This code is contributed by rakeshsahni </script>
True
Time Complexity: O(N)Auxiliary Space: O(1)
rakeshsahni
samim2000
shikhasingrajput
lokeshpotta20
School Programming
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Constructors in Java
Exceptions in Java
Data Types
Inline Functions in C++
Pure Virtual Functions and Abstract Classes in C++
Write a program to reverse an array or string
Write a program to print all permutations of a given string
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack
KMP Algorithm for Pattern Searching | [
{
"code": null,
"e": 25464,
"s": 25436,
"text": "\n06 Jan, 2022"
},
{
"code": null,
"e": 25605,
"s": 25464,
"text": "Given two strings s1 and s2, the task is to check if the alphabetical order sum of characters of two given strings are equal or notExamples:"
},
{
"code": null,
"e": 25724,
"s": 25605,
"text": "Input: s1= “geek”, s2=”abcdefg”Output: TrueExplanation: Alphabetical order sum of characters of both the strings are:"
},
{
"code": null,
"e": 25742,
"s": 25724,
"text": "s1= 7+5+5+11 = 28"
},
{
"code": null,
"e": 25766,
"s": 25742,
"text": "s2= 1+2+3+4+5+6+7 = 28 "
},
{
"code": null,
"e": 25807,
"s": 25766,
"text": "Input: s1= “bad”, s2=”good”Output: False"
},
{
"code": null,
"e": 26023,
"s": 25807,
"text": "Approach: The task can be solved by finding the alphabetical order sum of characters by simply iterating over the string. For each character, add the ASCII value of the current character + 1 in the resultant answer."
},
{
"code": null,
"e": 26074,
"s": 26023,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26078,
"s": 26074,
"text": "C++"
},
{
"code": null,
"e": 26083,
"s": 26078,
"text": "Java"
},
{
"code": null,
"e": 26091,
"s": 26083,
"text": "Python3"
},
{
"code": null,
"e": 26094,
"s": 26091,
"text": "C#"
},
{
"code": null,
"e": 26105,
"s": 26094,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if both strings have the// same alphabetical order sum of charactersbool findTheSum(string s1, string s2){ int sum1 = 0; int sum2 = 0; int n = s1.length(); int m = s2.length(); // Add value of char in sum1 for (int i = 0; i < n; i++) { sum1 += s1[i] - 'a' + 1; } // Add value of char in sum2 for (int i = 0; i < m; i++) { sum2 += s2[i] - 'a' + 1; } // Check sum1 are equal to sum2 or not if (sum1 == sum2) { return true; } else { return false; }} // Driver Codeint main(){ string s1 = \"geek\"; string s2 = \"abcdefg\"; cout << (findTheSum(s1, s2) ? \"True\" : \"False\"); return 0;}",
"e": 26873,
"s": 26105,
"text": null
},
{
"code": "// Java code to implement above approachimport java.util.*;public class GFG { // Function to check if both strings have the // same alphabetical order sum of characters static boolean findTheSum(String s1, String s2) { int sum1 = 0; int sum2 = 0; int n = s1.length(); int m = s2.length(); // Add value of char in sum1 for (int i = 0; i < n; i++) { sum1 += s1.charAt(i) - 'a' + 1; } // Add value of char in sum2 for (int i = 0; i < m; i++) { sum2 += s2.charAt(i) - 'a' + 1; } // Check sum1 are equal to sum2 or not if (sum1 == sum2) { return true; } else { return false; } } // Driver code public static void main(String args[]) { String s1 = \"geek\"; String s2 = \"abcdefg\"; System.out.println((findTheSum(s1, s2) ? \"True\" : \"False\")); }} // This code is contributed by Samim Hossain Mondal.",
"e": 27752,
"s": 26873,
"text": null
},
{
"code": "# Python code for the above approach # Function to check if both strings have the# same alphabetical order sum of charactersdef findTheSum(s1, s2): sum1 = 0 sum2 = 0 n = len(s1) m = len(s2) # Add value of char in sum1 for i in range(n): sum1 += ord(s1[i]) - ord('a') + 1 # Add value of char in sum2 for i in range(m): sum2 += ord(s2[i]) - ord('a') + 1 # Check sum1 are equal to sum2 or not if (sum1 == sum2): return 1 else: return 0 # Driver Codes1 = \"geek\"s2 = \"abcdefg\"if findTheSum(s1, s2) == 1: print(\"True\")else: print(\"False\") # This code is contributed by Potta Lokesh",
"e": 28399,
"s": 27752,
"text": null
},
{
"code": "// C# code to implement above approachusing System;public class GFG { // Function to check if both strings have the // same alphabetical order sum of characters static bool findTheSum(String s1, String s2) { int sum1 = 0; int sum2 = 0; int n = s1.Length; int m = s2.Length; // Add value of char in sum1 for (int i = 0; i < n; i++) { sum1 += s1[i] - 'a' + 1; } // Add value of char in sum2 for (int i = 0; i < m; i++) { sum2 += s2[i] - 'a' + 1; } // Check sum1 are equal to sum2 or not if (sum1 == sum2) { return true; } else { return false; } } // Driver code public static void Main(String []args) { String s1 = \"geek\"; String s2 = \"abcdefg\"; Console.WriteLine((findTheSum(s1, s2) ? \"True\" : \"False\")); }} // This code is contributed by shikhasingrajput",
"e": 29242,
"s": 28399,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to check if both strings have the // same alphabetical order sum of characters const findTheSum = (s1, s2) => { let sum1 = 0; let sum2 = 0; let n = s1.length; let m = s2.length; // Add value of char in sum1 for (let i = 0; i < n; i++) { sum1 += s1.charCodeAt(i) - 'a'.charCodeAt(0) + 1; } // Add value of char in sum2 for (let i = 0; i < m; i++) { sum2 += s2.charCodeAt(i) - 'a'.charCodeAt(0) + 1; } // Check sum1 are equal to sum2 or not if (sum1 == sum2) { return true; } else { return false; } } // Driver Code let s1 = \"geek\"; let s2 = \"abcdefg\"; if (findTheSum(s1, s2)) document.write(\"True\"); else document.write(\"False\"); // This code is contributed by rakeshsahni </script>",
"e": 30179,
"s": 29242,
"text": null
},
{
"code": null,
"e": 30187,
"s": 30182,
"text": "True"
},
{
"code": null,
"e": 30233,
"s": 30189,
"text": "Time Complexity: O(N)Auxiliary Space: O(1) "
},
{
"code": null,
"e": 30245,
"s": 30233,
"text": "rakeshsahni"
},
{
"code": null,
"e": 30255,
"s": 30245,
"text": "samim2000"
},
{
"code": null,
"e": 30272,
"s": 30255,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 30286,
"s": 30272,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 30305,
"s": 30286,
"text": "School Programming"
},
{
"code": null,
"e": 30313,
"s": 30305,
"text": "Strings"
},
{
"code": null,
"e": 30321,
"s": 30313,
"text": "Strings"
},
{
"code": null,
"e": 30419,
"s": 30321,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30440,
"s": 30419,
"text": "Constructors in Java"
},
{
"code": null,
"e": 30459,
"s": 30440,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 30470,
"s": 30459,
"text": "Data Types"
},
{
"code": null,
"e": 30494,
"s": 30470,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 30545,
"s": 30494,
"text": "Pure Virtual Functions and Abstract Classes in C++"
},
{
"code": null,
"e": 30591,
"s": 30545,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 30651,
"s": 30591,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 30685,
"s": 30651,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 30760,
"s": 30685,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
] |
How to Remove All Directories and Files in Golang? - GeeksforGeeks | 23 Mar, 2020
In Go language, you are allowed to remove all the directories and files from a directory or folder with the help of RemoveAll() function. This function removes all the directories and files from the path you will pass to this function. It will remove everything from the specified path, but returns the first error it encounters. If the specified path does not exist, then this method returns nil. If this method throws an error, then it will be of type *PathError. It is defined under the os package so, you have to import os package in your program for accessing RemoveAll() function.
Syntax:
func RemoveAll(path string) error
Example 1:
// Golang program to illustrate how to // remove all the files and directories// from the default directorypackage main import ( "log" "os") func main() { // Remove all the directories and files // Using RemoveAll() function err := os.RemoveAll("/Users/anki/Documents/go") if err != nil { log.Fatal(err) }}
Output:
Before:
After:
Example 2:
// Golang program to illustrate how to remove// all the files and directories from the// new directorypackage main import ( "log" "os") func main() { // Remove all the directories and files // Using RemoveAll() function err := os.RemoveAll("/Users/anki/Documents/new_folder/files") if err != nil { log.Fatal(err) }}
Output:
Before:
After:
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
strings.Replace() Function in Golang With Examples
Arrays in Go
fmt.Sprintf() Function in Golang With Examples
How to Split a String in Golang?
Slices in Golang
Golang Maps
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
Interfaces in Golang | [
{
"code": null,
"e": 25466,
"s": 25438,
"text": "\n23 Mar, 2020"
},
{
"code": null,
"e": 26053,
"s": 25466,
"text": "In Go language, you are allowed to remove all the directories and files from a directory or folder with the help of RemoveAll() function. This function removes all the directories and files from the path you will pass to this function. It will remove everything from the specified path, but returns the first error it encounters. If the specified path does not exist, then this method returns nil. If this method throws an error, then it will be of type *PathError. It is defined under the os package so, you have to import os package in your program for accessing RemoveAll() function."
},
{
"code": null,
"e": 26061,
"s": 26053,
"text": "Syntax:"
},
{
"code": null,
"e": 26095,
"s": 26061,
"text": "func RemoveAll(path string) error"
},
{
"code": null,
"e": 26106,
"s": 26095,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate how to // remove all the files and directories// from the default directorypackage main import ( \"log\" \"os\") func main() { // Remove all the directories and files // Using RemoveAll() function err := os.RemoveAll(\"/Users/anki/Documents/go\") if err != nil { log.Fatal(err) }}",
"e": 26445,
"s": 26106,
"text": null
},
{
"code": null,
"e": 26453,
"s": 26445,
"text": "Output:"
},
{
"code": null,
"e": 26461,
"s": 26453,
"text": "Before:"
},
{
"code": null,
"e": 26468,
"s": 26461,
"text": "After:"
},
{
"code": null,
"e": 26479,
"s": 26468,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate how to remove// all the files and directories from the// new directorypackage main import ( \"log\" \"os\") func main() { // Remove all the directories and files // Using RemoveAll() function err := os.RemoveAll(\"/Users/anki/Documents/new_folder/files\") if err != nil { log.Fatal(err) }}",
"e": 26827,
"s": 26479,
"text": null
},
{
"code": null,
"e": 26835,
"s": 26827,
"text": "Output:"
},
{
"code": null,
"e": 26843,
"s": 26835,
"text": "Before:"
},
{
"code": null,
"e": 26850,
"s": 26843,
"text": "After:"
},
{
"code": null,
"e": 26862,
"s": 26850,
"text": "Go Language"
},
{
"code": null,
"e": 26960,
"s": 26862,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27006,
"s": 26960,
"text": "6 Best Books to Learn Go Programming Language"
},
{
"code": null,
"e": 27057,
"s": 27006,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 27070,
"s": 27057,
"text": "Arrays in Go"
},
{
"code": null,
"e": 27117,
"s": 27070,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 27150,
"s": 27117,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 27167,
"s": 27150,
"text": "Slices in Golang"
},
{
"code": null,
"e": 27179,
"s": 27167,
"text": "Golang Maps"
},
{
"code": null,
"e": 27201,
"s": 27179,
"text": "Inheritance in GoLang"
},
{
"code": null,
"e": 27255,
"s": 27201,
"text": "Different Ways to Find the Type of Variable in Golang"
}
] |
Sapient Interview Experience - GeeksforGeeks | 31 Oct, 2019
Sapient was hiring for Java Developer/Microservice. The best part is that they provide pick up and drop service.
Round 1 Telephonic Round: MCQs based questions by HR on Core Java
Round 2 Case Study Round: A problem statement will be given and we have to make a microservice API using our tech stack in 120 min. You can ask for more time. I have to write JUnit test cases also. No internet is provided and have to use eclipse IDE. It’s not an elimination round
Round 3 F2F (technical discussion):
Introduce yourselfWhat all technologies have you used and whyMany questions around your current projectImmutable class and objectSingleton PatternFactory PatternMultithreadingSynchronizedWhat are triggers?When to use them?SQL Trigger | Student DatabaseWhat is Indexing and how to use indexing with composite keysHashMap internal workingDifference between synchronized Hashmap and Concurrent HashmapHow to compare a HashMap with object Student: Use Comparator class Comparator Interface in Java with ExamplesQuestions on static methodsLambda functionPredicates in Java8 ( Interview also wanted to ask Java 9 question but I have not used it so informed him the same)Default methodMarker interfaceFunctional InterfaceMethod overloading and overridingIf we have a parent class implementing a Serialize method and child class doesn’t want to serialize what will you do ( Read case 3 from this link: Object Serialization with Inheritance in Java)What will be the output of the below program:public class ABC{
public static test(){SOP("Hello");}
public class Check{
ABC obj=null;
obj.test();
}Maven vs Ant vs GradleJunit test cases and tell me about some Mocking framework(Mockito)Spring bean cycleHibernate CachingJenkins based questionsWhat is dockerLinux commands
Introduce yourself
What all technologies have you used and why
Many questions around your current projectImmutable class and objectSingleton PatternFactory PatternMultithreadingSynchronized
Immutable class and object
Singleton Pattern
Factory Pattern
Multithreading
Synchronized
What are triggers?
When to use them?
SQL Trigger | Student Database
What is Indexing and how to use indexing with composite keys
HashMap internal working
Difference between synchronized Hashmap and Concurrent Hashmap
How to compare a HashMap with object Student: Use Comparator class Comparator Interface in Java with Examples
Questions on static methods
Lambda function
Predicates in Java8 ( Interview also wanted to ask Java 9 question but I have not used it so informed him the same)
Default method
Marker interface
Functional Interface
Method overloading and overriding
If we have a parent class implementing a Serialize method and child class doesn’t want to serialize what will you do ( Read case 3 from this link: Object Serialization with Inheritance in Java)
What will be the output of the below program:public class ABC{
public static test(){SOP("Hello");}
public class Check{
ABC obj=null;
obj.test();
}
public class ABC{
public static test(){SOP("Hello");}
public class Check{
ABC obj=null;
obj.test();
}
Maven vs Ant vs Gradle
Junit test cases and tell me about some Mocking framework(Mockito)
Spring bean cycle
Hibernate Caching
Jenkins based questions
What is docker
Linux commands
Combine score of round 2 and 3 results in going to round 4
Round 4 Physcometry Test: It was a Thomas Cook based psychometric test
Round 5 HR Round:
Salary expectation discussions
Marketing
Sapient
Interview Experiences
Sapient
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (Off-Campus)
Amazon AWS Interview Experience for SDE-1
Difference between ANN, CNN and RNN
Amazon Interview Experience for SDE-1 (Off-Campus) 2022
Amazon Interview Experience
Amazon Interview Experience for SDE-1
Amazon Interview Experience (Off-Campus) 2022
EPAM Interview Experience (Off-Campus)
Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)
JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021 | [
{
"code": null,
"e": 26369,
"s": 26341,
"text": "\n31 Oct, 2019"
},
{
"code": null,
"e": 26482,
"s": 26369,
"text": "Sapient was hiring for Java Developer/Microservice. The best part is that they provide pick up and drop service."
},
{
"code": null,
"e": 26548,
"s": 26482,
"text": "Round 1 Telephonic Round: MCQs based questions by HR on Core Java"
},
{
"code": null,
"e": 26829,
"s": 26548,
"text": "Round 2 Case Study Round: A problem statement will be given and we have to make a microservice API using our tech stack in 120 min. You can ask for more time. I have to write JUnit test cases also. No internet is provided and have to use eclipse IDE. It’s not an elimination round"
},
{
"code": null,
"e": 26865,
"s": 26829,
"text": "Round 3 F2F (technical discussion):"
},
{
"code": null,
"e": 28127,
"s": 26865,
"text": "Introduce yourselfWhat all technologies have you used and whyMany questions around your current projectImmutable class and objectSingleton PatternFactory PatternMultithreadingSynchronizedWhat are triggers?When to use them?SQL Trigger | Student DatabaseWhat is Indexing and how to use indexing with composite keysHashMap internal workingDifference between synchronized Hashmap and Concurrent HashmapHow to compare a HashMap with object Student: Use Comparator class Comparator Interface in Java with ExamplesQuestions on static methodsLambda functionPredicates in Java8 ( Interview also wanted to ask Java 9 question but I have not used it so informed him the same)Default methodMarker interfaceFunctional InterfaceMethod overloading and overridingIf we have a parent class implementing a Serialize method and child class doesn’t want to serialize what will you do ( Read case 3 from this link: Object Serialization with Inheritance in Java)What will be the output of the below program:public class ABC{ \npublic static test(){SOP(\"Hello\");}\npublic class Check{\nABC obj=null;\nobj.test();\n}Maven vs Ant vs GradleJunit test cases and tell me about some Mocking framework(Mockito)Spring bean cycleHibernate CachingJenkins based questionsWhat is dockerLinux commands"
},
{
"code": null,
"e": 28146,
"s": 28127,
"text": "Introduce yourself"
},
{
"code": null,
"e": 28190,
"s": 28146,
"text": "What all technologies have you used and why"
},
{
"code": null,
"e": 28317,
"s": 28190,
"text": "Many questions around your current projectImmutable class and objectSingleton PatternFactory PatternMultithreadingSynchronized"
},
{
"code": null,
"e": 28344,
"s": 28317,
"text": "Immutable class and object"
},
{
"code": null,
"e": 28362,
"s": 28344,
"text": "Singleton Pattern"
},
{
"code": null,
"e": 28378,
"s": 28362,
"text": "Factory Pattern"
},
{
"code": null,
"e": 28393,
"s": 28378,
"text": "Multithreading"
},
{
"code": null,
"e": 28406,
"s": 28393,
"text": "Synchronized"
},
{
"code": null,
"e": 28425,
"s": 28406,
"text": "What are triggers?"
},
{
"code": null,
"e": 28443,
"s": 28425,
"text": "When to use them?"
},
{
"code": null,
"e": 28474,
"s": 28443,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 28536,
"s": 28474,
"text": "What is Indexing and how to use indexing with composite keys"
},
{
"code": null,
"e": 28561,
"s": 28536,
"text": "HashMap internal working"
},
{
"code": null,
"e": 28624,
"s": 28561,
"text": "Difference between synchronized Hashmap and Concurrent Hashmap"
},
{
"code": null,
"e": 28734,
"s": 28624,
"text": "How to compare a HashMap with object Student: Use Comparator class Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 28762,
"s": 28734,
"text": "Questions on static methods"
},
{
"code": null,
"e": 28778,
"s": 28762,
"text": "Lambda function"
},
{
"code": null,
"e": 28894,
"s": 28778,
"text": "Predicates in Java8 ( Interview also wanted to ask Java 9 question but I have not used it so informed him the same)"
},
{
"code": null,
"e": 28909,
"s": 28894,
"text": "Default method"
},
{
"code": null,
"e": 28926,
"s": 28909,
"text": "Marker interface"
},
{
"code": null,
"e": 28947,
"s": 28926,
"text": "Functional Interface"
},
{
"code": null,
"e": 28981,
"s": 28947,
"text": "Method overloading and overriding"
},
{
"code": null,
"e": 29175,
"s": 28981,
"text": "If we have a parent class implementing a Serialize method and child class doesn’t want to serialize what will you do ( Read case 3 from this link: Object Serialization with Inheritance in Java)"
},
{
"code": null,
"e": 29323,
"s": 29175,
"text": "What will be the output of the below program:public class ABC{ \npublic static test(){SOP(\"Hello\");}\npublic class Check{\nABC obj=null;\nobj.test();\n}"
},
{
"code": null,
"e": 29426,
"s": 29323,
"text": "public class ABC{ \npublic static test(){SOP(\"Hello\");}\npublic class Check{\nABC obj=null;\nobj.test();\n}"
},
{
"code": null,
"e": 29449,
"s": 29426,
"text": "Maven vs Ant vs Gradle"
},
{
"code": null,
"e": 29516,
"s": 29449,
"text": "Junit test cases and tell me about some Mocking framework(Mockito)"
},
{
"code": null,
"e": 29534,
"s": 29516,
"text": "Spring bean cycle"
},
{
"code": null,
"e": 29552,
"s": 29534,
"text": "Hibernate Caching"
},
{
"code": null,
"e": 29576,
"s": 29552,
"text": "Jenkins based questions"
},
{
"code": null,
"e": 29591,
"s": 29576,
"text": "What is docker"
},
{
"code": null,
"e": 29606,
"s": 29591,
"text": "Linux commands"
},
{
"code": null,
"e": 29665,
"s": 29606,
"text": "Combine score of round 2 and 3 results in going to round 4"
},
{
"code": null,
"e": 29736,
"s": 29665,
"text": "Round 4 Physcometry Test: It was a Thomas Cook based psychometric test"
},
{
"code": null,
"e": 29754,
"s": 29736,
"text": "Round 5 HR Round:"
},
{
"code": null,
"e": 29785,
"s": 29754,
"text": "Salary expectation discussions"
},
{
"code": null,
"e": 29795,
"s": 29785,
"text": "Marketing"
},
{
"code": null,
"e": 29803,
"s": 29795,
"text": "Sapient"
},
{
"code": null,
"e": 29825,
"s": 29803,
"text": "Interview Experiences"
},
{
"code": null,
"e": 29833,
"s": 29825,
"text": "Sapient"
},
{
"code": null,
"e": 29931,
"s": 29833,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29982,
"s": 29931,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus)"
},
{
"code": null,
"e": 30024,
"s": 29982,
"text": "Amazon AWS Interview Experience for SDE-1"
},
{
"code": null,
"e": 30060,
"s": 30024,
"text": "Difference between ANN, CNN and RNN"
},
{
"code": null,
"e": 30116,
"s": 30060,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus) 2022"
},
{
"code": null,
"e": 30144,
"s": 30116,
"text": "Amazon Interview Experience"
},
{
"code": null,
"e": 30182,
"s": 30144,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 30228,
"s": 30182,
"text": "Amazon Interview Experience (Off-Campus) 2022"
},
{
"code": null,
"e": 30267,
"s": 30228,
"text": "EPAM Interview Experience (Off-Campus)"
},
{
"code": null,
"e": 30344,
"s": 30267,
"text": "Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)"
}
] |
How to pass/access node.js variable to an html file/template ? - GeeksforGeeks | 07 Apr, 2021
The following approach covers how to pass/access node.js variable to an HTML file/template. We will build a basic Node.js application that will let you show dynamic content on an HTML page, i.e. your name and age. For adding the name and age values to our HTML template, we’ll be using the pug package.
Pug is a template engine that can be used to inject dynamic data into an HTML page. Its function is to convert the provided data into HTML content and serve it as a static page. Pug’s syntax resembles that of traditional HTML but is a lot cleaner and prioritizes indentation and spacing for controlling the flow of logic.
Creating NodeJS Application And Installing Module:
Step 1: We can create a new project with Node Package Manager by using the following command.npm init
Step 1: We can create a new project with Node Package Manager by using the following command.
npm init
Step 2: Install the required project dependencies i.e express and pug modules using the following command.npm install express pug --save
Step 2: Install the required project dependencies i.e express and pug modules using the following command.
npm install express pug --save
By default, all HTML templates are stored in the views folder in a project. We’ll create the template file index.pug using the same structure.
Project Directory: Our project directory will look like this.
Project Structure
index.js
const express = require('express'); // Initialize Appconst app = express(); // Assign routeapp.use('/', (req, res, next) => { res.render('index.pug', { name: 'John Doe', age: 21 });}); // Start serverapp.listen(5000, () => { console.log('App listening on port 5000');});
Explanation: The above code it split into 3 sections:
Importing express and initializing its instanceCreating a route that will serve the HTML template and also pass data into it (name and age of a user).Starting the server.
Importing express and initializing its instance
Creating a route that will serve the HTML template and also pass data into it (name and age of a user).
Starting the server.
index.pug
doctype htmlhtml(lang="en") head title= 'Node.js Template' body h1 My name is #{name} p I am #{age} years old
Explanation: Behind the scenes, the above pub code along with the provided data is translated into an HTML page and then served via the Node.js application.
Step to run the application:
Run the index.js file using the following command.
node index.js
Output: Now open your browser and go to http://localhost:5000/, you will see the following output:
Visual Representation of index.pug template
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js Export Module
How to connect Node.js with React.js ?
Mongoose find() Function
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26267,
"s": 26239,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 26571,
"s": 26267,
"text": "The following approach covers how to pass/access node.js variable to an HTML file/template. We will build a basic Node.js application that will let you show dynamic content on an HTML page, i.e. your name and age. For adding the name and age values to our HTML template, we’ll be using the pug package. "
},
{
"code": null,
"e": 26894,
"s": 26571,
"text": "Pug is a template engine that can be used to inject dynamic data into an HTML page. Its function is to convert the provided data into HTML content and serve it as a static page. Pug’s syntax resembles that of traditional HTML but is a lot cleaner and prioritizes indentation and spacing for controlling the flow of logic. "
},
{
"code": null,
"e": 26945,
"s": 26894,
"text": "Creating NodeJS Application And Installing Module:"
},
{
"code": null,
"e": 27047,
"s": 26945,
"text": "Step 1: We can create a new project with Node Package Manager by using the following command.npm init"
},
{
"code": null,
"e": 27141,
"s": 27047,
"text": "Step 1: We can create a new project with Node Package Manager by using the following command."
},
{
"code": null,
"e": 27150,
"s": 27141,
"text": "npm init"
},
{
"code": null,
"e": 27287,
"s": 27150,
"text": "Step 2: Install the required project dependencies i.e express and pug modules using the following command.npm install express pug --save"
},
{
"code": null,
"e": 27394,
"s": 27287,
"text": "Step 2: Install the required project dependencies i.e express and pug modules using the following command."
},
{
"code": null,
"e": 27425,
"s": 27394,
"text": "npm install express pug --save"
},
{
"code": null,
"e": 27568,
"s": 27425,
"text": "By default, all HTML templates are stored in the views folder in a project. We’ll create the template file index.pug using the same structure."
},
{
"code": null,
"e": 27630,
"s": 27568,
"text": "Project Directory: Our project directory will look like this."
},
{
"code": null,
"e": 27648,
"s": 27630,
"text": "Project Structure"
},
{
"code": null,
"e": 27657,
"s": 27648,
"text": "index.js"
},
{
"code": "const express = require('express'); // Initialize Appconst app = express(); // Assign routeapp.use('/', (req, res, next) => { res.render('index.pug', { name: 'John Doe', age: 21 });}); // Start serverapp.listen(5000, () => { console.log('App listening on port 5000');});",
"e": 27933,
"s": 27657,
"text": null
},
{
"code": null,
"e": 27987,
"s": 27933,
"text": "Explanation: The above code it split into 3 sections:"
},
{
"code": null,
"e": 28158,
"s": 27987,
"text": "Importing express and initializing its instanceCreating a route that will serve the HTML template and also pass data into it (name and age of a user).Starting the server."
},
{
"code": null,
"e": 28206,
"s": 28158,
"text": "Importing express and initializing its instance"
},
{
"code": null,
"e": 28310,
"s": 28206,
"text": "Creating a route that will serve the HTML template and also pass data into it (name and age of a user)."
},
{
"code": null,
"e": 28331,
"s": 28310,
"text": "Starting the server."
},
{
"code": null,
"e": 28341,
"s": 28331,
"text": "index.pug"
},
{
"code": "doctype htmlhtml(lang=\"en\") head title= 'Node.js Template' body h1 My name is #{name} p I am #{age} years old",
"e": 28462,
"s": 28341,
"text": null
},
{
"code": null,
"e": 28619,
"s": 28462,
"text": "Explanation: Behind the scenes, the above pub code along with the provided data is translated into an HTML page and then served via the Node.js application."
},
{
"code": null,
"e": 28648,
"s": 28619,
"text": "Step to run the application:"
},
{
"code": null,
"e": 28699,
"s": 28648,
"text": "Run the index.js file using the following command."
},
{
"code": null,
"e": 28713,
"s": 28699,
"text": "node index.js"
},
{
"code": null,
"e": 28812,
"s": 28713,
"text": "Output: Now open your browser and go to http://localhost:5000/, you will see the following output:"
},
{
"code": null,
"e": 28856,
"s": 28812,
"text": "Visual Representation of index.pug template"
},
{
"code": null,
"e": 28873,
"s": 28856,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 28880,
"s": 28873,
"text": "Picked"
},
{
"code": null,
"e": 28888,
"s": 28880,
"text": "Node.js"
},
{
"code": null,
"e": 28905,
"s": 28888,
"text": "Web Technologies"
},
{
"code": null,
"e": 29003,
"s": 28905,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29025,
"s": 29003,
"text": "Node.js Export Module"
},
{
"code": null,
"e": 29064,
"s": 29025,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 29089,
"s": 29064,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 29159,
"s": 29089,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 29186,
"s": 29159,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 29226,
"s": 29186,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29271,
"s": 29226,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29314,
"s": 29271,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29376,
"s": 29314,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Java Swing | JWindow with examples - GeeksforGeeks | 06 Jun, 2018
JWindow is a part of Java Swing and it can appear on any part of the users desktop. It is different from JFrame in the respect that JWindow does not have a title bar or window management buttons like minimize, maximize, and close, which JFrame has. JWindow can contain several components such as buttons and labels.Constructor of the class are:
JWindow() : creates an empty Window without any specified ownerJWindow(Frame o) :creates an empty Window with a specified frame as its ownerJWindow(Frame o) : creates an empty Window with a specified frame as its ownerJWindow(Window o) : creates an empty Window with a specified window as its ownerJWindow(Window o, GraphicsConfiguration g) : creates an empty window with a specified window as its owner and specified graphics Configuration.JWindow(GraphicsConfiguration g) :creates an empty window with a specified Graphics Configuration g.
JWindow() : creates an empty Window without any specified owner
JWindow(Frame o) :creates an empty Window with a specified frame as its owner
JWindow(Frame o) : creates an empty Window with a specified frame as its owner
JWindow(Window o) : creates an empty Window with a specified window as its owner
JWindow(Window o, GraphicsConfiguration g) : creates an empty window with a specified window as its owner and specified graphics Configuration.
JWindow(GraphicsConfiguration g) :creates an empty window with a specified Graphics Configuration g.
Commonly used methods
setLayout(LayoutManager m) : sets the layout of the Window to specified layout managersetContentPane(Container c) : sets the ContentPane property of the windowgetContentPane() : get the container which is the ContentPane for this Windowadd(Component c): adds component to the WindowisVisible(boolean b): sets the visibility of the Window, if value of the boolean is true then visible else invisibleupdate(Graphics g) : calls the paint(g) functionremove(Component c) : removes the component cgetGraphics() : returns the graphics context of the component.getLayeredPane() : returns the layered pane for the windowsetContentPane(Container c) :sets the content pane for the windowsetLayeredPane(JLayeredPane l) : set the layered pane for the windowsetRootPane(JRootPane r) : sets the rootPane for the windowsetTransferHandler(TransferHandler n) : Sets the transferHandler property, which is a mechanism to support transfer of data into this component.setRootPaneCheckingEnabled(boolean enabled) : Sets whether calls to add and setLayout are forwarded to the contentPane.setRootPane(JRootPane root) :Sets the rootPane property of the window.setGlassPane(Component glass) : Sets the glassPane property of the window.repaint(long time, int x, int y, int width, int height): Repaints the specified rectangle of this component within time milliseconds.remove(Component c): Removes the specified component from the window.isRootPaneCheckingEnabled() : Returns whether calls to add and setLayout are forwarded to the contentPane or not .getTransferHandler() : returns the transferHandler property.getRootPane() : Returns the rootPane object for this window.getGlassPane() : Returns the glassPane object for this window.createRootPane() : Called by the constructor methods to create the default rootPane.addImpl(Component co, Object c, int i) : Adds the specified child Component to the window.
setLayout(LayoutManager m) : sets the layout of the Window to specified layout manager
setContentPane(Container c) : sets the ContentPane property of the window
getContentPane() : get the container which is the ContentPane for this Window
add(Component c): adds component to the Window
isVisible(boolean b): sets the visibility of the Window, if value of the boolean is true then visible else invisible
update(Graphics g) : calls the paint(g) function
remove(Component c) : removes the component c
getGraphics() : returns the graphics context of the component.
getLayeredPane() : returns the layered pane for the window
setContentPane(Container c) :sets the content pane for the window
setLayeredPane(JLayeredPane l) : set the layered pane for the window
setRootPane(JRootPane r) : sets the rootPane for the window
setTransferHandler(TransferHandler n) : Sets the transferHandler property, which is a mechanism to support transfer of data into this component.
setRootPaneCheckingEnabled(boolean enabled) : Sets whether calls to add and setLayout are forwarded to the contentPane.
setRootPane(JRootPane root) :Sets the rootPane property of the window.
setGlassPane(Component glass) : Sets the glassPane property of the window.
repaint(long time, int x, int y, int width, int height): Repaints the specified rectangle of this component within time milliseconds.
remove(Component c): Removes the specified component from the window.
isRootPaneCheckingEnabled() : Returns whether calls to add and setLayout are forwarded to the contentPane or not .
getTransferHandler() : returns the transferHandler property.
getRootPane() : Returns the rootPane object for this window.
getGlassPane() : Returns the glassPane object for this window.
createRootPane() : Called by the constructor methods to create the default rootPane.
addImpl(Component co, Object c, int i) : Adds the specified child Component to the window.
The following programs will illustrate the use of JWindow
1. program to create a simple JWindow
// java Program to create a simple JWindowimport java.awt.event.*;import java.awt.*;import javax.swing.*; class solveit extends JFrame implements ActionListener { // frame static JFrame f; // main class public static void main(String[] args) { // create a new frame f = new JFrame("frame"); // create a object solveit s = new solveit(); // create a panel JPanel p = new JPanel(); JButton b = new JButton("click"); // add actionlistener to button b.addActionListener(s); // add button to panel p.add(b); f.add(p); // set the size of frame f.setSize(400, 400); f.show(); } // if button is pressed public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals("click")) { // create a window JWindow w = new JWindow(f); // set panel JPanel p = new JPanel(); // create a label JLabel l = new JLabel("this is a window"); // set border p.setBorder(BorderFactory.createLineBorder(Color.black)); p.add(l); w.add(p); // set background p.setBackground(Color.red); // setsize of window w.setSize(200, 100); // set visibility of window w.setVisible(true); // set location of window w.setLocation(100, 100); } }}
Output :
1. program to create a multiple JWindow .( where one window is the owner of the other )
// java program to create a multiple JWindow .( where one window is the owner of the other )<import java.awt.event.*;import java.awt.*;import javax.swing.*;class solveit extends JFrame implements ActionListener { // frame static JFrame f; // windows JWindow w, w1; // object of class static solveit s; // main class public static void main(String[] args) { // create a new frame f = new JFrame("frame"); // create a object s = new solveit(); // create a panel JPanel p = new JPanel(); JButton b = new JButton("click"); // add actionlistener to button b.addActionListener(s); // add button to panel p.add(b); f.add(p); // set the size of frame f.setSize(400, 400); f.show(); } // if button is pressed public void actionPerformed(ActionEvent e) { String s1 = e.getActionCommand(); if (s1.equals("click")) { // create a window w = new JWindow(f); // set panel JPanel p = new JPanel(); // create a label JLabel l = new JLabel("this is first window"); // create a button JButton b = new JButton("Click me"); // add Action listener b.addActionListener(s); // set border p.setBorder(BorderFactory.createLineBorder(Color.black)); p.add(l); p.add(b); w.add(p); // set background p.setBackground(Color.red); // setsize of window w.setSize(200, 100); // set visibility of window w.setVisible(true); // set location of window w.setLocation(100, 100); } else { // create a window w1 = new JWindow(w); // set panel JPanel p = new JPanel(); // create a label JLabel l = new JLabel("this is the second window"); // set border p.setBorder(BorderFactory.createLineBorder(Color.black)); p.add(l); w1.add(p); // set background p.setBackground(Color.blue); // setsize of window w1.setSize(200, 100); // set visibility of window w1.setVisible(true); // set location of window w1.setLocation(210, 210); } }}
Output :
Note : the above programs might nor run in an online compiler please use an offline IDE
java-swing
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": "\n06 Jun, 2018"
},
{
"code": null,
"e": 25570,
"s": 25225,
"text": "JWindow is a part of Java Swing and it can appear on any part of the users desktop. It is different from JFrame in the respect that JWindow does not have a title bar or window management buttons like minimize, maximize, and close, which JFrame has. JWindow can contain several components such as buttons and labels.Constructor of the class are:"
},
{
"code": null,
"e": 26112,
"s": 25570,
"text": "JWindow() : creates an empty Window without any specified ownerJWindow(Frame o) :creates an empty Window with a specified frame as its ownerJWindow(Frame o) : creates an empty Window with a specified frame as its ownerJWindow(Window o) : creates an empty Window with a specified window as its ownerJWindow(Window o, GraphicsConfiguration g) : creates an empty window with a specified window as its owner and specified graphics Configuration.JWindow(GraphicsConfiguration g) :creates an empty window with a specified Graphics Configuration g."
},
{
"code": null,
"e": 26176,
"s": 26112,
"text": "JWindow() : creates an empty Window without any specified owner"
},
{
"code": null,
"e": 26254,
"s": 26176,
"text": "JWindow(Frame o) :creates an empty Window with a specified frame as its owner"
},
{
"code": null,
"e": 26333,
"s": 26254,
"text": "JWindow(Frame o) : creates an empty Window with a specified frame as its owner"
},
{
"code": null,
"e": 26414,
"s": 26333,
"text": "JWindow(Window o) : creates an empty Window with a specified window as its owner"
},
{
"code": null,
"e": 26558,
"s": 26414,
"text": "JWindow(Window o, GraphicsConfiguration g) : creates an empty window with a specified window as its owner and specified graphics Configuration."
},
{
"code": null,
"e": 26659,
"s": 26558,
"text": "JWindow(GraphicsConfiguration g) :creates an empty window with a specified Graphics Configuration g."
},
{
"code": null,
"e": 26681,
"s": 26659,
"text": "Commonly used methods"
},
{
"code": null,
"e": 28564,
"s": 26681,
"text": "setLayout(LayoutManager m) : sets the layout of the Window to specified layout managersetContentPane(Container c) : sets the ContentPane property of the windowgetContentPane() : get the container which is the ContentPane for this Windowadd(Component c): adds component to the WindowisVisible(boolean b): sets the visibility of the Window, if value of the boolean is true then visible else invisibleupdate(Graphics g) : calls the paint(g) functionremove(Component c) : removes the component cgetGraphics() : returns the graphics context of the component.getLayeredPane() : returns the layered pane for the windowsetContentPane(Container c) :sets the content pane for the windowsetLayeredPane(JLayeredPane l) : set the layered pane for the windowsetRootPane(JRootPane r) : sets the rootPane for the windowsetTransferHandler(TransferHandler n) : Sets the transferHandler property, which is a mechanism to support transfer of data into this component.setRootPaneCheckingEnabled(boolean enabled) : Sets whether calls to add and setLayout are forwarded to the contentPane.setRootPane(JRootPane root) :Sets the rootPane property of the window.setGlassPane(Component glass) : Sets the glassPane property of the window.repaint(long time, int x, int y, int width, int height): Repaints the specified rectangle of this component within time milliseconds.remove(Component c): Removes the specified component from the window.isRootPaneCheckingEnabled() : Returns whether calls to add and setLayout are forwarded to the contentPane or not .getTransferHandler() : returns the transferHandler property.getRootPane() : Returns the rootPane object for this window.getGlassPane() : Returns the glassPane object for this window.createRootPane() : Called by the constructor methods to create the default rootPane.addImpl(Component co, Object c, int i) : Adds the specified child Component to the window."
},
{
"code": null,
"e": 28651,
"s": 28564,
"text": "setLayout(LayoutManager m) : sets the layout of the Window to specified layout manager"
},
{
"code": null,
"e": 28725,
"s": 28651,
"text": "setContentPane(Container c) : sets the ContentPane property of the window"
},
{
"code": null,
"e": 28803,
"s": 28725,
"text": "getContentPane() : get the container which is the ContentPane for this Window"
},
{
"code": null,
"e": 28850,
"s": 28803,
"text": "add(Component c): adds component to the Window"
},
{
"code": null,
"e": 28967,
"s": 28850,
"text": "isVisible(boolean b): sets the visibility of the Window, if value of the boolean is true then visible else invisible"
},
{
"code": null,
"e": 29016,
"s": 28967,
"text": "update(Graphics g) : calls the paint(g) function"
},
{
"code": null,
"e": 29062,
"s": 29016,
"text": "remove(Component c) : removes the component c"
},
{
"code": null,
"e": 29125,
"s": 29062,
"text": "getGraphics() : returns the graphics context of the component."
},
{
"code": null,
"e": 29184,
"s": 29125,
"text": "getLayeredPane() : returns the layered pane for the window"
},
{
"code": null,
"e": 29250,
"s": 29184,
"text": "setContentPane(Container c) :sets the content pane for the window"
},
{
"code": null,
"e": 29319,
"s": 29250,
"text": "setLayeredPane(JLayeredPane l) : set the layered pane for the window"
},
{
"code": null,
"e": 29379,
"s": 29319,
"text": "setRootPane(JRootPane r) : sets the rootPane for the window"
},
{
"code": null,
"e": 29524,
"s": 29379,
"text": "setTransferHandler(TransferHandler n) : Sets the transferHandler property, which is a mechanism to support transfer of data into this component."
},
{
"code": null,
"e": 29644,
"s": 29524,
"text": "setRootPaneCheckingEnabled(boolean enabled) : Sets whether calls to add and setLayout are forwarded to the contentPane."
},
{
"code": null,
"e": 29715,
"s": 29644,
"text": "setRootPane(JRootPane root) :Sets the rootPane property of the window."
},
{
"code": null,
"e": 29790,
"s": 29715,
"text": "setGlassPane(Component glass) : Sets the glassPane property of the window."
},
{
"code": null,
"e": 29924,
"s": 29790,
"text": "repaint(long time, int x, int y, int width, int height): Repaints the specified rectangle of this component within time milliseconds."
},
{
"code": null,
"e": 29994,
"s": 29924,
"text": "remove(Component c): Removes the specified component from the window."
},
{
"code": null,
"e": 30109,
"s": 29994,
"text": "isRootPaneCheckingEnabled() : Returns whether calls to add and setLayout are forwarded to the contentPane or not ."
},
{
"code": null,
"e": 30170,
"s": 30109,
"text": "getTransferHandler() : returns the transferHandler property."
},
{
"code": null,
"e": 30231,
"s": 30170,
"text": "getRootPane() : Returns the rootPane object for this window."
},
{
"code": null,
"e": 30294,
"s": 30231,
"text": "getGlassPane() : Returns the glassPane object for this window."
},
{
"code": null,
"e": 30379,
"s": 30294,
"text": "createRootPane() : Called by the constructor methods to create the default rootPane."
},
{
"code": null,
"e": 30470,
"s": 30379,
"text": "addImpl(Component co, Object c, int i) : Adds the specified child Component to the window."
},
{
"code": null,
"e": 30528,
"s": 30470,
"text": "The following programs will illustrate the use of JWindow"
},
{
"code": null,
"e": 30566,
"s": 30528,
"text": "1. program to create a simple JWindow"
},
{
"code": "// java Program to create a simple JWindowimport java.awt.event.*;import java.awt.*;import javax.swing.*; class solveit extends JFrame implements ActionListener { // frame static JFrame f; // main class public static void main(String[] args) { // create a new frame f = new JFrame(\"frame\"); // create a object solveit s = new solveit(); // create a panel JPanel p = new JPanel(); JButton b = new JButton(\"click\"); // add actionlistener to button b.addActionListener(s); // add button to panel p.add(b); f.add(p); // set the size of frame f.setSize(400, 400); f.show(); } // if button is pressed public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals(\"click\")) { // create a window JWindow w = new JWindow(f); // set panel JPanel p = new JPanel(); // create a label JLabel l = new JLabel(\"this is a window\"); // set border p.setBorder(BorderFactory.createLineBorder(Color.black)); p.add(l); w.add(p); // set background p.setBackground(Color.red); // setsize of window w.setSize(200, 100); // set visibility of window w.setVisible(true); // set location of window w.setLocation(100, 100); } }}",
"e": 32089,
"s": 30566,
"text": null
},
{
"code": null,
"e": 32098,
"s": 32089,
"text": "Output :"
},
{
"code": null,
"e": 32186,
"s": 32098,
"text": "1. program to create a multiple JWindow .( where one window is the owner of the other )"
},
{
"code": "// java program to create a multiple JWindow .( where one window is the owner of the other )<import java.awt.event.*;import java.awt.*;import javax.swing.*;class solveit extends JFrame implements ActionListener { // frame static JFrame f; // windows JWindow w, w1; // object of class static solveit s; // main class public static void main(String[] args) { // create a new frame f = new JFrame(\"frame\"); // create a object s = new solveit(); // create a panel JPanel p = new JPanel(); JButton b = new JButton(\"click\"); // add actionlistener to button b.addActionListener(s); // add button to panel p.add(b); f.add(p); // set the size of frame f.setSize(400, 400); f.show(); } // if button is pressed public void actionPerformed(ActionEvent e) { String s1 = e.getActionCommand(); if (s1.equals(\"click\")) { // create a window w = new JWindow(f); // set panel JPanel p = new JPanel(); // create a label JLabel l = new JLabel(\"this is first window\"); // create a button JButton b = new JButton(\"Click me\"); // add Action listener b.addActionListener(s); // set border p.setBorder(BorderFactory.createLineBorder(Color.black)); p.add(l); p.add(b); w.add(p); // set background p.setBackground(Color.red); // setsize of window w.setSize(200, 100); // set visibility of window w.setVisible(true); // set location of window w.setLocation(100, 100); } else { // create a window w1 = new JWindow(w); // set panel JPanel p = new JPanel(); // create a label JLabel l = new JLabel(\"this is the second window\"); // set border p.setBorder(BorderFactory.createLineBorder(Color.black)); p.add(l); w1.add(p); // set background p.setBackground(Color.blue); // setsize of window w1.setSize(200, 100); // set visibility of window w1.setVisible(true); // set location of window w1.setLocation(210, 210); } }}",
"e": 34669,
"s": 32186,
"text": null
},
{
"code": null,
"e": 34678,
"s": 34669,
"text": "Output :"
},
{
"code": null,
"e": 34766,
"s": 34678,
"text": "Note : the above programs might nor run in an online compiler please use an offline IDE"
},
{
"code": null,
"e": 34777,
"s": 34766,
"text": "java-swing"
},
{
"code": null,
"e": 34782,
"s": 34777,
"text": "Java"
},
{
"code": null,
"e": 34787,
"s": 34782,
"text": "Java"
},
{
"code": null,
"e": 34885,
"s": 34787,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34900,
"s": 34885,
"text": "Stream In Java"
},
{
"code": null,
"e": 34921,
"s": 34900,
"text": "Constructors in Java"
},
{
"code": null,
"e": 34940,
"s": 34921,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 34970,
"s": 34940,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 35016,
"s": 34970,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 35033,
"s": 35016,
"text": "Generics in Java"
},
{
"code": null,
"e": 35054,
"s": 35033,
"text": "Introduction to Java"
},
{
"code": null,
"e": 35090,
"s": 35054,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 35133,
"s": 35090,
"text": "Comparator Interface in Java with Examples"
}
] |
Find the number of pairs (a, b) such that a % b = K - GeeksforGeeks | 25 May, 2021
Given two integers N and K where N, K > 0, the task is to find the total number of pairs (a, b) where 1 ≤ a, b ≤ N such that a % b = K.Examples:
Input: N = 4, K = 2 Output: 2 Only valid pairs are (2, 3) and (2, 4).Input: N = 11, K = 5 Output: 7
Naive approach: Run two loop from 1 to n and count all the pairs (i, j) where i % j = K. The time complexity of this approach will be O(n2).Efficient approach: Initially total count = N – K because all the numbers from the range which are > K will give K as the remainder after dividing it. After that, for all i > K there are exactly (N – K) / i numbers which will give remainder as K after getting divided by i.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count// of required pairsint CountAllPairs(int N, int K){ int count = 0; if (N > K) { // Initial count count = N - K; for (int i = K + 1; i <= N; i++) count = count + ((N - K) / i); } return count;} // Driver codeint main(){ int N = 11, K = 5; cout << CountAllPairs(N, K); return 0;}
// Java implementation of the approachimport java.io.*;class GFG { // Function to return the count // of required pairs static int CountAllPairs(int N, int K) { int count = 0; if (N > K) { // Initial count count = N - K; for (int i = K + 1; i <= N; i++) count = count + ((N - K) / i); } return count; } // Driver code public static void main(String[] args) { int N = 11, K = 5; System.out.println(CountAllPairs(N, K)); }}
# Python3 implementation of the approachimport math # Function to return the count# of required pairsdef CountAllPairs(N, K): count = 0 if( N > K): # Initial count count = N - K for i in range(K + 1, N + 1): count = count + ((N - K) // i) return count # Driver codeN = 11K = 5print(CountAllPairs(N, K))
// C# implementation of the approachusing System;class GFG { // Function to return the count // of required pairs static int CountAllPairs(int N, int K) { int count = 0; if (N > K) { // Initial count count = N - K; for (int i = K + 1; i <= N; i++) count = count + ((N - K) / i); } return count; } // Driver code public static void Main() { int N = 11, K = 5; Console.WriteLine(CountAllPairs(N, K)); }}
<?php// PHP implementation of the approach // Function to return the count// of required pairsfunction CountAllPairs($N, $K){ $count = 0; if( $N > $K){ // Initial count $count = $N - $K; for($i = $K+1; $i <= $N ; $i++) { $x = ((($N - $K) / $i)); $count = $count + (int)($x); } } return $count;} // Driver code $N = 11; $K = 5; echo(CountAllPairs($N, $K)); ?>
<script> // JavaScript implementation of the approach // Function to return the count // of required pairs function CountAllPairs( N, K) { let count = 0; if (N > K) { // Initial count count = N - K; for (let i = K + 1; i <= N; i++) count = count + parseInt((N - K) / i); } return count; } // Driver code let N = 11, K = 5; document.write(CountAllPairs(N, K)); //contributed by sravan (171fa07058) </script>
7
sravankumar8128
Algorithms
Arrays
Arrays
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
Difference between Algorithm, Pseudocode and Program
K means Clustering - Introduction
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
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": 25941,
"s": 25913,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 26088,
"s": 25941,
"text": "Given two integers N and K where N, K > 0, the task is to find the total number of pairs (a, b) where 1 ≤ a, b ≤ N such that a % b = K.Examples: "
},
{
"code": null,
"e": 26190,
"s": 26088,
"text": "Input: N = 4, K = 2 Output: 2 Only valid pairs are (2, 3) and (2, 4).Input: N = 11, K = 5 Output: 7 "
},
{
"code": null,
"e": 26657,
"s": 26192,
"text": "Naive approach: Run two loop from 1 to n and count all the pairs (i, j) where i % j = K. The time complexity of this approach will be O(n2).Efficient approach: Initially total count = N – K because all the numbers from the range which are > K will give K as the remainder after dividing it. After that, for all i > K there are exactly (N – K) / i numbers which will give remainder as K after getting divided by i.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26661,
"s": 26657,
"text": "C++"
},
{
"code": null,
"e": 26666,
"s": 26661,
"text": "Java"
},
{
"code": null,
"e": 26674,
"s": 26666,
"text": "Python3"
},
{
"code": null,
"e": 26677,
"s": 26674,
"text": "C#"
},
{
"code": null,
"e": 26681,
"s": 26677,
"text": "PHP"
},
{
"code": null,
"e": 26692,
"s": 26681,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count// of required pairsint CountAllPairs(int N, int K){ int count = 0; if (N > K) { // Initial count count = N - K; for (int i = K + 1; i <= N; i++) count = count + ((N - K) / i); } return count;} // Driver codeint main(){ int N = 11, K = 5; cout << CountAllPairs(N, K); return 0;}",
"e": 27143,
"s": 26692,
"text": null
},
{
"code": "// Java implementation of the approachimport java.io.*;class GFG { // Function to return the count // of required pairs static int CountAllPairs(int N, int K) { int count = 0; if (N > K) { // Initial count count = N - K; for (int i = K + 1; i <= N; i++) count = count + ((N - K) / i); } return count; } // Driver code public static void main(String[] args) { int N = 11, K = 5; System.out.println(CountAllPairs(N, K)); }}",
"e": 27688,
"s": 27143,
"text": null
},
{
"code": "# Python3 implementation of the approachimport math # Function to return the count# of required pairsdef CountAllPairs(N, K): count = 0 if( N > K): # Initial count count = N - K for i in range(K + 1, N + 1): count = count + ((N - K) // i) return count # Driver codeN = 11K = 5print(CountAllPairs(N, K))",
"e": 28058,
"s": 27688,
"text": null
},
{
"code": "// C# implementation of the approachusing System;class GFG { // Function to return the count // of required pairs static int CountAllPairs(int N, int K) { int count = 0; if (N > K) { // Initial count count = N - K; for (int i = K + 1; i <= N; i++) count = count + ((N - K) / i); } return count; } // Driver code public static void Main() { int N = 11, K = 5; Console.WriteLine(CountAllPairs(N, K)); }}",
"e": 28583,
"s": 28058,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to return the count// of required pairsfunction CountAllPairs($N, $K){ $count = 0; if( $N > $K){ // Initial count $count = $N - $K; for($i = $K+1; $i <= $N ; $i++) { $x = ((($N - $K) / $i)); $count = $count + (int)($x); } } return $count;} // Driver code $N = 11; $K = 5; echo(CountAllPairs($N, $K)); ?>",
"e": 29047,
"s": 28583,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function to return the count // of required pairs function CountAllPairs( N, K) { let count = 0; if (N > K) { // Initial count count = N - K; for (let i = K + 1; i <= N; i++) count = count + parseInt((N - K) / i); } return count; } // Driver code let N = 11, K = 5; document.write(CountAllPairs(N, K)); //contributed by sravan (171fa07058) </script>",
"e": 29579,
"s": 29047,
"text": null
},
{
"code": null,
"e": 29581,
"s": 29579,
"text": "7"
},
{
"code": null,
"e": 29599,
"s": 29583,
"text": "sravankumar8128"
},
{
"code": null,
"e": 29610,
"s": 29599,
"text": "Algorithms"
},
{
"code": null,
"e": 29617,
"s": 29610,
"text": "Arrays"
},
{
"code": null,
"e": 29624,
"s": 29617,
"text": "Arrays"
},
{
"code": null,
"e": 29635,
"s": 29624,
"text": "Algorithms"
},
{
"code": null,
"e": 29733,
"s": 29635,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29758,
"s": 29733,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 29785,
"s": 29758,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 29838,
"s": 29785,
"text": "Difference between Algorithm, Pseudocode and Program"
},
{
"code": null,
"e": 29872,
"s": 29838,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 29939,
"s": 29872,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 29954,
"s": 29939,
"text": "Arrays in Java"
},
{
"code": null,
"e": 29970,
"s": 29954,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 30038,
"s": 29970,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 30084,
"s": 30038,
"text": "Write a program to reverse an array or string"
}
] |
Longest subarray in which absolute difference between any two element is not greater than X | 30 Jun, 2022
Given an integer array arr[] of size N and an integer X, the task is to find the longest sub-array where the absolute difference between any two elements is not greater than X. Examples:
Input: arr = { 8, 4, 2, 6, 7 }, X = 4 Output: 4 2 6 Explanation: The sub-array described by index [1, 3], i.e, { 4, 2, 6 } contains no such difference of two elements which is greater than 4.Input: arr = { 15, 10, 1, 2, 4, 7, 2}, X = 5 Output: 2 4 7 2 Explanation: The sub-array described by indexes [3, 6], i.e, { 2, 4, 7, 2 } contains no such difference of two elements which is greater than 5.
Naive Approach: Simple solution is to consider all subarrays one by one, find the maximum and minimum element of that sub-array and check if their difference is not greater than X. Among all such sub-arrays print the longest sub-array.Time Complexity: O(N3)Efficient Approach: The idea is to use the Sliding Window Technique to consider a sub-array and use a Map data structure to find the maximum and minimum element in that sub-array.
At first the Start and End of the window points to the 0-th index.
At every iteration, the element at End is inserted in the Map if not already present or otherwise its count is incremented.
If the difference between the maximum and minimum element is not greater than X, then update the maximum length of the required sub-array and store the beginning of that sub-array in a variable.
Otherwise, increment the Start of the window until the difference between the maximum and minimum element is not greater than X.
When incrementing the Start, the size of the window decreases, remove the element at the Start from the Map if and only if the count of that element becomes zero.
Finally, print the sub-array with the longest length, and the absolute difference between any two elements is not greater than the X.Below is the implementation of the above approach:
C++
Java
Python3
Javascript
// C++ program to find the longest sub-array// where the absolute difference between any// two elements is not greater than X #include <bits/stdc++.h>using namespace std; // Function that prints the longest sub-array// where the absolute difference between any// two element is not greater than Xvoid longestSubarray(int* A, int N, int X){ // Initialize a variable to store // length of longest sub-array int maxLen = 0; // Initialize a variable to store the // beginning of the longest sub-array int beginning = 0; // Initialize a map to store the maximum // and the minimum elements for a given window map<int, int> window; // Initialize the window int start = 0, end = 0; // Loop through the array for (; end < N; end++) { // Increment the count of that // element in the window window[A[end]]++; // Find the maximum and minimum element // in the current window auto minimum = window.begin()->first; auto maximum = window.rbegin()->first; // If the difference is not // greater than X if (maximum - minimum <= X) { // Update the length of the longest // sub-array and store the beginning // of the sub-array if (maxLen < end - start + 1) { maxLen = end - start + 1; beginning = start; } } // Decrease the size of the window else { while (start < end) { // Remove the element at start window[A[start]]--; // Remove the element from the window // if its count is zero if (window[A[start]] == 0) { window.erase(window.find(A[start])); } // Increment the start of the window start++; // Find the maximum and minimum element // in the current window auto minimum = window.begin()->first; auto maximum = window.rbegin()->first; // Stop decreasing the size of window // when difference is not greater if (maximum - minimum <= X) break; } } } // Print the longest sub-array for (int i = beginning; i < beginning + maxLen; i++) cout << A[i] << " ";} // Driver Codeint main(){ int arr[] = { 15, 10, 1, 2, 4, 7, 2 }, X = 5; int n = sizeof(arr) / sizeof(arr[0]); longestSubarray(arr, n, X); return 0;}
// JAVA program to find the longest sub-array// where the absolute difference between any// two elements is not greater than Ximport java.io.*;import java.lang.*;import java.util.*;class GFG{ // Function that prints the longest sub-array // where the absolute difference between any // two element is not greater than X static void longestSubarray(int A[], int N, int X) { // Initialize a variable to store // length of longest sub-array int maxLen = 0; // Initialize a variable to store the // beginning of the longest sub-array int beginning = 0; // Initialize a map to store the maximum // and the minimum elements for a given window TreeMap<Integer, Integer> window = new TreeMap<>(); // Initialize the window int start = 0, end = 0; // Loop through the array for (; end < N; end++) { // Increment the count of that // element in the window window.put(A[end], window.getOrDefault(A[end], 0) + 1); // Find the maximum and minimum element // in the current window int minimum = window.firstKey(); int maximum = window.lastKey(); // If the difference is not // greater than X if (maximum - minimum <= X) { // Update the length of the longest // sub-array and store the beginning // of the sub-array if (maxLen < end - start + 1) { maxLen = end - start + 1; beginning = start; } } // Decrease the size of the window else { while (start < end) { // Remove the element at start window.put(A[start], window.get(A[start]) - 1); // Remove the element from the window // if its count is zero if (window.get(A[start]) == 0) { window.remove(A[start]); } // Increment the start of the window start++; // Find the maximum and minimum element // in the current window minimum = window.firstKey(); maximum = window.lastKey(); // Stop decreasing the size of window // when difference is not greater if (maximum - minimum <= X) break; } } } // Print the longest sub-array for (int i = beginning; i < beginning + maxLen; i++) System.out.print(A[i] + " "); } // Driver Code public static void main(String[] args) { // Given array int arr[] = { 15, 10, 1, 2, 4, 7, 2 }, X = 5; // store the size of the array int n = arr.length; // Function call longestSubarray(arr, n, X); }} // This code is contributed by Kingash.
# Python3 program to find the longest sub-array# where the absolute difference between any# two elements is not greater than X # Function that prints the longest sub-array# where the absolute difference between any# two element is not greater than Xdef longestSubarray(A, N, X): # Initialize a variable to store # length of longest sub-array maxLen = 0 # Initialize a variable to store the # beginning of the longest sub-array beginning = 0 # Initialize a map to store the maximum # and the minimum elements for a given window window = {} # Initialize the window start = 0 # Loop through the array for end in range(N): # Increment the count of that # element in the window if A[end] in window: window[A[end]] += 1 else: window[A[end]] = 1 # Find the maximum and minimum element # in the current window minimum = min(list(window.keys())) maximum = max(list(window.keys())) # If the difference is not # greater than X if maximum - minimum <= X: # Update the length of the longest # sub-array and store the beginning # of the sub-array if maxLen < end - start + 1: maxLen = end - start + 1 beginning = start # Decrease the size of the window else: while start < end: # Remove the element at start window[A[start]] -= 1 # Remove the element from the window # if its count is zero if window[A[start]] == 0: window.pop(A[start]) # Increment the start of the window start += 1 # Find the maximum and minimum element # in the current window minimum = min(list(window.keys())) maximum = max(list(window.keys())) # Stop decreasing the size of window # when difference is not greater if maximum - minimum <= X: break # Print the longest sub-array for i in range(beginning, beginning + maxLen): print(A[i], end = ' ') # Driver Codearr = [15, 10, 1, 2, 4, 7, 2]X = 5n = len(arr)longestSubarray(arr, n, X) # This code is contributed by Shivam Singh
<script> // JavaScript program to find the longest sub-array// where the absolute difference between any// two elements is not greater than X // Function that prints the longest sub-array// where the absolute difference between any// two element is not greater than Xfunction longestSubarray(A, N, X){ // Initialize a variable to store // length of longest sub-array let maxLen = 0 // Initialize a variable to store the // beginning of the longest sub-array let beginning = 0 // Initialize a map to store the maximum // and the minimum elements for a given window let window = new Map() // Initialize the window let start = 0 // Loop through the array for(let end=0;end<N;end++){ // Increment the count of that // element in the window if(window.has(A[end])) window.set(A[end],window.get(A[end]) + 1) else window.set(A[end] , 1) // Find the maximum and minimum element // in the current window let minimum = Math.min(...window.keys()) let maximum = Math.max(...window.keys()) // If the difference is not // greater than X if(maximum - minimum <= X){ // Update the length of the longest // sub-array and store the beginning // of the sub-array if(maxLen < end - start + 1){ maxLen = end - start + 1 beginning = start } } // Decrease the size of the window else{ while(start < end){ // Remove the element at start window.set(A[start],window.get(A[start]) - 1) // Remove the element from the window // if its count is zero if(window.get(A[start]) == 0) window.delete(A[start]) // Increment the start of the window start += 1 // Find the maximum and minimum element // in the current window minimum = Math.min(...window.keys()) maximum = Math.max(...window.keys()) // Stop decreasing the size of window // when difference is not greater if(maximum - minimum <= X) break } } } // Print the longest sub-array for(let i=beginning;i<beginning+maxLen;i++){ document.write(A[i],' ') }} // Driver Codelet arr = [15, 10, 1, 2, 4, 7, 2]let X = 5let n = arr.lengthlongestSubarray(arr, n, X) // This code is contributed by Shinjanpatra </script>
2 4 7 2
Time Complexity: O(N * log(N))
SHIVAMSINGH67
Kingash
sweetyty
shinjanpatra
vinayedula
sliding-window
subarray
Arrays
Competitive Programming
Mathematical
sliding-window
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Introduction to Data Structures
Search an element in a sorted and rotated array
Find Second largest element in an array
Count Inversions in an array | Set 1 (Using Merge Sort)
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Modulo 10^9+7 (1000000007)
Arrow operator -> in C/C++ with Examples
Prefix Sum Array - Implementation and Applications in Competitive Programming | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 241,
"s": 52,
"text": "Given an integer array arr[] of size N and an integer X, the task is to find the longest sub-array where the absolute difference between any two elements is not greater than X. Examples: "
},
{
"code": null,
"e": 640,
"s": 241,
"text": "Input: arr = { 8, 4, 2, 6, 7 }, X = 4 Output: 4 2 6 Explanation: The sub-array described by index [1, 3], i.e, { 4, 2, 6 } contains no such difference of two elements which is greater than 4.Input: arr = { 15, 10, 1, 2, 4, 7, 2}, X = 5 Output: 2 4 7 2 Explanation: The sub-array described by indexes [3, 6], i.e, { 2, 4, 7, 2 } contains no such difference of two elements which is greater than 5. "
},
{
"code": null,
"e": 1081,
"s": 642,
"text": "Naive Approach: Simple solution is to consider all subarrays one by one, find the maximum and minimum element of that sub-array and check if their difference is not greater than X. Among all such sub-arrays print the longest sub-array.Time Complexity: O(N3)Efficient Approach: The idea is to use the Sliding Window Technique to consider a sub-array and use a Map data structure to find the maximum and minimum element in that sub-array. "
},
{
"code": null,
"e": 1148,
"s": 1081,
"text": "At first the Start and End of the window points to the 0-th index."
},
{
"code": null,
"e": 1272,
"s": 1148,
"text": "At every iteration, the element at End is inserted in the Map if not already present or otherwise its count is incremented."
},
{
"code": null,
"e": 1467,
"s": 1272,
"text": "If the difference between the maximum and minimum element is not greater than X, then update the maximum length of the required sub-array and store the beginning of that sub-array in a variable."
},
{
"code": null,
"e": 1596,
"s": 1467,
"text": "Otherwise, increment the Start of the window until the difference between the maximum and minimum element is not greater than X."
},
{
"code": null,
"e": 1759,
"s": 1596,
"text": "When incrementing the Start, the size of the window decreases, remove the element at the Start from the Map if and only if the count of that element becomes zero."
},
{
"code": null,
"e": 1945,
"s": 1759,
"text": "Finally, print the sub-array with the longest length, and the absolute difference between any two elements is not greater than the X.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1949,
"s": 1945,
"text": "C++"
},
{
"code": null,
"e": 1954,
"s": 1949,
"text": "Java"
},
{
"code": null,
"e": 1962,
"s": 1954,
"text": "Python3"
},
{
"code": null,
"e": 1973,
"s": 1962,
"text": "Javascript"
},
{
"code": "// C++ program to find the longest sub-array// where the absolute difference between any// two elements is not greater than X #include <bits/stdc++.h>using namespace std; // Function that prints the longest sub-array// where the absolute difference between any// two element is not greater than Xvoid longestSubarray(int* A, int N, int X){ // Initialize a variable to store // length of longest sub-array int maxLen = 0; // Initialize a variable to store the // beginning of the longest sub-array int beginning = 0; // Initialize a map to store the maximum // and the minimum elements for a given window map<int, int> window; // Initialize the window int start = 0, end = 0; // Loop through the array for (; end < N; end++) { // Increment the count of that // element in the window window[A[end]]++; // Find the maximum and minimum element // in the current window auto minimum = window.begin()->first; auto maximum = window.rbegin()->first; // If the difference is not // greater than X if (maximum - minimum <= X) { // Update the length of the longest // sub-array and store the beginning // of the sub-array if (maxLen < end - start + 1) { maxLen = end - start + 1; beginning = start; } } // Decrease the size of the window else { while (start < end) { // Remove the element at start window[A[start]]--; // Remove the element from the window // if its count is zero if (window[A[start]] == 0) { window.erase(window.find(A[start])); } // Increment the start of the window start++; // Find the maximum and minimum element // in the current window auto minimum = window.begin()->first; auto maximum = window.rbegin()->first; // Stop decreasing the size of window // when difference is not greater if (maximum - minimum <= X) break; } } } // Print the longest sub-array for (int i = beginning; i < beginning + maxLen; i++) cout << A[i] << \" \";} // Driver Codeint main(){ int arr[] = { 15, 10, 1, 2, 4, 7, 2 }, X = 5; int n = sizeof(arr) / sizeof(arr[0]); longestSubarray(arr, n, X); return 0;}",
"e": 4515,
"s": 1973,
"text": null
},
{
"code": "// JAVA program to find the longest sub-array// where the absolute difference between any// two elements is not greater than Ximport java.io.*;import java.lang.*;import java.util.*;class GFG{ // Function that prints the longest sub-array // where the absolute difference between any // two element is not greater than X static void longestSubarray(int A[], int N, int X) { // Initialize a variable to store // length of longest sub-array int maxLen = 0; // Initialize a variable to store the // beginning of the longest sub-array int beginning = 0; // Initialize a map to store the maximum // and the minimum elements for a given window TreeMap<Integer, Integer> window = new TreeMap<>(); // Initialize the window int start = 0, end = 0; // Loop through the array for (; end < N; end++) { // Increment the count of that // element in the window window.put(A[end], window.getOrDefault(A[end], 0) + 1); // Find the maximum and minimum element // in the current window int minimum = window.firstKey(); int maximum = window.lastKey(); // If the difference is not // greater than X if (maximum - minimum <= X) { // Update the length of the longest // sub-array and store the beginning // of the sub-array if (maxLen < end - start + 1) { maxLen = end - start + 1; beginning = start; } } // Decrease the size of the window else { while (start < end) { // Remove the element at start window.put(A[start], window.get(A[start]) - 1); // Remove the element from the window // if its count is zero if (window.get(A[start]) == 0) { window.remove(A[start]); } // Increment the start of the window start++; // Find the maximum and minimum element // in the current window minimum = window.firstKey(); maximum = window.lastKey(); // Stop decreasing the size of window // when difference is not greater if (maximum - minimum <= X) break; } } } // Print the longest sub-array for (int i = beginning; i < beginning + maxLen; i++) System.out.print(A[i] + \" \"); } // Driver Code public static void main(String[] args) { // Given array int arr[] = { 15, 10, 1, 2, 4, 7, 2 }, X = 5; // store the size of the array int n = arr.length; // Function call longestSubarray(arr, n, X); }} // This code is contributed by Kingash.",
"e": 7162,
"s": 4515,
"text": null
},
{
"code": "# Python3 program to find the longest sub-array# where the absolute difference between any# two elements is not greater than X # Function that prints the longest sub-array# where the absolute difference between any# two element is not greater than Xdef longestSubarray(A, N, X): # Initialize a variable to store # length of longest sub-array maxLen = 0 # Initialize a variable to store the # beginning of the longest sub-array beginning = 0 # Initialize a map to store the maximum # and the minimum elements for a given window window = {} # Initialize the window start = 0 # Loop through the array for end in range(N): # Increment the count of that # element in the window if A[end] in window: window[A[end]] += 1 else: window[A[end]] = 1 # Find the maximum and minimum element # in the current window minimum = min(list(window.keys())) maximum = max(list(window.keys())) # If the difference is not # greater than X if maximum - minimum <= X: # Update the length of the longest # sub-array and store the beginning # of the sub-array if maxLen < end - start + 1: maxLen = end - start + 1 beginning = start # Decrease the size of the window else: while start < end: # Remove the element at start window[A[start]] -= 1 # Remove the element from the window # if its count is zero if window[A[start]] == 0: window.pop(A[start]) # Increment the start of the window start += 1 # Find the maximum and minimum element # in the current window minimum = min(list(window.keys())) maximum = max(list(window.keys())) # Stop decreasing the size of window # when difference is not greater if maximum - minimum <= X: break # Print the longest sub-array for i in range(beginning, beginning + maxLen): print(A[i], end = ' ') # Driver Codearr = [15, 10, 1, 2, 4, 7, 2]X = 5n = len(arr)longestSubarray(arr, n, X) # This code is contributed by Shivam Singh",
"e": 9547,
"s": 7162,
"text": null
},
{
"code": "<script> // JavaScript program to find the longest sub-array// where the absolute difference between any// two elements is not greater than X // Function that prints the longest sub-array// where the absolute difference between any// two element is not greater than Xfunction longestSubarray(A, N, X){ // Initialize a variable to store // length of longest sub-array let maxLen = 0 // Initialize a variable to store the // beginning of the longest sub-array let beginning = 0 // Initialize a map to store the maximum // and the minimum elements for a given window let window = new Map() // Initialize the window let start = 0 // Loop through the array for(let end=0;end<N;end++){ // Increment the count of that // element in the window if(window.has(A[end])) window.set(A[end],window.get(A[end]) + 1) else window.set(A[end] , 1) // Find the maximum and minimum element // in the current window let minimum = Math.min(...window.keys()) let maximum = Math.max(...window.keys()) // If the difference is not // greater than X if(maximum - minimum <= X){ // Update the length of the longest // sub-array and store the beginning // of the sub-array if(maxLen < end - start + 1){ maxLen = end - start + 1 beginning = start } } // Decrease the size of the window else{ while(start < end){ // Remove the element at start window.set(A[start],window.get(A[start]) - 1) // Remove the element from the window // if its count is zero if(window.get(A[start]) == 0) window.delete(A[start]) // Increment the start of the window start += 1 // Find the maximum and minimum element // in the current window minimum = Math.min(...window.keys()) maximum = Math.max(...window.keys()) // Stop decreasing the size of window // when difference is not greater if(maximum - minimum <= X) break } } } // Print the longest sub-array for(let i=beginning;i<beginning+maxLen;i++){ document.write(A[i],' ') }} // Driver Codelet arr = [15, 10, 1, 2, 4, 7, 2]let X = 5let n = arr.lengthlongestSubarray(arr, n, X) // This code is contributed by Shinjanpatra </script>",
"e": 12170,
"s": 9547,
"text": null
},
{
"code": null,
"e": 12178,
"s": 12170,
"text": "2 4 7 2"
},
{
"code": null,
"e": 12212,
"s": 12180,
"text": "Time Complexity: O(N * log(N)) "
},
{
"code": null,
"e": 12226,
"s": 12212,
"text": "SHIVAMSINGH67"
},
{
"code": null,
"e": 12234,
"s": 12226,
"text": "Kingash"
},
{
"code": null,
"e": 12243,
"s": 12234,
"text": "sweetyty"
},
{
"code": null,
"e": 12256,
"s": 12243,
"text": "shinjanpatra"
},
{
"code": null,
"e": 12267,
"s": 12256,
"text": "vinayedula"
},
{
"code": null,
"e": 12282,
"s": 12267,
"text": "sliding-window"
},
{
"code": null,
"e": 12291,
"s": 12282,
"text": "subarray"
},
{
"code": null,
"e": 12298,
"s": 12291,
"text": "Arrays"
},
{
"code": null,
"e": 12322,
"s": 12298,
"text": "Competitive Programming"
},
{
"code": null,
"e": 12335,
"s": 12322,
"text": "Mathematical"
},
{
"code": null,
"e": 12350,
"s": 12335,
"text": "sliding-window"
},
{
"code": null,
"e": 12357,
"s": 12350,
"text": "Arrays"
},
{
"code": null,
"e": 12370,
"s": 12357,
"text": "Mathematical"
},
{
"code": null,
"e": 12468,
"s": 12370,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12491,
"s": 12468,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 12523,
"s": 12491,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 12571,
"s": 12523,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 12611,
"s": 12571,
"text": "Find Second largest element in an array"
},
{
"code": null,
"e": 12667,
"s": 12611,
"text": "Count Inversions in an array | Set 1 (Using Merge Sort)"
},
{
"code": null,
"e": 12710,
"s": 12667,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 12753,
"s": 12710,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 12780,
"s": 12753,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 12821,
"s": 12780,
"text": "Arrow operator -> in C/C++ with Examples"
}
] |
Draw a line on an image using OpenCV | In this program, we will draw a simple line on an image using the OpenCV function line().
Step 1: Import cv2.
Step 2: Read the image using imread().
Step 3: Get the dimensions of the image using the image.shape method.
Step 4: Define starting point of the line.
Step 5: Define the end point of the line.
Step 6: Define the thickness of the line.
Step 7: Draw the line using the cv2.line() function and pass Step 3 to Step 4 as parameters.
import cv2
image = cv2.imread('testimage.jpg')
height, width, channels = image.shape
startpoint = (0, 0)
endpoint = (height, width)
thickness = 9
color = (255, 0, 0)
image = cv2.line(image, startpoint, endpoint, color, thickness)
cv2.imshow('Line', image)
As you can see, a blue line is drawn on the image. | [
{
"code": null,
"e": 1152,
"s": 1062,
"text": "In this program, we will draw a simple line on an image using the OpenCV function line()."
},
{
"code": null,
"e": 1501,
"s": 1152,
"text": "Step 1: Import cv2.\nStep 2: Read the image using imread().\nStep 3: Get the dimensions of the image using the image.shape method.\nStep 4: Define starting point of the line.\nStep 5: Define the end point of the line.\nStep 6: Define the thickness of the line.\nStep 7: Draw the line using the cv2.line() function and pass Step 3 to Step 4 as parameters."
},
{
"code": null,
"e": 1758,
"s": 1501,
"text": "import cv2\n\nimage = cv2.imread('testimage.jpg')\nheight, width, channels = image.shape\nstartpoint = (0, 0)\nendpoint = (height, width)\nthickness = 9\ncolor = (255, 0, 0)\nimage = cv2.line(image, startpoint, endpoint, color, thickness)\ncv2.imshow('Line', image)"
},
{
"code": null,
"e": 1809,
"s": 1758,
"text": "As you can see, a blue line is drawn on the image."
}
] |
Maximum sum subsequence of any size which is decreasing-increasing alternatively - GeeksforGeeks | 11 Jan, 2022
Given an array of integers arr[], find the subsequence with maximum sum whose elements are first decreasing, then increasing, or vice versa, The subsequence can start anywhere in the main sequence, not necessarily at the first element of the main sequence.
A sequence {x1, x2, .. xn} is an alternating sequence if its elements satisfy one of the following relations (As described in the article Longest alternating subsequence):
Two adjacent elements that are equal are not counted as alternating.
x1 < x2 > x3 < x4 > x5 < .... xn or x1 > x2 < x3 > x4 < x5 > .... xn
Examples :
Input: arr[] = {4, 8, 2, 5, 6, 8}Output: 26Explanation: Alternating subsequence with maximum sum is {4, 8, 6, 8}. Sum = 4 + 8 + 6 + 8 = 26
Input: arr[] = {0, 1, 1, 1, 3, 2, 5}Output: 11Explanation: Alternating subsequence with maximum sum is {1, 3, 2, 5}. Sum = 1 + 3 + 2 + 5 = 11
Input: arr[] = {1, 4, 5}Output: 9Explanation: Alternating subsequence with maximum sum is {4, 5}. Sum = 4 + 5 = 9
Input: arr[] = {1, 0, 1, 0, 0, 3}Output: 5Explanation: Alternating subsequence with maximum sum is {1, 0, 1, 0, 3}. Sum = 1 + 0 + 1 + 0 + 3 = 5
Input: arr[] = {5, 5}Output: 5Explanation: Alternating subsequence with maximum sum is {5}. Sum = 5
This problem is an extension of the Maximum sum alternating subsequence problem. Unlike the previous problem, now we need to calculate the maximum sum of the alternating subsequence regardless of where it is in the main sequence, and regardless of whether it starts with two elements ascending or two descending elements.
Approach: This problem can be solved by Dynamic Programming combined with Backtracking. Suppose, we have an array arr[] with any N elements.
We can consider each arr[i] element as a terminating element of an alternating sequence.
There can be many alternating subsequences whose last element is arr[i], but surely one of them is the sequence with the greatest sum.
Furthermore, the maximum sum of the alternating subsequences ending with arr[i] is not necessarily greater than the maximum sum of the alternating subsequences ending with arr[i-1]. And this is the basis for implementing the algorithm according to the Backtracking technique.
Have an array say maxSum[] of length N which will store all the maximum sums ending at each element in the array arr[]. Specifically, maxSum[i] will store the maximum sum of the alternating subsequence ending at the value arr[i].
We will use another array before[] to store the value preceding the last element of each alternating subsequence with maximum sum.
For example, an array arr[] = {1, 5, 7, 3, 4, 5} will have an alternating subsequence {5, 7, 3, 4} whose maximum sum is 5 + 7 + 3 + 4 = 19. The subsequence {5, 7, 3, 4} ends at the value 4, which has index 4 in the array arr[]. So we have arr[4] = 4, maxSum[4] = 19, before[4] = 3 (because arr[3] = 3). Those values will be calculated and saved into two arrays maxSum[] and before[] during the calculation and can be reused as needed.
Use the following steps to implement the approach:
Use a loop to iterate through every element of the array arr[]. Each time we traverse an arr[i] element, we look at the elements that precede it:
i Loop traversal from 1 to N-1 (There’s no need to start at position 0, because that’s the base case): j Loop traversal from 0 to i-1:
At each state i and j, we will reuse any maxSum[j] with 0 <= j < i according to the principle of Dynamic Programming:
if: (arr[i] > arr[j] && arr[before[j]] > arr[j]) or (arr[i] < arr[j] && arr[before[j]] < arr[j])
then: sum = arr[i] + maxSum[j]
If maxSum[j] does not satisfy the above condition, it can be two equal elements. Since two equal elements are not treated as an alternating sequence, we only take one of them.
if: arr[i] == arr[j]
then: sum = maxSum[j]
Or it may not be any of the above, like having more than two elements in increasing or having more than two elements in decreasing order.
Example {1, 5, 7, 3, 4, 5}. Suppose we are at i = 5, j = 4.
Then before[4] is the 3-rd element, and (arr[before[j]], arr[j], arr[i]) = (arr[before[4]], arr[4], arr[5]) = (arr[3], arr[4], arr[5]) = (3, 4, 5).
The above one is not a valid alternating subsequence, meaning that before[j] is not the index of a valid value.
We will look at the preceding element of arr[before[j]] in its alternating sequence: before[before[j]] = before[3] = 2, and arr[2] with arr[4] and arr[5] form a valid subsequence (7, 4, 5).
So we get a value of arr[5] + arr[4] + maxSum[2], which is the final sum of state {i = 5, j = 4}.
We need to compare it with other {i and j} states (like {i = 5, j = 3}, {i = 5, j = 2}...) to get the final result for maxSum[5].
Then save j into the before[5] if it precedes arr[5] and helps arr[5] form a valid subsequence with a maximum sum at state 5.
Take a look at the illustration below to get the idea clear.
index : 0 1 2 3 4 5 || N = 6arr[] : 1, 5, 7, 3, 4, 5
—————————————————————————————————-
maxSum[0] : 1 0 0 0 0 0 = 1 base casebefore[-1] : -1 _ _ _ _ _
maxSum[1] : 1 6 0 0 0 0 = 6 because 1 + 5before[1] : -1 0 _ _ _ _
maxSum[2] : 1 6 12 0 0 0 = 12 because 1, 5, 7 isn’t alternating subsequence, and just 5 & 7 before[2] : -1 0 1 _ _ _ is valid, we use backtracking at index 2 so we will go through the following subsequence: {1, 7}, {5, 7}. We have {5, 7} because before[1] is index 0, we continue to find value at before[before[1]] = -1, whose value is 0, so 0 + 5 + 7 = 12 > 1 + 7.
maxSum[3] : 1 6 12 15 0 0 = 15 because 5, 7, 3 is valid alternating subsequence, before[3] : -1 0 1 2 _ _ so 3 + max(maxSum[2], maxSum[1], maxSum[0]) = 3 + 12.
maxSum[4] : 1 6 12 15 19 0 = 19 because 5, 7, 3, 4 is valid alternating subsequence,before[4] : -1 0 1 2 3 _ so 4 + max(maxSum[3], maxSum[2],... maxSum[0]) = 4 + 15.
maxSum[5] : 1 6 12 15 19 21 = 21, arr[5] cannot be the next element of maxSum[4] because 3, 4, 5before[5] : -1 0 1 2 3 2 isn’t alternating subsequence. So we need use backtracking here. We will treat the value 3 as an invalid value for the alternating subsequence ending in arr[5]. We need to find the preceding element of before[arr[4]] in the sum of maxSum[4] recursively, that is index 2. Now 7, 4, 5 have formed a valid alternating subsequence. So we have 5 + max(backtracking(index 4), maxSum[3], maxSum[2],...) = 5 + 16 ( because 4 + 7 + 5)Then, final max sum of alternating subsequence of arr is max element of “maxSum” array.
Output: 21
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ code to implement the above approach #include <bits/stdc++.h>using namespace std; // Function for backtrackingint backtracking(int arr[], int maxSum[], int before[], int N, int root, int bef_root, int bbef_root){ // {root, bef_root} represents state{i, j} // bbef_root represent before[before[j]] // We ignore the invalid before[j] index // Base case: if (bbef_root == -1) return arr[bef_root]; // The case of a subsequence with // alternating parts: if ((arr[root] > arr[bef_root] && arr[bbef_root] > arr[bef_root]) || (arr[root] < arr[bef_root] && arr[bbef_root] < arr[bef_root])) { return arr[bef_root] + maxSum[bbef_root]; } // case (arr[bef_root] == arr[bbef_root]) else { return backtracking(arr, maxSum, before, N, root, bef_root, before[bbef_root]); }} int maxSumAlternatingSubsequence(int arr[], int N){ // Max alternating subsequence sum // ending at arr[i]. int maxSum[N]; // Array to store the index of the element // preceding the last element at maxSum[i] int before[N]; // Value initialization for arrays: fill_n(&maxSum[0], N, 0); maxSum[0] = arr[0]; before[0] = -1; // Iterate over the array: for (int i = 1; i < N; i++) for (int j = 0; j < i; j++) { int currentMax = 0; if ((arr[i] > arr[j] && arr[before[j]] > arr[j]) || (arr[i] < arr[j] && arr[before[j]] < arr[j]) || before[j] == -1) { // Whenever an element is // between two smaller elements // or between two larger elements, // it is an alternating sequence. // When the preceding index of j is -1, // we need to treat it explicitly, // because -1 is not a valid index. currentMax = (arr[i] == arr[j]) ? maxSum[j] : arr[i] + maxSum[j]; } else if (arr[i] == arr[j]) { // If arr[i] is equal to arr[j] then // only take it once, // before[j] cannot be equal to -1. currentMax = maxSum[j]; } else { // Perform backtracking // If three adjacent elements // are increasing or decreasing. currentMax = arr[i] + backtracking( arr, maxSum, before, N, i, j, before[before[j]]); } if (currentMax >= maxSum[i]) { // Stores the maximum sum and // the index preceding // the last element // at position i of // current alternating subsequence // after each iteration. maxSum[i] = currentMax; before[i] = j; } } // get max result in array return *max_element(maxSum, maxSum + N);} // Driver codeint main(){ int arr[] = { 1, 5, 7, 3, 4, 5 }; int N = sizeof(arr) / sizeof(int); // Maximum sum of alternating subsequence // of array arr[] cout << maxSumAlternatingSubsequence(arr, N) << endl; return 0;}
// Java code to implement the above approachimport java.io.*; class GFG{ // Function for backtrackingstatic int backtracking(int arr[], int maxSum[], int before[], int N, int root, int bef_root, int bbef_root){ // {root, bef_root} represents state{i, j} // bbef_root represent before[before[j]] // We ignore the invalid before[j] index // Base case: if (bbef_root == -1) return arr[bef_root]; // The case of a subsequence with // alternating parts: if ((arr[root] > arr[bef_root] && arr[bbef_root] > arr[bef_root]) || (arr[root] < arr[bef_root] && arr[bbef_root] < arr[bef_root])) { return arr[bef_root] + maxSum[bbef_root]; } // case (arr[bef_root] == arr[bbef_root]) else { return backtracking(arr, maxSum, before, N, root, bef_root, before[bbef_root]); }} static int maxSumAlternatingSubsequence(int arr[], int N){ // Max alternating subsequence sum // ending at arr[i]. int maxSum[] = new int[N]; // Array to store the index of the element // preceding the last element at maxSum[i] int before[] = new int[N]; // Value initialization for arrays: maxSum[0] = arr[0]; before[0] = -1; // Iterate over the array: for(int i = 1; i < N; i++) for(int j = 0; j < i; j++) { int currentMax = 0; if ((arr[i] > arr[j] && before[j] != -1 && arr[before[j]] > arr[j]) || (arr[i] < arr[j] && before[j] != -1 && arr[before[j]] < arr[j]) || before[j] == -1) { // Whenever an element is // between two smaller elements // or between two larger elements, // it is an alternating sequence. // When the preceding index of j is -1, // we need to treat it explicitly, // because -1 is not a valid index. currentMax = (arr[i] == arr[j]) ? maxSum[j] : arr[i] + maxSum[j]; } else if (arr[i] == arr[j]) { // If arr[i] is equal to arr[j] then // only take it once, // before[j] cannot be equal to -1. currentMax = maxSum[j]; } else { // Perform backtracking // If three adjacent elements // are increasing or decreasing. currentMax = arr[i] + backtracking(arr, maxSum, before, N, i, j, before[before[j]]); } if (currentMax >= maxSum[i]) { // Stores the maximum sum and the index // preceding the last element at position // i of current alternating subsequence // after each iteration. maxSum[i] = currentMax; before[i] = j; } } // get max result in array int maxi = 0; for(int i = 0; i < N; i++) { maxi = Math.max(maxSum[i], maxi); } return maxi;} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 5, 7, 3, 4, 5 }; int N = arr.length; // Maximum sum of alternating subsequence // of array arr[] System.out.println( maxSumAlternatingSubsequence(arr, N));}} // This code is contributed by Potta Lokesh
# Python code to implement the above approach # Function for backtrackingdef backtracking(arr, maxSum, before, N, root, bef_root, bbef_root): # {root, bef_root} represents state{i, j} # bbef_root represent before[before[j]] # We ignore the invalid before[j] index # Base case: if (bbef_root == -1): return arr[bef_root] # The case of a subsequence with # alternating parts: if (arr[root] > arr[bef_root] and arr[bbef_root] > arr[bef_root]) or (arr[root] < arr[bef_root] and arr[bbef_root] < arr[bef_root]): return arr[bef_root] + maxSum[bbef_root] # case (arr[bef_root] == arr[bbef_root]) else: return backtracking(arr, maxSum, before, N, root, bef_root, before[bbef_root]) def maxSumAlternatingSubsequence(arr, N): # Max alternating subsequence sum # ending at arr[i]. maxSum = [0] * N # Array to store the index of the element # preceding the last element at maxSum[i] before = [0] * N # Value initialization for arrays: maxSum[0] = arr[0] before[0] = -1 # Iterate over the array: for i in range(N): for j in range(i): currentMax = 0 if (arr[i] > arr[j] and before[j] != -1 and arr[before[j]] > arr[j]) or (arr[i] < arr[j] and before[j] != -1 and arr[before[j]] < arr[j]) or before[j] == -1: # Whenever an element is # between two smaller elements # or between two larger elements, # it is an alternating sequence. # When the preceding index of j is -1, # we need to treat it explicitly, # because -1 is not a valid index. currentMax = maxSum[j] if ( arr[i] == arr[j]) else arr[i] + maxSum[j] elif (arr[i] == arr[j]): # If arr[i] is equal to arr[j] then # only take it once, # before[j] cannot be equal to -1. currentMax = maxSum[j] else: # Perform backtracking # If three adjacent elements # are increasing or decreasing. currentMax = arr[i] + backtracking(arr, maxSum, before, N, i, j, before[before[j]]) if (currentMax >= maxSum[i]): # Stores the maximum sum and the index # preceding the last element at position # i of current alternating subsequence # after each iteration. maxSum[i] = currentMax before[i] = j # get max result in array maxi = 0 for i in range(N): maxi = max(maxSum[i], maxi) return maxi # Driver codearr = [1, 5, 7, 3, 4, 5]N = len(arr) # Maximum sum of alternating subsequence# of array arrprint(maxSumAlternatingSubsequence(arr, N)) # This code is contributed by gfgking
// C# program for above approachusing System;class GFG{ // Function for backtrackingstatic int backtracking(int []arr, int []maxSum, int []before, int N, int root, int bef_root, int bbef_root){ // {root, bef_root} represents state{i, j} // bbef_root represent before[before[j]] // We ignore the invalid before[j] index // Base case: if (bbef_root == -1) return arr[bef_root]; // The case of a subsequence with // alternating parts: if ((arr[root] > arr[bef_root] && arr[bbef_root] > arr[bef_root]) || (arr[root] < arr[bef_root] && arr[bbef_root] < arr[bef_root])) { return arr[bef_root] + maxSum[bbef_root]; } // case (arr[bef_root] == arr[bbef_root]) else { return backtracking(arr, maxSum, before, N, root, bef_root, before[bbef_root]); }} static int maxSumAlternatingSubsequence(int []arr, int N){ // Max alternating subsequence sum // ending at arr[i]. int []maxSum = new int[N]; // Array to store the index of the element // preceding the last element at maxSum[i] int []before = new int[N]; // Value initialization for arrays: maxSum[0] = arr[0]; before[0] = -1; // Iterate over the array: for(int i = 1; i < N; i++) for(int j = 0; j < i; j++) { int currentMax = 0; if ((arr[i] > arr[j] && before[j] != -1 && arr[before[j]] > arr[j]) || (arr[i] < arr[j] && before[j] != -1 && arr[before[j]] < arr[j]) || before[j] == -1) { // Whenever an element is // between two smaller elements // or between two larger elements, // it is an alternating sequence. // When the preceding index of j is -1, // we need to treat it explicitly, // because -1 is not a valid index. currentMax = (arr[i] == arr[j]) ? maxSum[j] : arr[i] + maxSum[j]; } else if (arr[i] == arr[j]) { // If arr[i] is equal to arr[j] then // only take it once, // before[j] cannot be equal to -1. currentMax = maxSum[j]; } else { // Perform backtracking // If three adjacent elements // are increasing or decreasing. currentMax = arr[i] + backtracking(arr, maxSum, before, N, i, j, before[before[j]]); } if (currentMax >= maxSum[i]) { // Stores the maximum sum and the index // preceding the last element at position // i of current alternating subsequence // after each iteration. maxSum[i] = currentMax; before[i] = j; } } // get max result in array int maxi = 0; for(int i = 0; i < N; i++) { maxi = Math.Max(maxSum[i], maxi); } return maxi;} // Driver Codepublic static void Main(){ int []arr = { 1, 5, 7, 3, 4, 5 }; int N = arr.Length; // Maximum sum of alternating subsequence // of array arr[] Console.Write( maxSumAlternatingSubsequence(arr, N));}} // This code is contributed by Samim Hossain Mondal.
<script>// javascript code to implement the above approach // Function for backtrackingfunction backtracking(arr , maxSum, before , N , root, bef_root , bbef_root){ // {root, bef_root} represents state{i, j} // bbef_root represent before[before[j]] // We ignore the invalid before[j] index // Base case: if (bbef_root == -1) return arr[bef_root]; // The case of a subsequence with // alternating parts: if ((arr[root] > arr[bef_root] && arr[bbef_root] > arr[bef_root]) || (arr[root] < arr[bef_root] && arr[bbef_root] < arr[bef_root])) { return arr[bef_root] + maxSum[bbef_root]; } // case (arr[bef_root] == arr[bbef_root]) else { return backtracking(arr, maxSum, before, N, root, bef_root, before[bbef_root]); }} function maxSumAlternatingSubsequence(arr,N){ // Max alternating subsequence sum // ending at arr[i]. var maxSum = Array.from({length: N}, (_, i) => 0); // Array to store the index of the element // preceding the last element at maxSum[i] var before = Array.from({length: N}, (_, i) => 0); // Value initialization for arrays: maxSum[0] = arr[0]; before[0] = -1; // Iterate over the array: for(var i = 1; i < N; i++) for(var j = 0; j < i; j++) { var currentMax = 0; if ((arr[i] > arr[j] && before[j] != -1 && arr[before[j]] > arr[j]) || (arr[i] < arr[j] && before[j] != -1 && arr[before[j]] < arr[j]) || before[j] == -1) { // Whenever an element is // between two smaller elements // or between two larger elements, // it is an alternating sequence. // When the preceding index of j is -1, // we need to treat it explicitly, // because -1 is not a valid index. currentMax = (arr[i] == arr[j]) ? maxSum[j] : arr[i] + maxSum[j]; } else if (arr[i] == arr[j]) { // If arr[i] is equal to arr[j] then // only take it once, // before[j] cannot be equal to -1. currentMax = maxSum[j]; } else { // Perform backtracking // If three adjacent elements // are increasing or decreasing. currentMax = arr[i] + backtracking(arr, maxSum, before, N, i, j, before[before[j]]); } if (currentMax >= maxSum[i]) { // Stores the maximum sum and the index // preceding the last element at position // i of current alternating subsequence // after each iteration. maxSum[i] = currentMax; before[i] = j; } } // get max result in array var maxi = 0; for(var i = 0; i < N; i++) { maxi = Math.max(maxSum[i], maxi); } return maxi;} // Driver codevar arr = [ 1, 5, 7, 3, 4, 5 ];var N = arr.length; // Maximum sum of alternating subsequence// of array arrdocument.write(maxSumAlternatingSubsequence(arr, N)); // This code is contributed by 29AjayKumar</script>
21
Time Complexity: O(N2) where N is the length of the array.Auxiliary Space: O(N)
lokeshpotta20
samim2000
29AjayKumar
gfgking
adnanirshad158
subsequence
Arrays
Backtracking
Dynamic Programming
Pattern Searching
Arrays
Dynamic Programming
Backtracking
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Move all negative numbers to beginning and positive to end with constant extra space
Program to find sum of elements in a given array
N Queen Problem | Backtracking-3
Write a program to print all permutations of a given string
Rat in a Maze | Backtracking-2
The Knight's tour problem | Backtracking-1
Backtracking | Introduction | [
{
"code": null,
"e": 24820,
"s": 24792,
"text": "\n11 Jan, 2022"
},
{
"code": null,
"e": 25077,
"s": 24820,
"text": "Given an array of integers arr[], find the subsequence with maximum sum whose elements are first decreasing, then increasing, or vice versa, The subsequence can start anywhere in the main sequence, not necessarily at the first element of the main sequence."
},
{
"code": null,
"e": 25250,
"s": 25077,
"text": "A sequence {x1, x2, .. xn} is an alternating sequence if its elements satisfy one of the following relations (As described in the article Longest alternating subsequence): "
},
{
"code": null,
"e": 25319,
"s": 25250,
"text": "Two adjacent elements that are equal are not counted as alternating."
},
{
"code": null,
"e": 25388,
"s": 25319,
"text": "x1 < x2 > x3 < x4 > x5 < .... xn or x1 > x2 < x3 > x4 < x5 > .... xn"
},
{
"code": null,
"e": 25400,
"s": 25388,
"text": " Examples :"
},
{
"code": null,
"e": 25539,
"s": 25400,
"text": "Input: arr[] = {4, 8, 2, 5, 6, 8}Output: 26Explanation: Alternating subsequence with maximum sum is {4, 8, 6, 8}. Sum = 4 + 8 + 6 + 8 = 26"
},
{
"code": null,
"e": 25681,
"s": 25539,
"text": "Input: arr[] = {0, 1, 1, 1, 3, 2, 5}Output: 11Explanation: Alternating subsequence with maximum sum is {1, 3, 2, 5}. Sum = 1 + 3 + 2 + 5 = 11"
},
{
"code": null,
"e": 25795,
"s": 25681,
"text": "Input: arr[] = {1, 4, 5}Output: 9Explanation: Alternating subsequence with maximum sum is {4, 5}. Sum = 4 + 5 = 9"
},
{
"code": null,
"e": 25939,
"s": 25795,
"text": "Input: arr[] = {1, 0, 1, 0, 0, 3}Output: 5Explanation: Alternating subsequence with maximum sum is {1, 0, 1, 0, 3}. Sum = 1 + 0 + 1 + 0 + 3 = 5"
},
{
"code": null,
"e": 26039,
"s": 25939,
"text": "Input: arr[] = {5, 5}Output: 5Explanation: Alternating subsequence with maximum sum is {5}. Sum = 5"
},
{
"code": null,
"e": 26363,
"s": 26041,
"text": "This problem is an extension of the Maximum sum alternating subsequence problem. Unlike the previous problem, now we need to calculate the maximum sum of the alternating subsequence regardless of where it is in the main sequence, and regardless of whether it starts with two elements ascending or two descending elements."
},
{
"code": null,
"e": 26505,
"s": 26363,
"text": "Approach: This problem can be solved by Dynamic Programming combined with Backtracking. Suppose, we have an array arr[] with any N elements. "
},
{
"code": null,
"e": 26594,
"s": 26505,
"text": "We can consider each arr[i] element as a terminating element of an alternating sequence."
},
{
"code": null,
"e": 26729,
"s": 26594,
"text": "There can be many alternating subsequences whose last element is arr[i], but surely one of them is the sequence with the greatest sum."
},
{
"code": null,
"e": 27005,
"s": 26729,
"text": "Furthermore, the maximum sum of the alternating subsequences ending with arr[i] is not necessarily greater than the maximum sum of the alternating subsequences ending with arr[i-1]. And this is the basis for implementing the algorithm according to the Backtracking technique."
},
{
"code": null,
"e": 27235,
"s": 27005,
"text": "Have an array say maxSum[] of length N which will store all the maximum sums ending at each element in the array arr[]. Specifically, maxSum[i] will store the maximum sum of the alternating subsequence ending at the value arr[i]."
},
{
"code": null,
"e": 27366,
"s": 27235,
"text": "We will use another array before[] to store the value preceding the last element of each alternating subsequence with maximum sum."
},
{
"code": null,
"e": 27804,
"s": 27366,
"text": "For example, an array arr[] = {1, 5, 7, 3, 4, 5} will have an alternating subsequence {5, 7, 3, 4} whose maximum sum is 5 + 7 + 3 + 4 = 19. The subsequence {5, 7, 3, 4} ends at the value 4, which has index 4 in the array arr[]. So we have arr[4] = 4, maxSum[4] = 19, before[4] = 3 (because arr[3] = 3). Those values will be calculated and saved into two arrays maxSum[] and before[] during the calculation and can be reused as needed."
},
{
"code": null,
"e": 27855,
"s": 27804,
"text": "Use the following steps to implement the approach:"
},
{
"code": null,
"e": 28001,
"s": 27855,
"text": "Use a loop to iterate through every element of the array arr[]. Each time we traverse an arr[i] element, we look at the elements that precede it:"
},
{
"code": null,
"e": 28143,
"s": 28001,
"text": "i Loop traversal from 1 to N-1 (There’s no need to start at position 0, because that’s the base case): j Loop traversal from 0 to i-1:"
},
{
"code": null,
"e": 28261,
"s": 28143,
"text": "At each state i and j, we will reuse any maxSum[j] with 0 <= j < i according to the principle of Dynamic Programming:"
},
{
"code": null,
"e": 28400,
"s": 28261,
"text": "if: (arr[i] > arr[j] && arr[before[j]] > arr[j]) or (arr[i] < arr[j] && arr[before[j]] < arr[j])"
},
{
"code": null,
"e": 28439,
"s": 28400,
"text": "then: sum = arr[i] + maxSum[j] "
},
{
"code": null,
"e": 28615,
"s": 28439,
"text": "If maxSum[j] does not satisfy the above condition, it can be two equal elements. Since two equal elements are not treated as an alternating sequence, we only take one of them."
},
{
"code": null,
"e": 28644,
"s": 28615,
"text": "if: arr[i] == arr[j]"
},
{
"code": null,
"e": 28673,
"s": 28644,
"text": "then: sum = maxSum[j]"
},
{
"code": null,
"e": 28811,
"s": 28673,
"text": "Or it may not be any of the above, like having more than two elements in increasing or having more than two elements in decreasing order."
},
{
"code": null,
"e": 28872,
"s": 28811,
"text": "Example {1, 5, 7, 3, 4, 5}. Suppose we are at i = 5, j = 4. "
},
{
"code": null,
"e": 29020,
"s": 28872,
"text": "Then before[4] is the 3-rd element, and (arr[before[j]], arr[j], arr[i]) = (arr[before[4]], arr[4], arr[5]) = (arr[3], arr[4], arr[5]) = (3, 4, 5)."
},
{
"code": null,
"e": 29132,
"s": 29020,
"text": "The above one is not a valid alternating subsequence, meaning that before[j] is not the index of a valid value."
},
{
"code": null,
"e": 29322,
"s": 29132,
"text": "We will look at the preceding element of arr[before[j]] in its alternating sequence: before[before[j]] = before[3] = 2, and arr[2] with arr[4] and arr[5] form a valid subsequence (7, 4, 5)."
},
{
"code": null,
"e": 29420,
"s": 29322,
"text": "So we get a value of arr[5] + arr[4] + maxSum[2], which is the final sum of state {i = 5, j = 4}."
},
{
"code": null,
"e": 29550,
"s": 29420,
"text": "We need to compare it with other {i and j} states (like {i = 5, j = 3}, {i = 5, j = 2}...) to get the final result for maxSum[5]."
},
{
"code": null,
"e": 29676,
"s": 29550,
"text": "Then save j into the before[5] if it precedes arr[5] and helps arr[5] form a valid subsequence with a maximum sum at state 5."
},
{
"code": null,
"e": 29737,
"s": 29676,
"text": "Take a look at the illustration below to get the idea clear."
},
{
"code": null,
"e": 29810,
"s": 29737,
"text": "index : 0 1 2 3 4 5 || N = 6arr[] : 1, 5, 7, 3, 4, 5"
},
{
"code": null,
"e": 29845,
"s": 29810,
"text": "—————————————————————————————————-"
},
{
"code": null,
"e": 29924,
"s": 29845,
"text": "maxSum[0] : 1 0 0 0 0 0 = 1 base casebefore[-1] : -1 _ _ _ _ _"
},
{
"code": null,
"e": 30007,
"s": 29924,
"text": "maxSum[1] : 1 6 0 0 0 0 = 6 because 1 + 5before[1] : -1 0 _ _ _ _"
},
{
"code": null,
"e": 30392,
"s": 30007,
"text": "maxSum[2] : 1 6 12 0 0 0 = 12 because 1, 5, 7 isn’t alternating subsequence, and just 5 & 7 before[2] : -1 0 1 _ _ _ is valid, we use backtracking at index 2 so we will go through the following subsequence: {1, 7}, {5, 7}. We have {5, 7} because before[1] is index 0, we continue to find value at before[before[1]] = -1, whose value is 0, so 0 + 5 + 7 = 12 > 1 + 7."
},
{
"code": null,
"e": 30567,
"s": 30392,
"text": "maxSum[3] : 1 6 12 15 0 0 = 15 because 5, 7, 3 is valid alternating subsequence, before[3] : -1 0 1 2 _ _ so 3 + max(maxSum[2], maxSum[1], maxSum[0]) = 3 + 12."
},
{
"code": null,
"e": 30748,
"s": 30567,
"text": "maxSum[4] : 1 6 12 15 19 0 = 19 because 5, 7, 3, 4 is valid alternating subsequence,before[4] : -1 0 1 2 3 _ so 4 + max(maxSum[3], maxSum[2],... maxSum[0]) = 4 + 15."
},
{
"code": null,
"e": 31395,
"s": 30748,
"text": "maxSum[5] : 1 6 12 15 19 21 = 21, arr[5] cannot be the next element of maxSum[4] because 3, 4, 5before[5] : -1 0 1 2 3 2 isn’t alternating subsequence. So we need use backtracking here. We will treat the value 3 as an invalid value for the alternating subsequence ending in arr[5]. We need to find the preceding element of before[arr[4]] in the sum of maxSum[4] recursively, that is index 2. Now 7, 4, 5 have formed a valid alternating subsequence. So we have 5 + max(backtracking(index 4), maxSum[3], maxSum[2],...) = 5 + 16 ( because 4 + 7 + 5)Then, final max sum of alternating subsequence of arr is max element of “maxSum” array."
},
{
"code": null,
"e": 31406,
"s": 31395,
"text": "Output: 21"
},
{
"code": null,
"e": 31457,
"s": 31406,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 31461,
"s": 31457,
"text": "C++"
},
{
"code": null,
"e": 31466,
"s": 31461,
"text": "Java"
},
{
"code": null,
"e": 31474,
"s": 31466,
"text": "Python3"
},
{
"code": null,
"e": 31477,
"s": 31474,
"text": "C#"
},
{
"code": null,
"e": 31488,
"s": 31477,
"text": "Javascript"
},
{
"code": "// C++ code to implement the above approach #include <bits/stdc++.h>using namespace std; // Function for backtrackingint backtracking(int arr[], int maxSum[], int before[], int N, int root, int bef_root, int bbef_root){ // {root, bef_root} represents state{i, j} // bbef_root represent before[before[j]] // We ignore the invalid before[j] index // Base case: if (bbef_root == -1) return arr[bef_root]; // The case of a subsequence with // alternating parts: if ((arr[root] > arr[bef_root] && arr[bbef_root] > arr[bef_root]) || (arr[root] < arr[bef_root] && arr[bbef_root] < arr[bef_root])) { return arr[bef_root] + maxSum[bbef_root]; } // case (arr[bef_root] == arr[bbef_root]) else { return backtracking(arr, maxSum, before, N, root, bef_root, before[bbef_root]); }} int maxSumAlternatingSubsequence(int arr[], int N){ // Max alternating subsequence sum // ending at arr[i]. int maxSum[N]; // Array to store the index of the element // preceding the last element at maxSum[i] int before[N]; // Value initialization for arrays: fill_n(&maxSum[0], N, 0); maxSum[0] = arr[0]; before[0] = -1; // Iterate over the array: for (int i = 1; i < N; i++) for (int j = 0; j < i; j++) { int currentMax = 0; if ((arr[i] > arr[j] && arr[before[j]] > arr[j]) || (arr[i] < arr[j] && arr[before[j]] < arr[j]) || before[j] == -1) { // Whenever an element is // between two smaller elements // or between two larger elements, // it is an alternating sequence. // When the preceding index of j is -1, // we need to treat it explicitly, // because -1 is not a valid index. currentMax = (arr[i] == arr[j]) ? maxSum[j] : arr[i] + maxSum[j]; } else if (arr[i] == arr[j]) { // If arr[i] is equal to arr[j] then // only take it once, // before[j] cannot be equal to -1. currentMax = maxSum[j]; } else { // Perform backtracking // If three adjacent elements // are increasing or decreasing. currentMax = arr[i] + backtracking( arr, maxSum, before, N, i, j, before[before[j]]); } if (currentMax >= maxSum[i]) { // Stores the maximum sum and // the index preceding // the last element // at position i of // current alternating subsequence // after each iteration. maxSum[i] = currentMax; before[i] = j; } } // get max result in array return *max_element(maxSum, maxSum + N);} // Driver codeint main(){ int arr[] = { 1, 5, 7, 3, 4, 5 }; int N = sizeof(arr) / sizeof(int); // Maximum sum of alternating subsequence // of array arr[] cout << maxSumAlternatingSubsequence(arr, N) << endl; return 0;}",
"e": 34895,
"s": 31488,
"text": null
},
{
"code": "// Java code to implement the above approachimport java.io.*; class GFG{ // Function for backtrackingstatic int backtracking(int arr[], int maxSum[], int before[], int N, int root, int bef_root, int bbef_root){ // {root, bef_root} represents state{i, j} // bbef_root represent before[before[j]] // We ignore the invalid before[j] index // Base case: if (bbef_root == -1) return arr[bef_root]; // The case of a subsequence with // alternating parts: if ((arr[root] > arr[bef_root] && arr[bbef_root] > arr[bef_root]) || (arr[root] < arr[bef_root] && arr[bbef_root] < arr[bef_root])) { return arr[bef_root] + maxSum[bbef_root]; } // case (arr[bef_root] == arr[bbef_root]) else { return backtracking(arr, maxSum, before, N, root, bef_root, before[bbef_root]); }} static int maxSumAlternatingSubsequence(int arr[], int N){ // Max alternating subsequence sum // ending at arr[i]. int maxSum[] = new int[N]; // Array to store the index of the element // preceding the last element at maxSum[i] int before[] = new int[N]; // Value initialization for arrays: maxSum[0] = arr[0]; before[0] = -1; // Iterate over the array: for(int i = 1; i < N; i++) for(int j = 0; j < i; j++) { int currentMax = 0; if ((arr[i] > arr[j] && before[j] != -1 && arr[before[j]] > arr[j]) || (arr[i] < arr[j] && before[j] != -1 && arr[before[j]] < arr[j]) || before[j] == -1) { // Whenever an element is // between two smaller elements // or between two larger elements, // it is an alternating sequence. // When the preceding index of j is -1, // we need to treat it explicitly, // because -1 is not a valid index. currentMax = (arr[i] == arr[j]) ? maxSum[j] : arr[i] + maxSum[j]; } else if (arr[i] == arr[j]) { // If arr[i] is equal to arr[j] then // only take it once, // before[j] cannot be equal to -1. currentMax = maxSum[j]; } else { // Perform backtracking // If three adjacent elements // are increasing or decreasing. currentMax = arr[i] + backtracking(arr, maxSum, before, N, i, j, before[before[j]]); } if (currentMax >= maxSum[i]) { // Stores the maximum sum and the index // preceding the last element at position // i of current alternating subsequence // after each iteration. maxSum[i] = currentMax; before[i] = j; } } // get max result in array int maxi = 0; for(int i = 0; i < N; i++) { maxi = Math.max(maxSum[i], maxi); } return maxi;} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 5, 7, 3, 4, 5 }; int N = arr.length; // Maximum sum of alternating subsequence // of array arr[] System.out.println( maxSumAlternatingSubsequence(arr, N));}} // This code is contributed by Potta Lokesh",
"e": 38556,
"s": 34895,
"text": null
},
{
"code": "# Python code to implement the above approach # Function for backtrackingdef backtracking(arr, maxSum, before, N, root, bef_root, bbef_root): # {root, bef_root} represents state{i, j} # bbef_root represent before[before[j]] # We ignore the invalid before[j] index # Base case: if (bbef_root == -1): return arr[bef_root] # The case of a subsequence with # alternating parts: if (arr[root] > arr[bef_root] and arr[bbef_root] > arr[bef_root]) or (arr[root] < arr[bef_root] and arr[bbef_root] < arr[bef_root]): return arr[bef_root] + maxSum[bbef_root] # case (arr[bef_root] == arr[bbef_root]) else: return backtracking(arr, maxSum, before, N, root, bef_root, before[bbef_root]) def maxSumAlternatingSubsequence(arr, N): # Max alternating subsequence sum # ending at arr[i]. maxSum = [0] * N # Array to store the index of the element # preceding the last element at maxSum[i] before = [0] * N # Value initialization for arrays: maxSum[0] = arr[0] before[0] = -1 # Iterate over the array: for i in range(N): for j in range(i): currentMax = 0 if (arr[i] > arr[j] and before[j] != -1 and arr[before[j]] > arr[j]) or (arr[i] < arr[j] and before[j] != -1 and arr[before[j]] < arr[j]) or before[j] == -1: # Whenever an element is # between two smaller elements # or between two larger elements, # it is an alternating sequence. # When the preceding index of j is -1, # we need to treat it explicitly, # because -1 is not a valid index. currentMax = maxSum[j] if ( arr[i] == arr[j]) else arr[i] + maxSum[j] elif (arr[i] == arr[j]): # If arr[i] is equal to arr[j] then # only take it once, # before[j] cannot be equal to -1. currentMax = maxSum[j] else: # Perform backtracking # If three adjacent elements # are increasing or decreasing. currentMax = arr[i] + backtracking(arr, maxSum, before, N, i, j, before[before[j]]) if (currentMax >= maxSum[i]): # Stores the maximum sum and the index # preceding the last element at position # i of current alternating subsequence # after each iteration. maxSum[i] = currentMax before[i] = j # get max result in array maxi = 0 for i in range(N): maxi = max(maxSum[i], maxi) return maxi # Driver codearr = [1, 5, 7, 3, 4, 5]N = len(arr) # Maximum sum of alternating subsequence# of array arrprint(maxSumAlternatingSubsequence(arr, N)) # This code is contributed by gfgking",
"e": 41539,
"s": 38556,
"text": null
},
{
"code": "// C# program for above approachusing System;class GFG{ // Function for backtrackingstatic int backtracking(int []arr, int []maxSum, int []before, int N, int root, int bef_root, int bbef_root){ // {root, bef_root} represents state{i, j} // bbef_root represent before[before[j]] // We ignore the invalid before[j] index // Base case: if (bbef_root == -1) return arr[bef_root]; // The case of a subsequence with // alternating parts: if ((arr[root] > arr[bef_root] && arr[bbef_root] > arr[bef_root]) || (arr[root] < arr[bef_root] && arr[bbef_root] < arr[bef_root])) { return arr[bef_root] + maxSum[bbef_root]; } // case (arr[bef_root] == arr[bbef_root]) else { return backtracking(arr, maxSum, before, N, root, bef_root, before[bbef_root]); }} static int maxSumAlternatingSubsequence(int []arr, int N){ // Max alternating subsequence sum // ending at arr[i]. int []maxSum = new int[N]; // Array to store the index of the element // preceding the last element at maxSum[i] int []before = new int[N]; // Value initialization for arrays: maxSum[0] = arr[0]; before[0] = -1; // Iterate over the array: for(int i = 1; i < N; i++) for(int j = 0; j < i; j++) { int currentMax = 0; if ((arr[i] > arr[j] && before[j] != -1 && arr[before[j]] > arr[j]) || (arr[i] < arr[j] && before[j] != -1 && arr[before[j]] < arr[j]) || before[j] == -1) { // Whenever an element is // between two smaller elements // or between two larger elements, // it is an alternating sequence. // When the preceding index of j is -1, // we need to treat it explicitly, // because -1 is not a valid index. currentMax = (arr[i] == arr[j]) ? maxSum[j] : arr[i] + maxSum[j]; } else if (arr[i] == arr[j]) { // If arr[i] is equal to arr[j] then // only take it once, // before[j] cannot be equal to -1. currentMax = maxSum[j]; } else { // Perform backtracking // If three adjacent elements // are increasing or decreasing. currentMax = arr[i] + backtracking(arr, maxSum, before, N, i, j, before[before[j]]); } if (currentMax >= maxSum[i]) { // Stores the maximum sum and the index // preceding the last element at position // i of current alternating subsequence // after each iteration. maxSum[i] = currentMax; before[i] = j; } } // get max result in array int maxi = 0; for(int i = 0; i < N; i++) { maxi = Math.Max(maxSum[i], maxi); } return maxi;} // Driver Codepublic static void Main(){ int []arr = { 1, 5, 7, 3, 4, 5 }; int N = arr.Length; // Maximum sum of alternating subsequence // of array arr[] Console.Write( maxSumAlternatingSubsequence(arr, N));}} // This code is contributed by Samim Hossain Mondal.",
"e": 45174,
"s": 41539,
"text": null
},
{
"code": "<script>// javascript code to implement the above approach // Function for backtrackingfunction backtracking(arr , maxSum, before , N , root, bef_root , bbef_root){ // {root, bef_root} represents state{i, j} // bbef_root represent before[before[j]] // We ignore the invalid before[j] index // Base case: if (bbef_root == -1) return arr[bef_root]; // The case of a subsequence with // alternating parts: if ((arr[root] > arr[bef_root] && arr[bbef_root] > arr[bef_root]) || (arr[root] < arr[bef_root] && arr[bbef_root] < arr[bef_root])) { return arr[bef_root] + maxSum[bbef_root]; } // case (arr[bef_root] == arr[bbef_root]) else { return backtracking(arr, maxSum, before, N, root, bef_root, before[bbef_root]); }} function maxSumAlternatingSubsequence(arr,N){ // Max alternating subsequence sum // ending at arr[i]. var maxSum = Array.from({length: N}, (_, i) => 0); // Array to store the index of the element // preceding the last element at maxSum[i] var before = Array.from({length: N}, (_, i) => 0); // Value initialization for arrays: maxSum[0] = arr[0]; before[0] = -1; // Iterate over the array: for(var i = 1; i < N; i++) for(var j = 0; j < i; j++) { var currentMax = 0; if ((arr[i] > arr[j] && before[j] != -1 && arr[before[j]] > arr[j]) || (arr[i] < arr[j] && before[j] != -1 && arr[before[j]] < arr[j]) || before[j] == -1) { // Whenever an element is // between two smaller elements // or between two larger elements, // it is an alternating sequence. // When the preceding index of j is -1, // we need to treat it explicitly, // because -1 is not a valid index. currentMax = (arr[i] == arr[j]) ? maxSum[j] : arr[i] + maxSum[j]; } else if (arr[i] == arr[j]) { // If arr[i] is equal to arr[j] then // only take it once, // before[j] cannot be equal to -1. currentMax = maxSum[j]; } else { // Perform backtracking // If three adjacent elements // are increasing or decreasing. currentMax = arr[i] + backtracking(arr, maxSum, before, N, i, j, before[before[j]]); } if (currentMax >= maxSum[i]) { // Stores the maximum sum and the index // preceding the last element at position // i of current alternating subsequence // after each iteration. maxSum[i] = currentMax; before[i] = j; } } // get max result in array var maxi = 0; for(var i = 0; i < N; i++) { maxi = Math.max(maxSum[i], maxi); } return maxi;} // Driver codevar arr = [ 1, 5, 7, 3, 4, 5 ];var N = arr.length; // Maximum sum of alternating subsequence// of array arrdocument.write(maxSumAlternatingSubsequence(arr, N)); // This code is contributed by 29AjayKumar</script>",
"e": 48670,
"s": 45174,
"text": null
},
{
"code": null,
"e": 48673,
"s": 48670,
"text": "21"
},
{
"code": null,
"e": 48753,
"s": 48673,
"text": "Time Complexity: O(N2) where N is the length of the array.Auxiliary Space: O(N)"
},
{
"code": null,
"e": 48769,
"s": 48755,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 48779,
"s": 48769,
"text": "samim2000"
},
{
"code": null,
"e": 48791,
"s": 48779,
"text": "29AjayKumar"
},
{
"code": null,
"e": 48799,
"s": 48791,
"text": "gfgking"
},
{
"code": null,
"e": 48814,
"s": 48799,
"text": "adnanirshad158"
},
{
"code": null,
"e": 48826,
"s": 48814,
"text": "subsequence"
},
{
"code": null,
"e": 48833,
"s": 48826,
"text": "Arrays"
},
{
"code": null,
"e": 48846,
"s": 48833,
"text": "Backtracking"
},
{
"code": null,
"e": 48866,
"s": 48846,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 48884,
"s": 48866,
"text": "Pattern Searching"
},
{
"code": null,
"e": 48891,
"s": 48884,
"text": "Arrays"
},
{
"code": null,
"e": 48911,
"s": 48891,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 48924,
"s": 48911,
"text": "Backtracking"
},
{
"code": null,
"e": 48942,
"s": 48924,
"text": "Pattern Searching"
},
{
"code": null,
"e": 49040,
"s": 48942,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 49065,
"s": 49040,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 49085,
"s": 49065,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 49123,
"s": 49085,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 49208,
"s": 49123,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 49257,
"s": 49208,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 49290,
"s": 49257,
"text": "N Queen Problem | Backtracking-3"
},
{
"code": null,
"e": 49350,
"s": 49290,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 49381,
"s": 49350,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 49424,
"s": 49381,
"text": "The Knight's tour problem | Backtracking-1"
}
] |
Visualizing intermediate activation in Convolutional Neural Networks with Keras | by Gabriel Pierobon | Towards Data Science | In this article we’re going to train a simple Convolutional Neural Network using Keras with Python for a classification task. For that we will use a very small and simple set of images consisting of 100 pictures of circle drawings, 100 pictures of squares and 100 pictures of triangles which I found here in Kaggle. These will be split into training and testing sets (folders in working directory) and fed to the network.
Most importantly, we are going to replicate some of the work of François Chollet in his book Deep Learning with Python in order to learn how our layer structure processes the data in terms of visualization of each intermediate activation, which consists of displaying the feature maps that are output by the convolution and pooling layers in the network.
What this means is that we are going to visualize the result of each activation layer.
We’ll go super fast since we are not focusing here on doing a detailed explanation of CNNs with Keras.
Let’s first import all our required libraries:
%matplotlib inlineimport globimport matplotlibfrom matplotlib import pyplot as pltimport matplotlib.image as mpimgimport numpy as npimport imageio as imfrom keras import modelsfrom keras.models import Sequentialfrom keras.layers import Conv2Dfrom keras.layers import MaxPooling2Dfrom keras.layers import Flattenfrom keras.layers import Densefrom keras.layers import Dropoutfrom keras.preprocessing import imagefrom keras.preprocessing.image import ImageDataGeneratorfrom keras.callbacks import ModelCheckpoint
These are our training images:
images = []for img_path in glob.glob('training_set/circles/*.png'): images.append(mpimg.imread(img_path))plt.figure(figsize=(20,10))columns = 5for i, image in enumerate(images): plt.subplot(len(images) / columns + 1, columns, i + 1) plt.imshow(image)
(code is pretty much same as above, see full code here)
Images shapes are of 28 pixels by 28 pixels in RGB scale (although they are arguably black and white only).
Let’s now proceed with our Convolutional Neural Network construction. As usually, we initiate the model with Sequential():
# Initialising the CNNclassifier = Sequential()
We specify our convolution layers and add MaxPooling to downsample and Dropout to prevent overfitting. We use Flatten and end with a Dense layer of 3 units, one for each class (circle [0], square [1], triangle [1]). We specify softmax as our last activation function, which is suggested for multiclass classification.
# Step 1 - Convolutionclassifier.add(Conv2D(32, (3, 3), padding='same', input_shape = (28, 28, 3), activation = 'relu'))classifier.add(Conv2D(32, (3, 3), activation='relu'))classifier.add(MaxPooling2D(pool_size=(2, 2)))classifier.add(Dropout(0.5)) # antes era 0.25# Adding a second convolutional layerclassifier.add(Conv2D(64, (3, 3), padding='same', activation = 'relu'))classifier.add(Conv2D(64, (3, 3), activation='relu'))classifier.add(MaxPooling2D(pool_size=(2, 2)))classifier.add(Dropout(0.5)) # antes era 0.25# Adding a third convolutional layerclassifier.add(Conv2D(64, (3, 3), padding='same', activation = 'relu'))classifier.add(Conv2D(64, (3, 3), activation='relu'))classifier.add(MaxPooling2D(pool_size=(2, 2)))classifier.add(Dropout(0.5)) # antes era 0.25# Step 3 - Flatteningclassifier.add(Flatten())# Step 4 - Full connectionclassifier.add(Dense(units = 512, activation = 'relu'))classifier.add(Dropout(0.5)) classifier.add(Dense(units = 3, activation = 'softmax'))
For this type of images, I might be building an overly complex structure, and it will be evident once we take a look at the feature maps, however, for the sake of this article, it helps me to showcase exactly what each layer will be doing. I’m certain we can obtain the same or better results with less layers and less complexity.
Let’s take a look at our model summary:
classifier.summary()
We compile the model utilizing rmsprop as our optimizer, categorical_crossentropy as our loss function and we specify accuracy as the metric we want to keep track of:
# Compiling the CNNclassifier.compile(optimizer = 'rmsprop', loss = 'categorical_crossentropy', metrics = ['accuracy'])
At this point we need to convert our pictures to a shape that the model will accept. For that we use the ImageDataGenerator. We initiate it and feed our images with .flow_from_directory. There are two main folders inside the working directory, called training_set and test_set. Each of those have 3 subfolders called circles, squares and triangles. I have sent 70 images of each shape to the training_set and 30 to the test_set.
train_datagen = ImageDataGenerator(rescale = 1./255)test_datagen = ImageDataGenerator(rescale = 1./255)training_set = train_datagen.flow_from_directory('training_set', target_size = (28, 28), batch_size = 16, class_mode = 'categorical')test_set = test_datagen.flow_from_directory('test_set', target_size = (28, 28), batch_size = 16, class_mode = 'categorical')
The model will train for 30 epochs but we will use ModelCheckpoint to store the weights of the best performing epoch. We will specify val_acc as the metric to use to define the best model. This means we will keep the weights of the epoch that scores highest in terms of accuracy on the test set.
checkpointer = ModelCheckpoint(filepath="best_weights.hdf5", monitor = 'val_acc', verbose=1, save_best_only=True)
Now it’s time to train the model, here we include the callback to our checkpointer
history = classifier.fit_generator(training_set, steps_per_epoch = 100, epochs = 20, callbacks=[checkpointer], validation_data = test_set, validation_steps = 50)
The model trains for 20 epochs and reaches it’s best performance at epoch 10. We get the following message:
`Epoch 00010: val_acc improved from 0.93333 to 0.95556, saving model to best_weights.hdf5`
After that, the model does not improve for the next epochs so the weights of epoch 10 are the ones stored- That means we have now an hdf5 file which stores the weights of that specific epoch, where the accuracy over the test set was of 95,6%
We will make sure our classifier is loaded with the best weights with this
classifier.load_weights('best_weights.hdf5')
And finally, let’s save the final model for usage later:
classifier.save('shapes_cnn.h5')
Let’s now inspect how our model performed over the 30 epochs:
acc = history.history['acc']val_acc = history.history['val_acc']loss = history.history['loss']val_loss = history.history['val_loss']epochs = range(1, len(acc) + 1)plt.plot(epochs, acc, 'bo', label='Training acc')plt.plot(epochs, val_acc, 'b', label='Validation acc')plt.title('Training and validation accuracy')plt.legend()plt.figure()plt.plot(epochs, loss, 'bo', label='Training loss')plt.plot(epochs, val_loss, 'b', label='Validation loss')plt.title('Training and validation loss')plt.legend()plt.show()
We can see that after epoch 10 the model starts overfitting. Regardless, we kept the results of epoch which had the best performance.
Let’s clarify now the class number assigned to each of our figures set, since that is how the model will produce it’s predictions:
circles: 0squres: 1triangles: 2
With our model trained and stored, we can load a simple unseen image from our test set and see how it is classified:
img_path = 'test_set/triangles/drawing(2).png'img = image.load_img(img_path, target_size=(28, 28))img_tensor = image.img_to_array(img)img_tensor = np.expand_dims(img_tensor, axis=0)img_tensor /= 255.plt.imshow(img_tensor[0])plt.show()print(img_tensor.shape)
# predicting imagesx = image.img_to_array(img)x = np.expand_dims(x, axis=0)images = np.vstack([x])classes = classifier.predict_classes(images, batch_size=10)print("Predicted class is:",classes)> Predicted class is: [2]
The prediction is class [2] which is a triangle.
So far so good. We now proceed to the most important part of this articl
Quoting François Chollet in his book “DEEP LEARNING with Python” (and I’ll quote him a lot in this section):
Intermediate activations are “useful for understanding how successive convnet layers transform their input, and for getting a first idea of the meaning of individual convnet filters.”
“The representations learned by convnets are highly amenable to visualization, in large part because they’re representations of visual concepts. Visualizing intermediate activations consists of displaying the feature maps that are output by various convolution and pooling layers in a network, given a certain input (the output of a layer is often called its activation, the output of the activation function). This gives a view into how an input is decomposed into the different filters learned by the network. Each channel encodes relatively independent features, so the proper way to visualize these feature maps is by independently plotting the contents of every channel as a 2D image.”
Next, we’ll get an input image — a picture of a triangle, not part of the images the network was trained on.
“In order to extract the feature maps we want to look at, we’ll create a Keras model that takes batches of images as input, and outputs the activations of all convolution and pooling layers. To do this, we’ll use the Keras class Model. A model is instantiated using two arguments: an input tensor (or list of input tensors) and an output tensor (or list of output tensors). The resulting class is a Keras model, just like the Sequential models, mapping the specified inputs to the specified outputs. What sets the Model class apart is that it allows for models with multiple outputs, unlike Sequential.”
layer_outputs = [layer.output for layer in classifier.layers[:12]] # Extracts the outputs of the top 12 layersactivation_model = models.Model(inputs=classifier.input, outputs=layer_outputs) # Creates a model that will return these outputs, given the model input
When fed an image input, this model returns the values of the layer activations in the original model.
activations = activation_model.predict(img_tensor) # Returns a list of five Numpy arrays: one array per layer activation
For instance, this is the activation of the first convolution layer for the image input:
first_layer_activation = activations[0]print(first_layer_activation.shape)(1, 28, 28, 32)
It’s a 28 × 28 feature map with 32 channels. Let’s try plotting the fourth channel of the activation of the first layer of the original model
plt.matshow(first_layer_activation[0, :, :, 4], cmap='viridis')
Even before we try to interpret this activation, let’s instead plot all the activations of this same image across each layer
The full code of this section can be found here
So here it is! Let’s try to interpret what’s going on:
The first layer is arguably retaining the full shape of the triangle, although there are several filters that are not activated and are left blank. At that stage, the activations retain almost all of the information present in the initial picture.
As we go deeper in the layers, the activations become increasingly abstract and less visually interpretable. They begin to encode higher-level concepts such as single borders, corners and angles. Higher presentations carry increasingly less information about the visual contents of the image, and increasingly more information related to the class of the image.
As mentioned above, the model stucture is overly complex to the point where we can see our last layers actually not activating at all, there’s nothing more to learn at that point.
So this is it! We have visualized how a convolutional neural network finds patterns in some basic figures and how it carries the information from one layer to anotherone.
Full code here. | [
{
"code": null,
"e": 468,
"s": 46,
"text": "In this article we’re going to train a simple Convolutional Neural Network using Keras with Python for a classification task. For that we will use a very small and simple set of images consisting of 100 pictures of circle drawings, 100 pictures of squares and 100 pictures of triangles which I found here in Kaggle. These will be split into training and testing sets (folders in working directory) and fed to the network."
},
{
"code": null,
"e": 824,
"s": 468,
"text": "Most importantly, we are going to replicate some of the work of François Chollet in his book Deep Learning with Python in order to learn how our layer structure processes the data in terms of visualization of each intermediate activation, which consists of displaying the feature maps that are output by the convolution and pooling layers in the network."
},
{
"code": null,
"e": 911,
"s": 824,
"text": "What this means is that we are going to visualize the result of each activation layer."
},
{
"code": null,
"e": 1014,
"s": 911,
"text": "We’ll go super fast since we are not focusing here on doing a detailed explanation of CNNs with Keras."
},
{
"code": null,
"e": 1061,
"s": 1014,
"text": "Let’s first import all our required libraries:"
},
{
"code": null,
"e": 1571,
"s": 1061,
"text": "%matplotlib inlineimport globimport matplotlibfrom matplotlib import pyplot as pltimport matplotlib.image as mpimgimport numpy as npimport imageio as imfrom keras import modelsfrom keras.models import Sequentialfrom keras.layers import Conv2Dfrom keras.layers import MaxPooling2Dfrom keras.layers import Flattenfrom keras.layers import Densefrom keras.layers import Dropoutfrom keras.preprocessing import imagefrom keras.preprocessing.image import ImageDataGeneratorfrom keras.callbacks import ModelCheckpoint"
},
{
"code": null,
"e": 1602,
"s": 1571,
"text": "These are our training images:"
},
{
"code": null,
"e": 1862,
"s": 1602,
"text": "images = []for img_path in glob.glob('training_set/circles/*.png'): images.append(mpimg.imread(img_path))plt.figure(figsize=(20,10))columns = 5for i, image in enumerate(images): plt.subplot(len(images) / columns + 1, columns, i + 1) plt.imshow(image)"
},
{
"code": null,
"e": 1918,
"s": 1862,
"text": "(code is pretty much same as above, see full code here)"
},
{
"code": null,
"e": 2026,
"s": 1918,
"text": "Images shapes are of 28 pixels by 28 pixels in RGB scale (although they are arguably black and white only)."
},
{
"code": null,
"e": 2149,
"s": 2026,
"text": "Let’s now proceed with our Convolutional Neural Network construction. As usually, we initiate the model with Sequential():"
},
{
"code": null,
"e": 2197,
"s": 2149,
"text": "# Initialising the CNNclassifier = Sequential()"
},
{
"code": null,
"e": 2515,
"s": 2197,
"text": "We specify our convolution layers and add MaxPooling to downsample and Dropout to prevent overfitting. We use Flatten and end with a Dense layer of 3 units, one for each class (circle [0], square [1], triangle [1]). We specify softmax as our last activation function, which is suggested for multiclass classification."
},
{
"code": null,
"e": 3495,
"s": 2515,
"text": "# Step 1 - Convolutionclassifier.add(Conv2D(32, (3, 3), padding='same', input_shape = (28, 28, 3), activation = 'relu'))classifier.add(Conv2D(32, (3, 3), activation='relu'))classifier.add(MaxPooling2D(pool_size=(2, 2)))classifier.add(Dropout(0.5)) # antes era 0.25# Adding a second convolutional layerclassifier.add(Conv2D(64, (3, 3), padding='same', activation = 'relu'))classifier.add(Conv2D(64, (3, 3), activation='relu'))classifier.add(MaxPooling2D(pool_size=(2, 2)))classifier.add(Dropout(0.5)) # antes era 0.25# Adding a third convolutional layerclassifier.add(Conv2D(64, (3, 3), padding='same', activation = 'relu'))classifier.add(Conv2D(64, (3, 3), activation='relu'))classifier.add(MaxPooling2D(pool_size=(2, 2)))classifier.add(Dropout(0.5)) # antes era 0.25# Step 3 - Flatteningclassifier.add(Flatten())# Step 4 - Full connectionclassifier.add(Dense(units = 512, activation = 'relu'))classifier.add(Dropout(0.5)) classifier.add(Dense(units = 3, activation = 'softmax'))"
},
{
"code": null,
"e": 3826,
"s": 3495,
"text": "For this type of images, I might be building an overly complex structure, and it will be evident once we take a look at the feature maps, however, for the sake of this article, it helps me to showcase exactly what each layer will be doing. I’m certain we can obtain the same or better results with less layers and less complexity."
},
{
"code": null,
"e": 3866,
"s": 3826,
"text": "Let’s take a look at our model summary:"
},
{
"code": null,
"e": 3887,
"s": 3866,
"text": "classifier.summary()"
},
{
"code": null,
"e": 4054,
"s": 3887,
"text": "We compile the model utilizing rmsprop as our optimizer, categorical_crossentropy as our loss function and we specify accuracy as the metric we want to keep track of:"
},
{
"code": null,
"e": 4211,
"s": 4054,
"text": "# Compiling the CNNclassifier.compile(optimizer = 'rmsprop', loss = 'categorical_crossentropy', metrics = ['accuracy'])"
},
{
"code": null,
"e": 4640,
"s": 4211,
"text": "At this point we need to convert our pictures to a shape that the model will accept. For that we use the ImageDataGenerator. We initiate it and feed our images with .flow_from_directory. There are two main folders inside the working directory, called training_set and test_set. Each of those have 3 subfolders called circles, squares and triangles. I have sent 70 images of each shape to the training_set and 30 to the test_set."
},
{
"code": null,
"e": 5422,
"s": 4640,
"text": "train_datagen = ImageDataGenerator(rescale = 1./255)test_datagen = ImageDataGenerator(rescale = 1./255)training_set = train_datagen.flow_from_directory('training_set', target_size = (28, 28), batch_size = 16, class_mode = 'categorical')test_set = test_datagen.flow_from_directory('test_set', target_size = (28, 28), batch_size = 16, class_mode = 'categorical')"
},
{
"code": null,
"e": 5718,
"s": 5422,
"text": "The model will train for 30 epochs but we will use ModelCheckpoint to store the weights of the best performing epoch. We will specify val_acc as the metric to use to define the best model. This means we will keep the weights of the epoch that scores highest in terms of accuracy on the test set."
},
{
"code": null,
"e": 5924,
"s": 5718,
"text": "checkpointer = ModelCheckpoint(filepath=\"best_weights.hdf5\", monitor = 'val_acc', verbose=1, save_best_only=True)"
},
{
"code": null,
"e": 6007,
"s": 5924,
"text": "Now it’s time to train the model, here we include the callback to our checkpointer"
},
{
"code": null,
"e": 6339,
"s": 6007,
"text": "history = classifier.fit_generator(training_set, steps_per_epoch = 100, epochs = 20, callbacks=[checkpointer], validation_data = test_set, validation_steps = 50)"
},
{
"code": null,
"e": 6447,
"s": 6339,
"text": "The model trains for 20 epochs and reaches it’s best performance at epoch 10. We get the following message:"
},
{
"code": null,
"e": 6538,
"s": 6447,
"text": "`Epoch 00010: val_acc improved from 0.93333 to 0.95556, saving model to best_weights.hdf5`"
},
{
"code": null,
"e": 6780,
"s": 6538,
"text": "After that, the model does not improve for the next epochs so the weights of epoch 10 are the ones stored- That means we have now an hdf5 file which stores the weights of that specific epoch, where the accuracy over the test set was of 95,6%"
},
{
"code": null,
"e": 6855,
"s": 6780,
"text": "We will make sure our classifier is loaded with the best weights with this"
},
{
"code": null,
"e": 6900,
"s": 6855,
"text": "classifier.load_weights('best_weights.hdf5')"
},
{
"code": null,
"e": 6957,
"s": 6900,
"text": "And finally, let’s save the final model for usage later:"
},
{
"code": null,
"e": 6990,
"s": 6957,
"text": "classifier.save('shapes_cnn.h5')"
},
{
"code": null,
"e": 7052,
"s": 6990,
"text": "Let’s now inspect how our model performed over the 30 epochs:"
},
{
"code": null,
"e": 7558,
"s": 7052,
"text": "acc = history.history['acc']val_acc = history.history['val_acc']loss = history.history['loss']val_loss = history.history['val_loss']epochs = range(1, len(acc) + 1)plt.plot(epochs, acc, 'bo', label='Training acc')plt.plot(epochs, val_acc, 'b', label='Validation acc')plt.title('Training and validation accuracy')plt.legend()plt.figure()plt.plot(epochs, loss, 'bo', label='Training loss')plt.plot(epochs, val_loss, 'b', label='Validation loss')plt.title('Training and validation loss')plt.legend()plt.show()"
},
{
"code": null,
"e": 7692,
"s": 7558,
"text": "We can see that after epoch 10 the model starts overfitting. Regardless, we kept the results of epoch which had the best performance."
},
{
"code": null,
"e": 7823,
"s": 7692,
"text": "Let’s clarify now the class number assigned to each of our figures set, since that is how the model will produce it’s predictions:"
},
{
"code": null,
"e": 7855,
"s": 7823,
"text": "circles: 0squres: 1triangles: 2"
},
{
"code": null,
"e": 7972,
"s": 7855,
"text": "With our model trained and stored, we can load a simple unseen image from our test set and see how it is classified:"
},
{
"code": null,
"e": 8230,
"s": 7972,
"text": "img_path = 'test_set/triangles/drawing(2).png'img = image.load_img(img_path, target_size=(28, 28))img_tensor = image.img_to_array(img)img_tensor = np.expand_dims(img_tensor, axis=0)img_tensor /= 255.plt.imshow(img_tensor[0])plt.show()print(img_tensor.shape)"
},
{
"code": null,
"e": 8449,
"s": 8230,
"text": "# predicting imagesx = image.img_to_array(img)x = np.expand_dims(x, axis=0)images = np.vstack([x])classes = classifier.predict_classes(images, batch_size=10)print(\"Predicted class is:\",classes)> Predicted class is: [2]"
},
{
"code": null,
"e": 8498,
"s": 8449,
"text": "The prediction is class [2] which is a triangle."
},
{
"code": null,
"e": 8571,
"s": 8498,
"text": "So far so good. We now proceed to the most important part of this articl"
},
{
"code": null,
"e": 8681,
"s": 8571,
"text": "Quoting François Chollet in his book “DEEP LEARNING with Python” (and I’ll quote him a lot in this section):"
},
{
"code": null,
"e": 8865,
"s": 8681,
"text": "Intermediate activations are “useful for understanding how successive convnet layers transform their input, and for getting a first idea of the meaning of individual convnet filters.”"
},
{
"code": null,
"e": 9556,
"s": 8865,
"text": "“The representations learned by convnets are highly amenable to visualization, in large part because they’re representations of visual concepts. Visualizing intermediate activations consists of displaying the feature maps that are output by various convolution and pooling layers in a network, given a certain input (the output of a layer is often called its activation, the output of the activation function). This gives a view into how an input is decomposed into the different filters learned by the network. Each channel encodes relatively independent features, so the proper way to visualize these feature maps is by independently plotting the contents of every channel as a 2D image.”"
},
{
"code": null,
"e": 9665,
"s": 9556,
"text": "Next, we’ll get an input image — a picture of a triangle, not part of the images the network was trained on."
},
{
"code": null,
"e": 10269,
"s": 9665,
"text": "“In order to extract the feature maps we want to look at, we’ll create a Keras model that takes batches of images as input, and outputs the activations of all convolution and pooling layers. To do this, we’ll use the Keras class Model. A model is instantiated using two arguments: an input tensor (or list of input tensors) and an output tensor (or list of output tensors). The resulting class is a Keras model, just like the Sequential models, mapping the specified inputs to the specified outputs. What sets the Model class apart is that it allows for models with multiple outputs, unlike Sequential.”"
},
{
"code": null,
"e": 10531,
"s": 10269,
"text": "layer_outputs = [layer.output for layer in classifier.layers[:12]] # Extracts the outputs of the top 12 layersactivation_model = models.Model(inputs=classifier.input, outputs=layer_outputs) # Creates a model that will return these outputs, given the model input"
},
{
"code": null,
"e": 10634,
"s": 10531,
"text": "When fed an image input, this model returns the values of the layer activations in the original model."
},
{
"code": null,
"e": 10755,
"s": 10634,
"text": "activations = activation_model.predict(img_tensor) # Returns a list of five Numpy arrays: one array per layer activation"
},
{
"code": null,
"e": 10844,
"s": 10755,
"text": "For instance, this is the activation of the first convolution layer for the image input:"
},
{
"code": null,
"e": 10934,
"s": 10844,
"text": "first_layer_activation = activations[0]print(first_layer_activation.shape)(1, 28, 28, 32)"
},
{
"code": null,
"e": 11076,
"s": 10934,
"text": "It’s a 28 × 28 feature map with 32 channels. Let’s try plotting the fourth channel of the activation of the first layer of the original model"
},
{
"code": null,
"e": 11140,
"s": 11076,
"text": "plt.matshow(first_layer_activation[0, :, :, 4], cmap='viridis')"
},
{
"code": null,
"e": 11265,
"s": 11140,
"text": "Even before we try to interpret this activation, let’s instead plot all the activations of this same image across each layer"
},
{
"code": null,
"e": 11313,
"s": 11265,
"text": "The full code of this section can be found here"
},
{
"code": null,
"e": 11368,
"s": 11313,
"text": "So here it is! Let’s try to interpret what’s going on:"
},
{
"code": null,
"e": 11616,
"s": 11368,
"text": "The first layer is arguably retaining the full shape of the triangle, although there are several filters that are not activated and are left blank. At that stage, the activations retain almost all of the information present in the initial picture."
},
{
"code": null,
"e": 11978,
"s": 11616,
"text": "As we go deeper in the layers, the activations become increasingly abstract and less visually interpretable. They begin to encode higher-level concepts such as single borders, corners and angles. Higher presentations carry increasingly less information about the visual contents of the image, and increasingly more information related to the class of the image."
},
{
"code": null,
"e": 12158,
"s": 11978,
"text": "As mentioned above, the model stucture is overly complex to the point where we can see our last layers actually not activating at all, there’s nothing more to learn at that point."
},
{
"code": null,
"e": 12329,
"s": 12158,
"text": "So this is it! We have visualized how a convolutional neural network finds patterns in some basic figures and how it carries the information from one layer to anotherone."
}
] |
How To Encode And Decode A Message using Python? - GeeksforGeeks | 01 Oct, 2020
Encryption is the process of converting a normal message (plain text) into a meaningless message (Ciphertext). Whereas, Decryption is the process of converting a meaningless message (Cipher text) into its original form (Plain text). In this article, we will take forward the idea of encryption and decryption and draft a python program.
In this article, we will be given a single-line message as input it is either encoded or decoded as per requirement and the resultant message is printed as output. Here, the conversion has been done by replacing A to Z, B to Y, ... Z to A. The case of the characters, numbers, spaces, and special characters present in the message is being kept unchanged.
Sample Example 1:
Encryption
Input : Hello World
Output : Svool Dliow
Explanation: (Reference- conversion table)
H is replaced with S
e is replaced with v
l is replaced with o
W is replaced with D
r is replaced with i
Decryption
Input : Svool Dliow
Output : Hello World
Explanation: (Reference- conversion table)
S is replaced with H
v is replaced with e
o is replaced with l
D is replaced with W
i is replaced with r
Sample Example 2:
Encryption
Input : GeeksForGeeks
Output : TvvphUliTvvph
Explanation: (Reference- conversion table)
G is replaced with T
e is replaced with v
k is replaced with p
s is replaced with h
F is replaced with U
o is replaced with l
r is replaced with i
Decryption
Input : TvvphUliTvvph
Output : GeeksForGeeks
Explanation: (Reference- conversion table)
T is replaced with G
v is replaced with e
p is replaced with k
h is replaced with s
U is replaced with F
l is replaced with o
i is replaced with r
Below is the implementation.
Python3
# Taking input from userdata = 'Welcome to GeeksForGeeks...' # conversion Chartconversion_code = { # Uppercase Alphabets 'A': 'Z', 'B': 'Y', 'C': 'X', 'D': 'W', 'E': 'V', 'F': 'U', 'G': 'T', 'H': 'S', 'I': 'R', 'J': 'Q', 'K': 'P', 'L': 'O', 'M': 'N', 'N': 'M', 'O': 'L', 'P': 'K', 'Q': 'J', 'R': 'I', 'S': 'H', 'T': 'G', 'U': 'F', 'V': 'E', 'W': 'D', 'X': 'C', 'Y': 'B', 'Z': 'A', # Lowercase Alphabets 'a': 'z', 'b': 'y', 'c': 'x', 'd': 'w', 'e': 'v', 'f': 'u', 'g': 't', 'h': 's', 'i': 'r', 'j': 'q', 'k': 'p', 'l': 'o', 'm': 'n', 'n': 'm', 'o': 'l', 'p': 'k', 'q': 'j', 'r': 'i', 's': 'h', 't': 'g', 'u': 'F', 'v': 'e', 'w': 'd', 'x': 'c', 'y': 'b', 'z': 'a'} # Creating converted outputconverted_data = "" for i in range(0, len(data)): if data[i] in conversion_code.keys(): converted_data += conversion_code[data[i]] else: converted_data += data[i] # Printing converted outputprint(converted_data)
Dvoxlnv gl TvvphUliTvvph...
cryptography
Python
cryptography
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24316,
"s": 24288,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 24653,
"s": 24316,
"text": "Encryption is the process of converting a normal message (plain text) into a meaningless message (Ciphertext). Whereas, Decryption is the process of converting a meaningless message (Cipher text) into its original form (Plain text). In this article, we will take forward the idea of encryption and decryption and draft a python program."
},
{
"code": null,
"e": 25009,
"s": 24653,
"text": "In this article, we will be given a single-line message as input it is either encoded or decoded as per requirement and the resultant message is printed as output. Here, the conversion has been done by replacing A to Z, B to Y, ... Z to A. The case of the characters, numbers, spaces, and special characters present in the message is being kept unchanged."
},
{
"code": null,
"e": 25027,
"s": 25009,
"text": "Sample Example 1:"
},
{
"code": null,
"e": 25038,
"s": 25027,
"text": "Encryption"
},
{
"code": null,
"e": 25080,
"s": 25038,
"text": "Input : Hello World\nOutput : Svool Dliow\n"
},
{
"code": null,
"e": 25123,
"s": 25080,
"text": "Explanation: (Reference- conversion table)"
},
{
"code": null,
"e": 25144,
"s": 25123,
"text": "H is replaced with S"
},
{
"code": null,
"e": 25165,
"s": 25144,
"text": "e is replaced with v"
},
{
"code": null,
"e": 25186,
"s": 25165,
"text": "l is replaced with o"
},
{
"code": null,
"e": 25207,
"s": 25186,
"text": "W is replaced with D"
},
{
"code": null,
"e": 25228,
"s": 25207,
"text": "r is replaced with i"
},
{
"code": null,
"e": 25239,
"s": 25228,
"text": "Decryption"
},
{
"code": null,
"e": 25283,
"s": 25239,
"text": "Input : Svool Dliow \nOutput : Hello World \n"
},
{
"code": null,
"e": 25326,
"s": 25283,
"text": "Explanation: (Reference- conversion table)"
},
{
"code": null,
"e": 25347,
"s": 25326,
"text": "S is replaced with H"
},
{
"code": null,
"e": 25368,
"s": 25347,
"text": "v is replaced with e"
},
{
"code": null,
"e": 25389,
"s": 25368,
"text": "o is replaced with l"
},
{
"code": null,
"e": 25410,
"s": 25389,
"text": "D is replaced with W"
},
{
"code": null,
"e": 25431,
"s": 25410,
"text": "i is replaced with r"
},
{
"code": null,
"e": 25449,
"s": 25431,
"text": "Sample Example 2:"
},
{
"code": null,
"e": 25460,
"s": 25449,
"text": "Encryption"
},
{
"code": null,
"e": 25506,
"s": 25460,
"text": "Input : GeeksForGeeks\nOutput : TvvphUliTvvph\n"
},
{
"code": null,
"e": 25549,
"s": 25506,
"text": "Explanation: (Reference- conversion table)"
},
{
"code": null,
"e": 25570,
"s": 25549,
"text": "G is replaced with T"
},
{
"code": null,
"e": 25591,
"s": 25570,
"text": "e is replaced with v"
},
{
"code": null,
"e": 25612,
"s": 25591,
"text": "k is replaced with p"
},
{
"code": null,
"e": 25633,
"s": 25612,
"text": "s is replaced with h"
},
{
"code": null,
"e": 25654,
"s": 25633,
"text": "F is replaced with U"
},
{
"code": null,
"e": 25675,
"s": 25654,
"text": "o is replaced with l"
},
{
"code": null,
"e": 25696,
"s": 25675,
"text": "r is replaced with i"
},
{
"code": null,
"e": 25707,
"s": 25696,
"text": "Decryption"
},
{
"code": null,
"e": 25754,
"s": 25707,
"text": "Input : TvvphUliTvvph \nOutput : GeeksForGeeks\n"
},
{
"code": null,
"e": 25797,
"s": 25754,
"text": "Explanation: (Reference- conversion table)"
},
{
"code": null,
"e": 25818,
"s": 25797,
"text": "T is replaced with G"
},
{
"code": null,
"e": 25839,
"s": 25818,
"text": "v is replaced with e"
},
{
"code": null,
"e": 25860,
"s": 25839,
"text": "p is replaced with k"
},
{
"code": null,
"e": 25881,
"s": 25860,
"text": "h is replaced with s"
},
{
"code": null,
"e": 25902,
"s": 25881,
"text": "U is replaced with F"
},
{
"code": null,
"e": 25923,
"s": 25902,
"text": "l is replaced with o"
},
{
"code": null,
"e": 25944,
"s": 25923,
"text": "i is replaced with r"
},
{
"code": null,
"e": 25973,
"s": 25944,
"text": "Below is the implementation."
},
{
"code": null,
"e": 25981,
"s": 25973,
"text": "Python3"
},
{
"code": "# Taking input from userdata = 'Welcome to GeeksForGeeks...' # conversion Chartconversion_code = { # Uppercase Alphabets 'A': 'Z', 'B': 'Y', 'C': 'X', 'D': 'W', 'E': 'V', 'F': 'U', 'G': 'T', 'H': 'S', 'I': 'R', 'J': 'Q', 'K': 'P', 'L': 'O', 'M': 'N', 'N': 'M', 'O': 'L', 'P': 'K', 'Q': 'J', 'R': 'I', 'S': 'H', 'T': 'G', 'U': 'F', 'V': 'E', 'W': 'D', 'X': 'C', 'Y': 'B', 'Z': 'A', # Lowercase Alphabets 'a': 'z', 'b': 'y', 'c': 'x', 'd': 'w', 'e': 'v', 'f': 'u', 'g': 't', 'h': 's', 'i': 'r', 'j': 'q', 'k': 'p', 'l': 'o', 'm': 'n', 'n': 'm', 'o': 'l', 'p': 'k', 'q': 'j', 'r': 'i', 's': 'h', 't': 'g', 'u': 'F', 'v': 'e', 'w': 'd', 'x': 'c', 'y': 'b', 'z': 'a'} # Creating converted outputconverted_data = \"\" for i in range(0, len(data)): if data[i] in conversion_code.keys(): converted_data += conversion_code[data[i]] else: converted_data += data[i] # Printing converted outputprint(converted_data)",
"e": 26953,
"s": 25981,
"text": null
},
{
"code": null,
"e": 26982,
"s": 26953,
"text": "Dvoxlnv gl TvvphUliTvvph...\n"
},
{
"code": null,
"e": 26995,
"s": 26982,
"text": "cryptography"
},
{
"code": null,
"e": 27002,
"s": 26995,
"text": "Python"
},
{
"code": null,
"e": 27015,
"s": 27002,
"text": "cryptography"
},
{
"code": null,
"e": 27113,
"s": 27015,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27145,
"s": 27113,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27201,
"s": 27145,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27243,
"s": 27201,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27285,
"s": 27243,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27307,
"s": 27285,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27346,
"s": 27307,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27377,
"s": 27346,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27432,
"s": 27377,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 27461,
"s": 27432,
"text": "Create a directory in Python"
}
] |
Using User-Defined Variables in MySQL | Let us understand what user variables are and how they can be used in MySQL. We will also see the rules −
User variables are written as @var_name. Here, the ‘var_name’ refers to variable name, which consists of alphanumeric characters, ., _, and $.
User variables are written as @var_name. Here, the ‘var_name’ refers to variable name, which consists of alphanumeric characters, ., _, and $.
A user variable name can contain other characters if they are quoted as a string or identifier.
A user variable name can contain other characters if they are quoted as a string or identifier.
User-defined variables are session specific.
User-defined variables are session specific.
A user variable which is defined by one client can’t be seen or used by other clients.
A user variable which is defined by one client can’t be seen or used by other clients.
But the only exception is that if a user has access to the Performance Schema
user_variables_by_thread table, then that user can see all user variables for all sessions.All variables for a given client session are automatically made free when that client exits.User variable names are not case-sensitive. The names have a maximum length of 64
characters.
But the only exception is that if a user has access to the Performance Schema
user_variables_by_thread table, then that user can see all user variables for all sessions.
All variables for a given client session are automatically made free when that client exits.
User variable names are not case-sensitive. The names have a maximum length of 64
characters.
One way to set a user-defined variable is by issuing a SET statement. Let us see how it can be done using the below command −
SET @var_name = expr [, @var_name = expr] ...
While using SET, use either = or := as the assignment operator.
User variables can be assigned a value from a limited set of data types. These include integer, decimal, floating-point, binary or nonbinary string, or NULL value.
Assignment of decimal and real values won’t preserve the precision or scale of the value.
Assignment of decimal and real values won’t preserve the precision or scale of the value.
A value of a type other than which is permissible gets converted to a permissible type.
A value of a type other than which is permissible gets converted to a permissible type.
This is the same coercibility that is used for table column values.
This is the same coercibility that is used for table column values.
MySQL user variables can be used to remember results without storing them in temporary variables in the client.
MySQL user variables can be used to remember results without storing them in temporary variables in the client.
They are used to store data without explicitly assigning a memory location to them.
They are used to store data without explicitly assigning a memory location to them. | [
{
"code": null,
"e": 1168,
"s": 1062,
"text": "Let us understand what user variables are and how they can be used in MySQL. We will also see the rules −"
},
{
"code": null,
"e": 1311,
"s": 1168,
"text": "User variables are written as @var_name. Here, the ‘var_name’ refers to variable name, which consists of alphanumeric characters, ., _, and $."
},
{
"code": null,
"e": 1454,
"s": 1311,
"text": "User variables are written as @var_name. Here, the ‘var_name’ refers to variable name, which consists of alphanumeric characters, ., _, and $."
},
{
"code": null,
"e": 1550,
"s": 1454,
"text": "A user variable name can contain other characters if they are quoted as a string or identifier."
},
{
"code": null,
"e": 1646,
"s": 1550,
"text": "A user variable name can contain other characters if they are quoted as a string or identifier."
},
{
"code": null,
"e": 1691,
"s": 1646,
"text": "User-defined variables are session specific."
},
{
"code": null,
"e": 1736,
"s": 1691,
"text": "User-defined variables are session specific."
},
{
"code": null,
"e": 1823,
"s": 1736,
"text": "A user variable which is defined by one client can’t be seen or used by other clients."
},
{
"code": null,
"e": 1910,
"s": 1823,
"text": "A user variable which is defined by one client can’t be seen or used by other clients."
},
{
"code": null,
"e": 2265,
"s": 1910,
"text": "But the only exception is that if a user has access to the Performance Schema\nuser_variables_by_thread table, then that user can see all user variables for all sessions.All variables for a given client session are automatically made free when that client exits.User variable names are not case-sensitive. The names have a maximum length of 64\ncharacters."
},
{
"code": null,
"e": 2435,
"s": 2265,
"text": "But the only exception is that if a user has access to the Performance Schema\nuser_variables_by_thread table, then that user can see all user variables for all sessions."
},
{
"code": null,
"e": 2528,
"s": 2435,
"text": "All variables for a given client session are automatically made free when that client exits."
},
{
"code": null,
"e": 2622,
"s": 2528,
"text": "User variable names are not case-sensitive. The names have a maximum length of 64\ncharacters."
},
{
"code": null,
"e": 2748,
"s": 2622,
"text": "One way to set a user-defined variable is by issuing a SET statement. Let us see how it can be done using the below command −"
},
{
"code": null,
"e": 2794,
"s": 2748,
"text": "SET @var_name = expr [, @var_name = expr] ..."
},
{
"code": null,
"e": 2858,
"s": 2794,
"text": "While using SET, use either = or := as the assignment operator."
},
{
"code": null,
"e": 3022,
"s": 2858,
"text": "User variables can be assigned a value from a limited set of data types. These include integer, decimal, floating-point, binary or nonbinary string, or NULL value."
},
{
"code": null,
"e": 3112,
"s": 3022,
"text": "Assignment of decimal and real values won’t preserve the precision or scale of the value."
},
{
"code": null,
"e": 3202,
"s": 3112,
"text": "Assignment of decimal and real values won’t preserve the precision or scale of the value."
},
{
"code": null,
"e": 3290,
"s": 3202,
"text": "A value of a type other than which is permissible gets converted to a permissible type."
},
{
"code": null,
"e": 3378,
"s": 3290,
"text": "A value of a type other than which is permissible gets converted to a permissible type."
},
{
"code": null,
"e": 3446,
"s": 3378,
"text": "This is the same coercibility that is used for table column values."
},
{
"code": null,
"e": 3514,
"s": 3446,
"text": "This is the same coercibility that is used for table column values."
},
{
"code": null,
"e": 3626,
"s": 3514,
"text": "MySQL user variables can be used to remember results without storing them in temporary variables in the client."
},
{
"code": null,
"e": 3738,
"s": 3626,
"text": "MySQL user variables can be used to remember results without storing them in temporary variables in the client."
},
{
"code": null,
"e": 3822,
"s": 3738,
"text": "They are used to store data without explicitly assigning a memory location to them."
},
{
"code": null,
"e": 3906,
"s": 3822,
"text": "They are used to store data without explicitly assigning a memory location to them."
}
] |
TypeScript String - GeeksforGeeks | 11 Jul, 2019
In TypeScript, the string is sequence of char values and also considered as an object. It is a type of primitive data type that is used to store text data. The string values are used between single quotation marks or double quotation marks, and also array of characters works same as a string. TypeScript string work with the series of character.
Syntax
var var_name = new String(string);
Property:
Constructor: It will return a reference to the string function.
Length: This property will return the length of the string.
Prototype: This property let you add the property and methods.
Methods:
charAt(): This method will return character at the specified index.
charCodeAt(): This method will return returns a number indicating the Unicode value of the character at the specified index.
concat(): This method will combine the two separate string and return that combined string.
indexOf(): It will return the index. Fast occurrence of specified value else -1 if not found.
lastIndexOf(): It will return index, last occurrence of specified value else -1 if not found.
localeCompare(): This method will return a number which indicate that the reference string comes before or after or the same as the given string in sort order.
match(): This method is used to match regular expression with the specified string.
replace(): This method is use to replace the match string by regular expression.
search(): This method is used to search for matching the regular expression with the specified string.
slice(): Extract the specified string and return a new string.
split(): Splits the specified String object into an array of strings.
substr(): Return the character from start to define index.
substring(): Returns character of string between two define indexes.
toLocaleLowerCase(): This method convert the string into lowercase while respecting the current locale.
toLocaleUpperCase(): This method convert the string into Uppercase while respecting the current locale.
toLowerCase(): This method convert the string into lowercase.
toString(): This method returns a string representing the specified object.
toUpperCase(): This method convert the string into uppercase.
valueOf(): This method returns the primitive value of specified string.
Example:
let uname = new String("Hello geeksforgeeks"); console.log("Message: " + uname); console.log("Length: " + uname.length);
Output:
Message: Hello geeksforgeeks
Length: 19
Template String: Template string support in TypeScript from ES6 version. Template strings are used to fixed the expressions into strings.
Example:
let emplName:string = "Mohit Jain"; let compName:string = "geeksforgeeks"; // Pre-ES6 let emplDetail1: string = emplName + " works in the " + compName + " company."; // Post-ES6 let emplDetail2: string = `${emplName} works in the ${compName} company.`; console.log("Before ES6: " +emplDetail1); console.log("After ES6: " +emplDetail2);
Output:
Before ES6: Mohit Jain works in the geeksforgeeks company.
After ES6: Mohit Jain works in the geeksforgeeks company.
Multi-Line String: ES6 provides us to write the multi-line string. This can be shown in the below example.We have to add “\n” at the end of each string for containing a new line in the string. This represents the clear cut statement.Example:
let multi = ' hello\n ' + 'Geeksforgeeks\n ' + 'my\n ' + 'name\n ' + 'is\n ' + 'Mohit Jain'; console.log(multi);
Output:
hello
Geeksforgeeks
my
name
is
Mohit Jain
String Literal Type: It is also a type of string and strings literal is a sequence of characters enclosed in double quotation marks (” “) and terminated with a null value. In a string literal type is a type whose expected value is a string with textual contents equal to that of the string literal type. In other words, we can say a string literal allow us to specify the exact string value specified in the string literal type. While a string literal type uses different allowed string value then use “pipe” or ” | ” symbol between them.
Syntax:
Type variableName = "value1" | "value2" | "value3"; // upto N number of values
String literal can be used in two ways:
Variable Assignment: Whatever the values will be allowed for literal type variable then We can assign. Otherwise, it will give the compile-time error.Example:type Pet = 'mouse' | 'dog' | 'Rabbit'; let pet: Pet; if(pet = 'mouse'){ console.log("Correct"); }; if(pet = 'Deer') { console.log(" we got compilation error type!"); }; Output:Correct
we got compilation error type!
type Pet = 'mouse' | 'dog' | 'Rabbit'; let pet: Pet; if(pet = 'mouse'){ console.log("Correct"); }; if(pet = 'Deer') { console.log(" we got compilation error type!"); };
Output:
Correct
we got compilation error type!
Function Parameter: For literal type argument we can pass only defined values. Otherwise, it will give the compile-time error.Example:type FruitsName = "Apple" | "Mango" | "Orange"; function showFruitName(fruitsName: FruitsName): void { console.log(fruitsName); } showFruitName('Mango'); //OK - Print 'Mango' //Compile Time Error showFruitName('Banana');Output:Mango
Banana
type FruitsName = "Apple" | "Mango" | "Orange"; function showFruitName(fruitsName: FruitsName): void { console.log(fruitsName); } showFruitName('Mango'); //OK - Print 'Mango' //Compile Time Error showFruitName('Banana');
Output:
Mango
Banana
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
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": 23971,
"s": 23943,
"text": "\n11 Jul, 2019"
},
{
"code": null,
"e": 24318,
"s": 23971,
"text": "In TypeScript, the string is sequence of char values and also considered as an object. It is a type of primitive data type that is used to store text data. The string values are used between single quotation marks or double quotation marks, and also array of characters works same as a string. TypeScript string work with the series of character."
},
{
"code": null,
"e": 24325,
"s": 24318,
"text": "Syntax"
},
{
"code": null,
"e": 24361,
"s": 24325,
"text": "var var_name = new String(string); "
},
{
"code": null,
"e": 24371,
"s": 24361,
"text": "Property:"
},
{
"code": null,
"e": 24435,
"s": 24371,
"text": "Constructor: It will return a reference to the string function."
},
{
"code": null,
"e": 24495,
"s": 24435,
"text": "Length: This property will return the length of the string."
},
{
"code": null,
"e": 24558,
"s": 24495,
"text": "Prototype: This property let you add the property and methods."
},
{
"code": null,
"e": 24567,
"s": 24558,
"text": "Methods:"
},
{
"code": null,
"e": 24635,
"s": 24567,
"text": "charAt(): This method will return character at the specified index."
},
{
"code": null,
"e": 24760,
"s": 24635,
"text": "charCodeAt(): This method will return returns a number indicating the Unicode value of the character at the specified index."
},
{
"code": null,
"e": 24852,
"s": 24760,
"text": "concat(): This method will combine the two separate string and return that combined string."
},
{
"code": null,
"e": 24946,
"s": 24852,
"text": "indexOf(): It will return the index. Fast occurrence of specified value else -1 if not found."
},
{
"code": null,
"e": 25040,
"s": 24946,
"text": "lastIndexOf(): It will return index, last occurrence of specified value else -1 if not found."
},
{
"code": null,
"e": 25200,
"s": 25040,
"text": "localeCompare(): This method will return a number which indicate that the reference string comes before or after or the same as the given string in sort order."
},
{
"code": null,
"e": 25284,
"s": 25200,
"text": "match(): This method is used to match regular expression with the specified string."
},
{
"code": null,
"e": 25365,
"s": 25284,
"text": "replace(): This method is use to replace the match string by regular expression."
},
{
"code": null,
"e": 25468,
"s": 25365,
"text": "search(): This method is used to search for matching the regular expression with the specified string."
},
{
"code": null,
"e": 25531,
"s": 25468,
"text": "slice(): Extract the specified string and return a new string."
},
{
"code": null,
"e": 25601,
"s": 25531,
"text": "split(): Splits the specified String object into an array of strings."
},
{
"code": null,
"e": 25660,
"s": 25601,
"text": "substr(): Return the character from start to define index."
},
{
"code": null,
"e": 25729,
"s": 25660,
"text": "substring(): Returns character of string between two define indexes."
},
{
"code": null,
"e": 25833,
"s": 25729,
"text": "toLocaleLowerCase(): This method convert the string into lowercase while respecting the current locale."
},
{
"code": null,
"e": 25937,
"s": 25833,
"text": "toLocaleUpperCase(): This method convert the string into Uppercase while respecting the current locale."
},
{
"code": null,
"e": 25999,
"s": 25937,
"text": "toLowerCase(): This method convert the string into lowercase."
},
{
"code": null,
"e": 26075,
"s": 25999,
"text": "toString(): This method returns a string representing the specified object."
},
{
"code": null,
"e": 26137,
"s": 26075,
"text": "toUpperCase(): This method convert the string into uppercase."
},
{
"code": null,
"e": 26209,
"s": 26137,
"text": "valueOf(): This method returns the primitive value of specified string."
},
{
"code": null,
"e": 26218,
"s": 26209,
"text": "Example:"
},
{
"code": "let uname = new String(\"Hello geeksforgeeks\"); console.log(\"Message: \" + uname); console.log(\"Length: \" + uname.length);",
"e": 26341,
"s": 26218,
"text": null
},
{
"code": null,
"e": 26349,
"s": 26341,
"text": "Output:"
},
{
"code": null,
"e": 26390,
"s": 26349,
"text": "Message: Hello geeksforgeeks\nLength: 19\n"
},
{
"code": null,
"e": 26528,
"s": 26390,
"text": "Template String: Template string support in TypeScript from ES6 version. Template strings are used to fixed the expressions into strings."
},
{
"code": null,
"e": 26537,
"s": 26528,
"text": "Example:"
},
{
"code": "let emplName:string = \"Mohit Jain\"; let compName:string = \"geeksforgeeks\"; // Pre-ES6 let emplDetail1: string = emplName + \" works in the \" + compName + \" company.\"; // Post-ES6 let emplDetail2: string = `${emplName} works in the ${compName} company.`; console.log(\"Before ES6: \" +emplDetail1); console.log(\"After ES6: \" +emplDetail2);",
"e": 26885,
"s": 26537,
"text": null
},
{
"code": null,
"e": 26893,
"s": 26885,
"text": "Output:"
},
{
"code": null,
"e": 27012,
"s": 26893,
"text": "Before ES6: Mohit Jain works in the geeksforgeeks company.\nAfter ES6: Mohit Jain works in the geeksforgeeks company.\n"
},
{
"code": null,
"e": 27254,
"s": 27012,
"text": "Multi-Line String: ES6 provides us to write the multi-line string. This can be shown in the below example.We have to add “\\n” at the end of each string for containing a new line in the string. This represents the clear cut statement.Example:"
},
{
"code": "let multi = ' hello\\n ' + 'Geeksforgeeks\\n ' + 'my\\n ' + 'name\\n ' + 'is\\n ' + 'Mohit Jain'; console.log(multi); ",
"e": 27395,
"s": 27254,
"text": null
},
{
"code": null,
"e": 27403,
"s": 27395,
"text": "Output:"
},
{
"code": null,
"e": 27445,
"s": 27403,
"text": "hello\nGeeksforgeeks\nmy\nname\nis\nMohit Jain"
},
{
"code": null,
"e": 27984,
"s": 27445,
"text": "String Literal Type: It is also a type of string and strings literal is a sequence of characters enclosed in double quotation marks (” “) and terminated with a null value. In a string literal type is a type whose expected value is a string with textual contents equal to that of the string literal type. In other words, we can say a string literal allow us to specify the exact string value specified in the string literal type. While a string literal type uses different allowed string value then use “pipe” or ” | ” symbol between them."
},
{
"code": null,
"e": 27992,
"s": 27984,
"text": "Syntax:"
},
{
"code": null,
"e": 28074,
"s": 27992,
"text": "Type variableName = \"value1\" | \"value2\" | \"value3\"; // upto N number of values \n"
},
{
"code": null,
"e": 28114,
"s": 28074,
"text": "String literal can be used in two ways:"
},
{
"code": null,
"e": 28504,
"s": 28114,
"text": "Variable Assignment: Whatever the values will be allowed for literal type variable then We can assign. Otherwise, it will give the compile-time error.Example:type Pet = 'mouse' | 'dog' | 'Rabbit'; let pet: Pet; if(pet = 'mouse'){ console.log(\"Correct\"); }; if(pet = 'Deer') { console.log(\" we got compilation error type!\"); }; Output:Correct\nwe got compilation error type!\n"
},
{
"code": "type Pet = 'mouse' | 'dog' | 'Rabbit'; let pet: Pet; if(pet = 'mouse'){ console.log(\"Correct\"); }; if(pet = 'Deer') { console.log(\" we got compilation error type!\"); }; ",
"e": 28690,
"s": 28504,
"text": null
},
{
"code": null,
"e": 28698,
"s": 28690,
"text": "Output:"
},
{
"code": null,
"e": 28738,
"s": 28698,
"text": "Correct\nwe got compilation error type!\n"
},
{
"code": null,
"e": 29125,
"s": 28738,
"text": "Function Parameter: For literal type argument we can pass only defined values. Otherwise, it will give the compile-time error.Example:type FruitsName = \"Apple\" | \"Mango\" | \"Orange\"; function showFruitName(fruitsName: FruitsName): void { console.log(fruitsName); } showFruitName('Mango'); //OK - Print 'Mango' //Compile Time Error showFruitName('Banana');Output:Mango\nBanana\n"
},
{
"code": "type FruitsName = \"Apple\" | \"Mango\" | \"Orange\"; function showFruitName(fruitsName: FruitsName): void { console.log(fruitsName); } showFruitName('Mango'); //OK - Print 'Mango' //Compile Time Error showFruitName('Banana');",
"e": 29358,
"s": 29125,
"text": null
},
{
"code": null,
"e": 29366,
"s": 29358,
"text": "Output:"
},
{
"code": null,
"e": 29380,
"s": 29366,
"text": "Mango\nBanana\n"
},
{
"code": null,
"e": 29391,
"s": 29380,
"text": "TypeScript"
},
{
"code": null,
"e": 29402,
"s": 29391,
"text": "JavaScript"
},
{
"code": null,
"e": 29419,
"s": 29402,
"text": "Web Technologies"
},
{
"code": null,
"e": 29517,
"s": 29419,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29526,
"s": 29517,
"text": "Comments"
},
{
"code": null,
"e": 29539,
"s": 29526,
"text": "Old Comments"
},
{
"code": null,
"e": 29600,
"s": 29539,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29645,
"s": 29600,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29717,
"s": 29645,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29769,
"s": 29717,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 29815,
"s": 29769,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 29871,
"s": 29815,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 29904,
"s": 29871,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29966,
"s": 29904,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30009,
"s": 29966,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to listen volume buttons in Android background service? | This example demonstrates how do I listen volume buttons in android background service.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16sp"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:text="Increase and decrease Volume"
android:textSize="24sp"
android:textStyle="bold" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.database.ContentObserver;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
SettingsContentObserver settingsContentObserver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settingsContentObserver = new SettingsContentObserver(this, new Handler());
getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.
CONTENT_URI, true, settingsContentObserver);
}
public class SettingsContentObserver extends ContentObserver {
int previousVolume;
Context context;
SettingsContentObserver(Context c, Handler handler) {
super(handler);
context = c;
AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
previousVolume =
Objects.requireNonNull(audio).getStreamVolume(AudioManager.STREAM_MUSIC);
}
@Override
public boolean deliverSelfNotifications() {
return super.deliverSelfNotifications();
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
int currentVolume =
Objects.requireNonNull(audio).getStreamVolume(AudioManager.STREAM_MUSIC);
int delta = previousVolume - currentVolume;
if (delta > 0) {
Toast.makeText(MainActivity.this, "Volume Decreased", Toast.LENGTH_SHORT).show();
previousVolume = currentVolume;
}
else if (delta < 0) {
Toast.makeText(MainActivity.this, "Volume Increased", Toast.LENGTH_SHORT).show();
previousVolume = currentVolume;
}
}
}
@Override
protected void onDestroy() {
getApplicationContext().getContentResolver().unregisterContentObserver(settingsContentObserver);
super.onDestroy();
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "This example demonstrates how do I listen volume buttons in android background service."
},
{
"code": null,
"e": 1279,
"s": 1150,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1344,
"s": 1279,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1924,
"s": 1344,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:padding=\"16sp\"\n tools:context=\".MainActivity\">\n<TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"30dp\"\n android:text=\"Increase and decrease Volume\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1981,
"s": 1924,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 4233,
"s": 1981,
"text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.content.Context;\nimport android.database.ContentObserver;\nimport android.media.AudioManager;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.widget.Toast;\nimport java.util.Objects;\npublic class MainActivity extends AppCompatActivity {\n SettingsContentObserver settingsContentObserver;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n settingsContentObserver = new SettingsContentObserver(this, new Handler());\n\n getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.\n CONTENT_URI, true, settingsContentObserver);\n }\n public class SettingsContentObserver extends ContentObserver {\n int previousVolume;\n Context context;\n SettingsContentObserver(Context c, Handler handler) {\n super(handler);\n context = c;\n AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);\n previousVolume =\n Objects.requireNonNull(audio).getStreamVolume(AudioManager.STREAM_MUSIC);\n }\n @Override\n public boolean deliverSelfNotifications() {\n return super.deliverSelfNotifications();\n }\n @Override\n public void onChange(boolean selfChange) {\n super.onChange(selfChange);\n AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);\n int currentVolume =\n Objects.requireNonNull(audio).getStreamVolume(AudioManager.STREAM_MUSIC);\n int delta = previousVolume - currentVolume;\n if (delta > 0) {\n Toast.makeText(MainActivity.this, \"Volume Decreased\", Toast.LENGTH_SHORT).show();\n previousVolume = currentVolume;\n }\n else if (delta < 0) {\n Toast.makeText(MainActivity.this, \"Volume Increased\", Toast.LENGTH_SHORT).show();\n previousVolume = currentVolume;\n }\n }\n }\n @Override\n protected void onDestroy() {\n getApplicationContext().getContentResolver().unregisterContentObserver(settingsContentObserver);\nsuper.onDestroy();\n }\n}"
},
{
"code": null,
"e": 4288,
"s": 4233,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4955,
"s": 4288,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n</application>\n</manifest>"
},
{
"code": null,
"e": 5310,
"s": 4955,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
}
] |
Difference between datetime and datetime-local in HTML5 | A date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601 with the time zone set to UTC.
Let us see an example:
<!DOCTYPE HTML>
<html>
<body>
<form action = "/cgi-bin/html5.cgi" method = "get">
Date and Time : <input type = "datetime" name = "newinput" />
<input type = "submit" value = "submit" />
</form>
</body>
</html>
A date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601, with no time zone information.
Let us see an example:
<!DOCTYPE HTML>
<html>
<body>
<form action = "/cgi-bin/html5.cgi" method = "get">
Local Date and Time : <input type = "datetime-local" name = "newinput" />
<input type = "submit" value = "submit" />
</form>
</body>
</html> | [
{
"code": null,
"e": 1203,
"s": 1062,
"text": "A date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601 with the time zone set to UTC."
},
{
"code": null,
"e": 1226,
"s": 1203,
"text": "Let us see an example:"
},
{
"code": null,
"e": 1473,
"s": 1226,
"text": "<!DOCTYPE HTML>\n<html>\n <body>\n <form action = \"/cgi-bin/html5.cgi\" method = \"get\">\n Date and Time : <input type = \"datetime\" name = \"newinput\" />\n <input type = \"submit\" value = \"submit\" />\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 1615,
"s": 1473,
"text": "A date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601, with no time zone information."
},
{
"code": null,
"e": 1638,
"s": 1615,
"text": "Let us see an example:"
},
{
"code": null,
"e": 1897,
"s": 1638,
"text": "<!DOCTYPE HTML>\n<html>\n <body>\n <form action = \"/cgi-bin/html5.cgi\" method = \"get\">\n Local Date and Time : <input type = \"datetime-local\" name = \"newinput\" />\n <input type = \"submit\" value = \"submit\" />\n </form>\n </body>\n</html>"
}
] |
How to check if a file already exists in R ? - GeeksforGeeks | 08 May, 2021
In this article, we will discuss how to check if a file already exists or not using R Programming Languague.
Directory in use:
The function file.exists() returns a logical vector indicating whether the file mentioned in the function existing or not.
Note: Make sure that to provide a file path for those, not in the current working directory.
Syntax: File.exists(“file_path”)
Return value: The function file.exists() returns a logical vector indicating whether the files named by its argument exist.
TRUE- file exists
FALSE- file does not exists
Example:
R
file.exists("Akshit.R")
Output:
[1] TRUE
Example 2:
R
file.exists("GFG.R")
Output:
[1] FALSE
This function can also be used to check whether the file is existing or not.
Syntax: file_test(op, x, y)
Parameter:
op: a character string specifying the test to be performed. Unary tests (only x is used) are “-f” (existence and not being a directory), “-d” (existence and directory) and “-x” (executable as a file or searchable as a directory). Binary tests are “-nt” (strictly newer than, using the modification dates) and “-ot” (strictly older than): in both cases the test is false unless both files exist.
x, y: character vectors giving file paths.
Returns: The function file_test() returns a logical vector indicating whether the files named by its argument exist.
TRUE- file exists
FALSE- file does not exists
Example
R
#"-f" (existence and not # being a directory)file_test("-f","Akshit.R")
Output
[1] TRUE
Example 2:
R
file_test("-f","GFG.R")
Output
[1] TRUE
Picked
R-FileHandling
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Data Visualization in R
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
How to import an Excel File into R ?
How to filter R DataFrame by values in a column? | [
{
"code": null,
"e": 25162,
"s": 25134,
"text": "\n08 May, 2021"
},
{
"code": null,
"e": 25271,
"s": 25162,
"text": "In this article, we will discuss how to check if a file already exists or not using R Programming Languague."
},
{
"code": null,
"e": 25289,
"s": 25271,
"text": "Directory in use:"
},
{
"code": null,
"e": 25413,
"s": 25289,
"text": "The function file.exists() returns a logical vector indicating whether the file mentioned in the function existing or not. "
},
{
"code": null,
"e": 25506,
"s": 25413,
"text": "Note: Make sure that to provide a file path for those, not in the current working directory."
},
{
"code": null,
"e": 25539,
"s": 25506,
"text": "Syntax: File.exists(“file_path”)"
},
{
"code": null,
"e": 25663,
"s": 25539,
"text": "Return value: The function file.exists() returns a logical vector indicating whether the files named by its argument exist."
},
{
"code": null,
"e": 25681,
"s": 25663,
"text": "TRUE- file exists"
},
{
"code": null,
"e": 25710,
"s": 25681,
"text": "FALSE- file does not exists"
},
{
"code": null,
"e": 25719,
"s": 25710,
"text": "Example:"
},
{
"code": null,
"e": 25721,
"s": 25719,
"text": "R"
},
{
"code": "file.exists(\"Akshit.R\")",
"e": 25745,
"s": 25721,
"text": null
},
{
"code": null,
"e": 25753,
"s": 25745,
"text": "Output:"
},
{
"code": null,
"e": 25762,
"s": 25753,
"text": "[1] TRUE"
},
{
"code": null,
"e": 25773,
"s": 25762,
"text": "Example 2:"
},
{
"code": null,
"e": 25775,
"s": 25773,
"text": "R"
},
{
"code": "file.exists(\"GFG.R\")",
"e": 25796,
"s": 25775,
"text": null
},
{
"code": null,
"e": 25804,
"s": 25796,
"text": "Output:"
},
{
"code": null,
"e": 25814,
"s": 25804,
"text": "[1] FALSE"
},
{
"code": null,
"e": 25891,
"s": 25814,
"text": "This function can also be used to check whether the file is existing or not."
},
{
"code": null,
"e": 25919,
"s": 25891,
"text": "Syntax: file_test(op, x, y)"
},
{
"code": null,
"e": 25930,
"s": 25919,
"text": "Parameter:"
},
{
"code": null,
"e": 26325,
"s": 25930,
"text": "op: a character string specifying the test to be performed. Unary tests (only x is used) are “-f” (existence and not being a directory), “-d” (existence and directory) and “-x” (executable as a file or searchable as a directory). Binary tests are “-nt” (strictly newer than, using the modification dates) and “-ot” (strictly older than): in both cases the test is false unless both files exist."
},
{
"code": null,
"e": 26368,
"s": 26325,
"text": "x, y: character vectors giving file paths."
},
{
"code": null,
"e": 26485,
"s": 26368,
"text": "Returns: The function file_test() returns a logical vector indicating whether the files named by its argument exist."
},
{
"code": null,
"e": 26503,
"s": 26485,
"text": "TRUE- file exists"
},
{
"code": null,
"e": 26532,
"s": 26503,
"text": "FALSE- file does not exists"
},
{
"code": null,
"e": 26540,
"s": 26532,
"text": "Example"
},
{
"code": null,
"e": 26542,
"s": 26540,
"text": "R"
},
{
"code": "#\"-f\" (existence and not # being a directory)file_test(\"-f\",\"Akshit.R\")",
"e": 26614,
"s": 26542,
"text": null
},
{
"code": null,
"e": 26621,
"s": 26614,
"text": "Output"
},
{
"code": null,
"e": 26630,
"s": 26621,
"text": "[1] TRUE"
},
{
"code": null,
"e": 26641,
"s": 26630,
"text": "Example 2:"
},
{
"code": null,
"e": 26643,
"s": 26641,
"text": "R"
},
{
"code": "file_test(\"-f\",\"GFG.R\") ",
"e": 26668,
"s": 26643,
"text": null
},
{
"code": null,
"e": 26675,
"s": 26668,
"text": "Output"
},
{
"code": null,
"e": 26684,
"s": 26675,
"text": "[1] TRUE"
},
{
"code": null,
"e": 26691,
"s": 26684,
"text": "Picked"
},
{
"code": null,
"e": 26706,
"s": 26691,
"text": "R-FileHandling"
},
{
"code": null,
"e": 26717,
"s": 26706,
"text": "R Language"
},
{
"code": null,
"e": 26815,
"s": 26717,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26824,
"s": 26815,
"text": "Comments"
},
{
"code": null,
"e": 26837,
"s": 26824,
"text": "Old Comments"
},
{
"code": null,
"e": 26889,
"s": 26837,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 26927,
"s": 26889,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 26962,
"s": 26927,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27020,
"s": 26962,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27044,
"s": 27020,
"text": "Data Visualization in R"
},
{
"code": null,
"e": 27081,
"s": 27044,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 27124,
"s": 27081,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 27174,
"s": 27124,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 27211,
"s": 27174,
"text": "How to import an Excel File into R ?"
}
] |
Predecessor and Successor | Practice | GeeksforGeeks | There is BST given with root node with key part as integer only. You need to find the inorder successor and predecessor of a given key. In case, if the either of predecessor or successor is not found print -1.
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 n denoting the number of edges of the BST. The next line contains the edges of the BST. The last line contains the key.
Output:
Print the predecessor followed by successor for the given key. If the predecessor or successor is not found print -1.
Note : You don't need to print anything. You only need to set p.pre to the predecessor and s.succ to the successor. p and s have been passed in the function parameter.
Constraints:
1<=T<=100
1<=n<=100
1<=data of node<=100
1<=key<=100
Example:
Input:
2
6
50 30 L 30 20 L 30 40 R 50 70 R 70 60 L 70 80 R
65
6
50 30 L 30 20 L 30 40 R 50 70 R 70 60 L 70 80 R
100
Output:
60 70
80 -1
0
maareftam
This comment was deleted.
-1
neerajchatterjee23012 weeks ago
void inorder(Node* root, vector<Node*> &ans, vector<int> &store){
if(root == NULL) return;
inorder(root->left, ans, store);
ans.push_back(root);
store.push_back(root->key);
inorder(root->right, ans, store);
}
// This function finds predecessor and successor of key in BST.
// It sets pre and suc as predecessor and successor respectively
void findPreSuc(Node* root, Node*& pre, Node*& suc, int key)
{
vector<Node*> ans;
vector<int> store;
inorder(root, ans, store);
// successor
int pos1 = upper_bound(store.begin(), store.end(), key) - store.begin();
// predecessor
int pos2 = lower_bound(store.begin(), store.end(), key) - store.begin();
int n = store.size();
if(pos1 == n){
suc = NULL;
if(pos2 >= 1){
pre = ans[pos2-1];
}
else{
pre = NULL;
}
}
else{
suc = ans[pos1];
if(pos2 >= 1){
pre = ans[pos2-1];
}
else{
pre = NULL;
}
}
}
0
sahuprashant291 month ago
Recursive and easy- only 3conditions used:
public static void findPreSuc(Node root, Res p, Res s, int key)
{
if(root==null)return;
if(key>root.data){
p.pre = root;
findPreSuc(root.right,p,s,key);
}
else if(key<root.data){
s.succ = root;
findPreSuc(root.left,p,s,key);
}
else{
findPreSuc(root.left,p,s,key);
findPreSuc(root.right,p,s,key);
}
}
0
sahuprashant29
This comment was deleted.
+1
rajatgupta96961 month ago
Node * Success(Node * root){ Node * curr = root->right; while(curr->left!=NULL) curr=curr->left; return curr;}Node * Predecer(Node * root){ Node * curr = root->left; while(curr->right!=NULL) curr=curr->right; return curr;}// This function finds predecessor and successor of key in BST.// It sets pre and suc as predecessor and successor respectivelyvoid findPreSuc(Node* root, Node*& pre, Node*& suc, int key){ if(root==NULL) return; if(root->key == key) { // suscessor - one right ---> extreme left if(root->right) suc=Success(root); // predessor - one left ---> extreme right if(root->left) pre=Predecer(root); return; } if(root->key < key) { pre =root; findPreSuc(root->right,pre,suc,key); } else if(root->key > key) { suc =root; findPreSuc(root->left,pre,suc,key); }
}
+1
ruchitchudasama1231 month ago
void findPreSuc(Node* root, Node*& pre, Node*& suc, int key)
{
if (!root) return;
// suc
Node* cur=root;
while(cur!=NULL)
if(cur->key > key){
suc=cur;
cur=cur->left;
}
else cur=cur->right;
// pre
cur=root;
while(cur)
if(cur->key < key){
pre=cur;
cur=cur->right;
}else cur=cur->left;
}
+2
koushalsharma0032 months ago
Simple C++ solution. Note that we don't have to consider the node whose value is equal to the key.
void findPreSuc(Node* root, Node*& pre, Node*& suc, int key)
{
// Your code goes here
if(!root) return;
Node* curr = root;
while(curr)
{
if(curr -> key < key)
{
pre = curr;
curr = curr -> right;
}
else
{
curr = curr -> left;
}
}
curr = root;
while(curr)
{
if(curr -> key > key)
{
suc = curr;
curr = curr -> left;
}
else
{
curr = curr -> right;
}
}
}
+1
gowthamreddyuppunuri2 months ago
void findPre(Node *root,Node *&pre,int key){
if(root == nullptr){
return;
}
if(root->key < key){
pre = root;
//just smaller than key
findPre(root->right,pre,key);
}
else if(root->key >= key){
findPre(root->left,pre,key);
}
}
void findSuc(Node *root,Node *&suc,int key){
if(root == nullptr){
return;
}
if(root->key <= key){
findSuc(root->right,suc,key);
}
else if(root->key > key){
//just greater find in left of root
suc = root;
findSuc(root->left,suc,key);
}
}
void findPreSuc(Node* root, Node*& pre, Node*& suc, int key)
{
// Your code goes here
findPre(root,pre,key);
findSuc(root,suc,key);
}
+2
sanketbhagat2 months ago
SIMPLE JAVA SOLUTION
class GfG{
public static void findPreSuc(Node root, Res p, Res s, int key){
// add your code here
Node curr = root;
while(curr!=null){
if(curr.data<key){
p.pre = curr;
curr = curr.right;
}else curr = curr.left;
}
curr = root;
while(curr!=null){
if(curr.data>key){
s.succ = curr;
curr = curr.left;
}else curr = curr.right;
}
}
}
+3
animesh18362 months ago
void findPreSuc(Node* root, Node*& pre, Node*& suc, int key)
{
if(not root)return;
findPreSuc(root->left,pre,suc,key);
if(root->key < key)pre=root;
if(root->key>key and not suc)suc=root;
findPreSuc(root->right,pre,suc,key);
}
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": 448,
"s": 238,
"text": "There is BST given with root node with key part as integer only. You need to find the inorder successor and predecessor of a given key. In case, if the either of predecessor or successor is not found print -1."
},
{
"code": null,
"e": 706,
"s": 448,
"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 n denoting the number of edges of the BST. The next line contains the edges of the BST. The last line contains the key."
},
{
"code": null,
"e": 832,
"s": 706,
"text": "Output:\nPrint the predecessor followed by successor for the given key. If the predecessor or successor is not found print -1."
},
{
"code": null,
"e": 1000,
"s": 832,
"text": "Note : You don't need to print anything. You only need to set p.pre to the predecessor and s.succ to the successor. p and s have been passed in the function parameter."
},
{
"code": null,
"e": 1066,
"s": 1000,
"text": "Constraints:\n1<=T<=100\n1<=n<=100\n1<=data of node<=100\n1<=key<=100"
},
{
"code": null,
"e": 1191,
"s": 1066,
"text": "Example:\nInput:\n2\n6\n50 30 L 30 20 L 30 40 R 50 70 R 70 60 L 70 80 R\n65\n6\n50 30 L 30 20 L 30 40 R 50 70 R 70 60 L 70 80 R\n100"
},
{
"code": null,
"e": 1213,
"s": 1191,
"text": "Output:\n60 70\n80 -1\n "
},
{
"code": null,
"e": 1215,
"s": 1213,
"text": "0"
},
{
"code": null,
"e": 1225,
"s": 1215,
"text": "maareftam"
},
{
"code": null,
"e": 1251,
"s": 1225,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1254,
"s": 1251,
"text": "-1"
},
{
"code": null,
"e": 1286,
"s": 1254,
"text": "neerajchatterjee23012 weeks ago"
},
{
"code": null,
"e": 1522,
"s": 1286,
"text": "void inorder(Node* root, vector<Node*> &ans, vector<int> &store){\n if(root == NULL) return;\n \n inorder(root->left, ans, store);\n \n ans.push_back(root);\n store.push_back(root->key);\n \n inorder(root->right, ans, store);\n}"
},
{
"code": null,
"e": 2329,
"s": 1522,
"text": "// This function finds predecessor and successor of key in BST.\n// It sets pre and suc as predecessor and successor respectively\nvoid findPreSuc(Node* root, Node*& pre, Node*& suc, int key)\n{\n \n vector<Node*> ans;\n vector<int> store;\n \n inorder(root, ans, store);\n \n // successor\n int pos1 = upper_bound(store.begin(), store.end(), key) - store.begin();\n // predecessor\n int pos2 = lower_bound(store.begin(), store.end(), key) - store.begin();\n \n int n = store.size();\n \n if(pos1 == n){\n suc = NULL;\n if(pos2 >= 1){\n pre = ans[pos2-1];\n }\n else{\n pre = NULL;\n }\n }\n else{\n suc = ans[pos1];\n \n if(pos2 >= 1){\n pre = ans[pos2-1];\n }\n else{\n pre = NULL;\n }\n }\n \n \n}"
},
{
"code": null,
"e": 2331,
"s": 2329,
"text": "0"
},
{
"code": null,
"e": 2357,
"s": 2331,
"text": "sahuprashant291 month ago"
},
{
"code": null,
"e": 2400,
"s": 2357,
"text": "Recursive and easy- only 3conditions used:"
},
{
"code": null,
"e": 2845,
"s": 2400,
"text": "public static void findPreSuc(Node root, Res p, Res s, int key)\n {\n if(root==null)return;\n \n if(key>root.data){\n p.pre = root;\n findPreSuc(root.right,p,s,key);\n }\n else if(key<root.data){\n s.succ = root;\n findPreSuc(root.left,p,s,key);\n }\n else{\n findPreSuc(root.left,p,s,key);\n findPreSuc(root.right,p,s,key);\n }\n }"
},
{
"code": null,
"e": 2847,
"s": 2845,
"text": "0"
},
{
"code": null,
"e": 2862,
"s": 2847,
"text": "sahuprashant29"
},
{
"code": null,
"e": 2888,
"s": 2862,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2891,
"s": 2888,
"text": "+1"
},
{
"code": null,
"e": 2917,
"s": 2891,
"text": "rajatgupta96961 month ago"
},
{
"code": null,
"e": 3806,
"s": 2917,
"text": "Node * Success(Node * root){ Node * curr = root->right; while(curr->left!=NULL) curr=curr->left; return curr;}Node * Predecer(Node * root){ Node * curr = root->left; while(curr->right!=NULL) curr=curr->right; return curr;}// This function finds predecessor and successor of key in BST.// It sets pre and suc as predecessor and successor respectivelyvoid findPreSuc(Node* root, Node*& pre, Node*& suc, int key){ if(root==NULL) return; if(root->key == key) { // suscessor - one right ---> extreme left if(root->right) suc=Success(root); // predessor - one left ---> extreme right if(root->left) pre=Predecer(root); return; } if(root->key < key) { pre =root; findPreSuc(root->right,pre,suc,key); } else if(root->key > key) { suc =root; findPreSuc(root->left,pre,suc,key); }"
},
{
"code": null,
"e": 3808,
"s": 3806,
"text": "}"
},
{
"code": null,
"e": 3811,
"s": 3808,
"text": "+1"
},
{
"code": null,
"e": 3841,
"s": 3811,
"text": "ruchitchudasama1231 month ago"
},
{
"code": null,
"e": 4265,
"s": 3841,
"text": "void findPreSuc(Node* root, Node*& pre, Node*& suc, int key)\n{\n\n if (!root) return;\n \n // suc\n Node* cur=root;\n while(cur!=NULL)\n if(cur->key > key){\n suc=cur;\n cur=cur->left;\n }\n else cur=cur->right;\n \n // pre\n cur=root;\n while(cur)\n if(cur->key < key){\n pre=cur;\n cur=cur->right;\n \n }else cur=cur->left;\n}"
},
{
"code": null,
"e": 4268,
"s": 4265,
"text": "+2"
},
{
"code": null,
"e": 4297,
"s": 4268,
"text": "koushalsharma0032 months ago"
},
{
"code": null,
"e": 4396,
"s": 4297,
"text": "Simple C++ solution. Note that we don't have to consider the node whose value is equal to the key."
},
{
"code": null,
"e": 4958,
"s": 4396,
"text": "void findPreSuc(Node* root, Node*& pre, Node*& suc, int key)\n{\n// Your code goes here\n if(!root) return;\n Node* curr = root;\n while(curr)\n {\n if(curr -> key < key)\n {\n pre = curr;\n curr = curr -> right;\n }\n else\n {\n curr = curr -> left;\n }\n }\n \n curr = root;\n while(curr)\n {\n if(curr -> key > key)\n {\n suc = curr;\n curr = curr -> left;\n }\n else\n {\n curr = curr -> right;\n }\n }\n\n}"
},
{
"code": null,
"e": 4961,
"s": 4958,
"text": "+1"
},
{
"code": null,
"e": 4994,
"s": 4961,
"text": "gowthamreddyuppunuri2 months ago"
},
{
"code": null,
"e": 5729,
"s": 4994,
"text": "void findPre(Node *root,Node *&pre,int key){\n if(root == nullptr){\n return;\n }\n if(root->key < key){\n pre = root;\n //just smaller than key\n findPre(root->right,pre,key);\n }\n else if(root->key >= key){\n findPre(root->left,pre,key);\n }\n}\nvoid findSuc(Node *root,Node *&suc,int key){\n if(root == nullptr){\n return;\n }\n if(root->key <= key){\n findSuc(root->right,suc,key);\n }\n else if(root->key > key){\n //just greater find in left of root\n suc = root;\n findSuc(root->left,suc,key);\n }\n}\n\nvoid findPreSuc(Node* root, Node*& pre, Node*& suc, int key)\n{\n\n// Your code goes here\n findPre(root,pre,key);\n findSuc(root,suc,key);\n\n}"
},
{
"code": null,
"e": 5732,
"s": 5729,
"text": "+2"
},
{
"code": null,
"e": 5757,
"s": 5732,
"text": "sanketbhagat2 months ago"
},
{
"code": null,
"e": 5778,
"s": 5757,
"text": "SIMPLE JAVA SOLUTION"
},
{
"code": null,
"e": 6275,
"s": 5778,
"text": "class GfG{\n public static void findPreSuc(Node root, Res p, Res s, int key){\n // add your code here\n \n Node curr = root;\n while(curr!=null){\n if(curr.data<key){\n p.pre = curr;\n curr = curr.right;\n }else curr = curr.left;\n }\n curr = root;\n while(curr!=null){\n if(curr.data>key){\n s.succ = curr;\n curr = curr.left;\n }else curr = curr.right;\n }\n }\n}"
},
{
"code": null,
"e": 6278,
"s": 6275,
"text": "+3"
},
{
"code": null,
"e": 6302,
"s": 6278,
"text": "animesh18362 months ago"
},
{
"code": null,
"e": 6555,
"s": 6302,
"text": "void findPreSuc(Node* root, Node*& pre, Node*& suc, int key)\n{\n\n if(not root)return;\n findPreSuc(root->left,pre,suc,key);\n if(root->key < key)pre=root;\n if(root->key>key and not suc)suc=root;\n \n findPreSuc(root->right,pre,suc,key);\n\n}"
},
{
"code": null,
"e": 6703,
"s": 6557,
"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": 6739,
"s": 6703,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6749,
"s": 6739,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6759,
"s": 6749,
"text": "\nContest\n"
},
{
"code": null,
"e": 6822,
"s": 6759,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6970,
"s": 6822,
"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": 7178,
"s": 6970,
"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": 7284,
"s": 7178,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
An Overview of Methods to Address the Multiple Comparison Problem | by Paulina Zheng | Towards Data Science | As data scientists, we are uniquely positioned to assess relationships between variables within a larger context and ultimately, tell stories with statistics.
In short, we use hypothesis testing to prove some hypothesis about our data.
This is a fairly straightforward process until we want to test a set of hypotheses simultaneously. In this post, I’ll review the problems with making such multiple comparisons and how to address them accordingly.
How do we first begin to investigate our belief about a situation? Well, we can conduct so-called hypothesis tests with the data available to us, in order to assess our claim.
Let’s consider drug A, which is currently in development. We are interested in whether drug A genuinely improves patients’ self-rated pain, compared to a placebo (a ‘sugar pill’ with no therapeutic effect).
How do we demonstrably measure and determine ‘effect’? It’s not enough to simply posit that drug A is better than placebo. We want to do so with specific measurements, based on the available data. For the purposes of this example, let’s assume that patients report pain using a numerical scale from 0–10. We can collect pain scores and then compare the mean of those scores across two groups: an experimental group (taking drug A) and a control group (taking placebo). It is important to note that each group is intended to be representative of a broader patient population.
For our hypothesis test, we must specify the following:
Null Hypothesis: What we are seeking to disprove, usually the ‘status quo’ (that there is no effect or difference). Here, our null hypothesis is that there is no difference between drug A and placebo in improving self-reported pain (the means are the same).
Alternative Hypothesis: Our effect of interest, or the antithesis of the null hypothesis. We would say that our alternative hypothesis is that there is a difference between drug A and placebo in improving self-reported pain (the means are not the same).
Significance level (α): Probability of incorrectly rejecting the null hypothesis, given that it’s true (false positive). This is always established at the beginning of every hypothesis test.
Of these, α is perhaps most relevant to the multiple comparison problem. It is important to first have a thorough understanding of how α is used in hypothesis testing.
If we find a difference in the mean pain scores across the two groups, does it actually mean anything? We can define boundaries that allow us to determine whether any observed differences are extreme enough to reflect an actual effect/relationship or are more likely to be due to chance alone.
Because we have the pain scores for every patient, we can describe the distribution of the scores for each group. For this example, we will say that for both groups, the data is roughly normally distributed.
Every hypothesis test is predicated on some type of distribution for the population in question. Any given distribution is centered around the mean (μ) and characterized by the spread (standard deviation, σ) of the data. Most hypothesis tests — and the assumptions thereof — are based on the normal, or Gaussian, distribution.
As evidenced above, for our patient population, 99.7% of our data should fall within 3 standard deviations of the mean. Using this distribution, we can determine how many standard deviations a given observation is from the mean. The ‘farther’ the observation is from the mean, the more unusual it is.
More technically, the number of standard deviations from the mean can be represented by a z-score. We use the z-score as a way of standardizing what we observe and is calculated as:
With the central limit theorem, we can assume that the data is distributed normally.
We can then calculate the test-statistic for our data. We need to compare this test-statistic to some threshold. If our test-statistic exceeds this threshold, then our finding is statistically significant and unlikely to be due to chance alone.
We use our pre-determined significance level (α) to define the threshold.
Typically, α is set to be 0.05, although this may vary depending on the field of study. What does this mean? It means that if you find an effect, you are willing to be 95% confident that your results are statistically significant and there is a 5% chance that it is due to chance alone.
We can look again at our standard normal distribution that we are using to inform all our calculations.
α defines the rejection region(s) for a Gaussian curve. Extreme results exist at the tail ends of the curve, farthest from the mean. The rejection region is chosen such that the probability is equal to α that it will contain the test statistic when the null hypothesis is true.
Because our hypothesis specified only that there was a difference between drug A and placebo, we test the relationship in both directions: drug A could be either better or worse than placebo. Therefore, it’s a two-tailed hypothesis test and we look at both ends of the Gaussian curve. We distribute α equally between the two tails so each tail will contain 0.025.
Here, the p-value guides our decision. The p-value is the probability of an effect at least as extreme as that observed in sample data, if the null hypothesis were true. If the test-statistic falls within the rejection region(s), then the p-value will be less than α. We can say that we are 95% confident that drug A significantly reduces patients’ self-reported pain, compared to placebo. There is a 5% chance that the observed effect is due to chance alone. Therefore, we reject the null hypothesis.
We want to establish α from the get-go because we want to control the probability of wrongfully rejecting the null hypothesis, or our type 1 error from the get-go. This is fairly straightforward for a single hypothesis test.
But what if we want to test for multiple hypotheses? You may encounter this in AB testing, when you want to compare multiple variations of a site against each other, or multiple symptoms treated in drug testing. You would need multiple null hypotheses then, one for each ‘variation’.
Each hypothesis will have an individual α*, which represents the type 1 error rate for that particular test. As the number of hypotheses increases, so too does the overall α for the set of tests because the individual α*’s accumulate. For a single hypothesis test at the α=0.05 level, the type 1 error rate is only 5%. There is only a 5% chance of erroneously rejecting the null hypothesis. For 2 hypothesis tests, however, the overall α becomes 0.10. The probability of erroneously rejecting at least 1 null hypothesis is 0.10. The overall α quickly grows with the addition of each new comparison:
Overall α ≤ 1-(1-α*)
Now, why not just restrict to a single test and avoid this messy complication? Efficiency and practical considerations may necessitate multiple comparisons. Let’s say we are interested in how drug A reduces pain, reduces incidences of headaches, etc. It makes sense to conduct a set of tests to understand the overall efficacy of drug A, based on multiple clinically meaningful measures.
So, we want to control our type 1 error. We can approach this in two different ways.
Control overall α (also known as family-wise error rate or FWER), which will affect the α* for each test. That is, we are controlling the overall probability of making at least one false discovery. Bonferroni and Sidak corrections all control FWER.Control false discovery rate (FDR). Where FWER controls for the probability for making a type 1 error at all, these procedures allow for type 1 errors (false positives) but control the proportion of these false positives in relation to true positives. This is done by adjusting the decision made for the p-value associated with each individual test to decide rejection or not. Because this will result in a higher type 1 error rate, it has higher power. This affords a higher probability of true discoveries. The step procedures control for FDR.
Control overall α (also known as family-wise error rate or FWER), which will affect the α* for each test. That is, we are controlling the overall probability of making at least one false discovery. Bonferroni and Sidak corrections all control FWER.
Control false discovery rate (FDR). Where FWER controls for the probability for making a type 1 error at all, these procedures allow for type 1 errors (false positives) but control the proportion of these false positives in relation to true positives. This is done by adjusting the decision made for the p-value associated with each individual test to decide rejection or not. Because this will result in a higher type 1 error rate, it has higher power. This affords a higher probability of true discoveries. The step procedures control for FDR.
Below, I’ll provide a brief overview of available correction procedures for multiple comparisons.
Bonferroni CorrectionThe most conservative of corrections, the Bonferroni correction is also perhaps the most straightforward in its approach. Simply divide α by the number of tests (m).
However, with many tests, α* will become very small. This reduces power, which means that we are very unlikely to make any true discoveries.
Sidak Correctionα* = 1-(1-α)^(1/m)
Holm’s Step-Down ProcedureAn update of the Bonferroni correction, this procedure is more powerful. Rather than controlling the FMER, Holm’s procedure controls for the false discovery rate (FDR) and performed after conducting all hypothesis tests and finding associated p-values at α within a set.
The step-down procedure is best illustrated with an example. Say we have three hypotheses, each with the associated p-value:
H1: 0.025H2: 0.003H3: 0.01
Step 1: Order p-values from smallest to greatest
H2: 0.003H3: 0.01H1: 0.025
Step 2: Use the Holm-Bonferroni formula for the first-ranked (smallest) p-value
α* = α/(n-rank+1)
α* = 0.05/(3–1+1) = 0.0167
Step 3: Compare the first-ranked p-value with the α* calculated from Step 2
0.003 < 0.0167
Because the p-value for H2 is less than the calculated α*, we can reject H2.
Move onto the next ranked p-value and repeat steps 2–3, calculating the α* for its respective rank and comparing it to that p-value. Continue until you reach the first non-rejected hypothesis. You would then fail to reject all following hypotheses.
Hochberg’s Step-Up ProcedureMore powerful than Holm’s step-down procedure, Hochberg’s step-up procedure also seeks to control the FDR and follows a similar process, only p-values are ranked from largest to smallest.
For each ranked p-value, it is compared to the α* calculated for its respective rank (same formula as Holm’s procedure). Testing continues until you reach the first non-rejected hypothesis. You would then fail to reject all following hypotheses.
For the purposes of this blog post, I will only briefly refer to two other well-known correction methods, which are a bit more involved than this blog post can accommodate.
Tukey’s ProcedureTukey’s procedure is a single-step multiple comparison test and is only applicable if you are interested in comparing all possible pairs of means; it does so simultaneously. It is essentially a t-test that corrects for FWER.
Dunnet’s CorrectionDunnet’s correction is similar to Tukey’s procedure except that it involves the comparison of every mean to a single control mean.
Both these procedures make use of the ANOVA test which allows you to test multiple groups, to see if there is a significant difference between any of the groups (null hypothesis: μ1 = μ2=...=μk). Tukey’s procedure or Dunnet’s correction can then allow you to identify which pairs are significantly different.
Certainly, making multiple comparisons is not simple. However, I hope this post has helped to elucidate the options that we, as data scientists, have in order to reduce false conclusions while at the same time, having enough flexibility to make some true conclusions. | [
{
"code": null,
"e": 330,
"s": 171,
"text": "As data scientists, we are uniquely positioned to assess relationships between variables within a larger context and ultimately, tell stories with statistics."
},
{
"code": null,
"e": 407,
"s": 330,
"text": "In short, we use hypothesis testing to prove some hypothesis about our data."
},
{
"code": null,
"e": 620,
"s": 407,
"text": "This is a fairly straightforward process until we want to test a set of hypotheses simultaneously. In this post, I’ll review the problems with making such multiple comparisons and how to address them accordingly."
},
{
"code": null,
"e": 796,
"s": 620,
"text": "How do we first begin to investigate our belief about a situation? Well, we can conduct so-called hypothesis tests with the data available to us, in order to assess our claim."
},
{
"code": null,
"e": 1003,
"s": 796,
"text": "Let’s consider drug A, which is currently in development. We are interested in whether drug A genuinely improves patients’ self-rated pain, compared to a placebo (a ‘sugar pill’ with no therapeutic effect)."
},
{
"code": null,
"e": 1578,
"s": 1003,
"text": "How do we demonstrably measure and determine ‘effect’? It’s not enough to simply posit that drug A is better than placebo. We want to do so with specific measurements, based on the available data. For the purposes of this example, let’s assume that patients report pain using a numerical scale from 0–10. We can collect pain scores and then compare the mean of those scores across two groups: an experimental group (taking drug A) and a control group (taking placebo). It is important to note that each group is intended to be representative of a broader patient population."
},
{
"code": null,
"e": 1634,
"s": 1578,
"text": "For our hypothesis test, we must specify the following:"
},
{
"code": null,
"e": 1892,
"s": 1634,
"text": "Null Hypothesis: What we are seeking to disprove, usually the ‘status quo’ (that there is no effect or difference). Here, our null hypothesis is that there is no difference between drug A and placebo in improving self-reported pain (the means are the same)."
},
{
"code": null,
"e": 2146,
"s": 1892,
"text": "Alternative Hypothesis: Our effect of interest, or the antithesis of the null hypothesis. We would say that our alternative hypothesis is that there is a difference between drug A and placebo in improving self-reported pain (the means are not the same)."
},
{
"code": null,
"e": 2337,
"s": 2146,
"text": "Significance level (α): Probability of incorrectly rejecting the null hypothesis, given that it’s true (false positive). This is always established at the beginning of every hypothesis test."
},
{
"code": null,
"e": 2505,
"s": 2337,
"text": "Of these, α is perhaps most relevant to the multiple comparison problem. It is important to first have a thorough understanding of how α is used in hypothesis testing."
},
{
"code": null,
"e": 2799,
"s": 2505,
"text": "If we find a difference in the mean pain scores across the two groups, does it actually mean anything? We can define boundaries that allow us to determine whether any observed differences are extreme enough to reflect an actual effect/relationship or are more likely to be due to chance alone."
},
{
"code": null,
"e": 3007,
"s": 2799,
"text": "Because we have the pain scores for every patient, we can describe the distribution of the scores for each group. For this example, we will say that for both groups, the data is roughly normally distributed."
},
{
"code": null,
"e": 3334,
"s": 3007,
"text": "Every hypothesis test is predicated on some type of distribution for the population in question. Any given distribution is centered around the mean (μ) and characterized by the spread (standard deviation, σ) of the data. Most hypothesis tests — and the assumptions thereof — are based on the normal, or Gaussian, distribution."
},
{
"code": null,
"e": 3635,
"s": 3334,
"text": "As evidenced above, for our patient population, 99.7% of our data should fall within 3 standard deviations of the mean. Using this distribution, we can determine how many standard deviations a given observation is from the mean. The ‘farther’ the observation is from the mean, the more unusual it is."
},
{
"code": null,
"e": 3817,
"s": 3635,
"text": "More technically, the number of standard deviations from the mean can be represented by a z-score. We use the z-score as a way of standardizing what we observe and is calculated as:"
},
{
"code": null,
"e": 3902,
"s": 3817,
"text": "With the central limit theorem, we can assume that the data is distributed normally."
},
{
"code": null,
"e": 4147,
"s": 3902,
"text": "We can then calculate the test-statistic for our data. We need to compare this test-statistic to some threshold. If our test-statistic exceeds this threshold, then our finding is statistically significant and unlikely to be due to chance alone."
},
{
"code": null,
"e": 4221,
"s": 4147,
"text": "We use our pre-determined significance level (α) to define the threshold."
},
{
"code": null,
"e": 4508,
"s": 4221,
"text": "Typically, α is set to be 0.05, although this may vary depending on the field of study. What does this mean? It means that if you find an effect, you are willing to be 95% confident that your results are statistically significant and there is a 5% chance that it is due to chance alone."
},
{
"code": null,
"e": 4612,
"s": 4508,
"text": "We can look again at our standard normal distribution that we are using to inform all our calculations."
},
{
"code": null,
"e": 4890,
"s": 4612,
"text": "α defines the rejection region(s) for a Gaussian curve. Extreme results exist at the tail ends of the curve, farthest from the mean. The rejection region is chosen such that the probability is equal to α that it will contain the test statistic when the null hypothesis is true."
},
{
"code": null,
"e": 5254,
"s": 4890,
"text": "Because our hypothesis specified only that there was a difference between drug A and placebo, we test the relationship in both directions: drug A could be either better or worse than placebo. Therefore, it’s a two-tailed hypothesis test and we look at both ends of the Gaussian curve. We distribute α equally between the two tails so each tail will contain 0.025."
},
{
"code": null,
"e": 5756,
"s": 5254,
"text": "Here, the p-value guides our decision. The p-value is the probability of an effect at least as extreme as that observed in sample data, if the null hypothesis were true. If the test-statistic falls within the rejection region(s), then the p-value will be less than α. We can say that we are 95% confident that drug A significantly reduces patients’ self-reported pain, compared to placebo. There is a 5% chance that the observed effect is due to chance alone. Therefore, we reject the null hypothesis."
},
{
"code": null,
"e": 5981,
"s": 5756,
"text": "We want to establish α from the get-go because we want to control the probability of wrongfully rejecting the null hypothesis, or our type 1 error from the get-go. This is fairly straightforward for a single hypothesis test."
},
{
"code": null,
"e": 6265,
"s": 5981,
"text": "But what if we want to test for multiple hypotheses? You may encounter this in AB testing, when you want to compare multiple variations of a site against each other, or multiple symptoms treated in drug testing. You would need multiple null hypotheses then, one for each ‘variation’."
},
{
"code": null,
"e": 6864,
"s": 6265,
"text": "Each hypothesis will have an individual α*, which represents the type 1 error rate for that particular test. As the number of hypotheses increases, so too does the overall α for the set of tests because the individual α*’s accumulate. For a single hypothesis test at the α=0.05 level, the type 1 error rate is only 5%. There is only a 5% chance of erroneously rejecting the null hypothesis. For 2 hypothesis tests, however, the overall α becomes 0.10. The probability of erroneously rejecting at least 1 null hypothesis is 0.10. The overall α quickly grows with the addition of each new comparison:"
},
{
"code": null,
"e": 6885,
"s": 6864,
"text": "Overall α ≤ 1-(1-α*)"
},
{
"code": null,
"e": 7273,
"s": 6885,
"text": "Now, why not just restrict to a single test and avoid this messy complication? Efficiency and practical considerations may necessitate multiple comparisons. Let’s say we are interested in how drug A reduces pain, reduces incidences of headaches, etc. It makes sense to conduct a set of tests to understand the overall efficacy of drug A, based on multiple clinically meaningful measures."
},
{
"code": null,
"e": 7358,
"s": 7273,
"text": "So, we want to control our type 1 error. We can approach this in two different ways."
},
{
"code": null,
"e": 8152,
"s": 7358,
"text": "Control overall α (also known as family-wise error rate or FWER), which will affect the α* for each test. That is, we are controlling the overall probability of making at least one false discovery. Bonferroni and Sidak corrections all control FWER.Control false discovery rate (FDR). Where FWER controls for the probability for making a type 1 error at all, these procedures allow for type 1 errors (false positives) but control the proportion of these false positives in relation to true positives. This is done by adjusting the decision made for the p-value associated with each individual test to decide rejection or not. Because this will result in a higher type 1 error rate, it has higher power. This affords a higher probability of true discoveries. The step procedures control for FDR."
},
{
"code": null,
"e": 8401,
"s": 8152,
"text": "Control overall α (also known as family-wise error rate or FWER), which will affect the α* for each test. That is, we are controlling the overall probability of making at least one false discovery. Bonferroni and Sidak corrections all control FWER."
},
{
"code": null,
"e": 8947,
"s": 8401,
"text": "Control false discovery rate (FDR). Where FWER controls for the probability for making a type 1 error at all, these procedures allow for type 1 errors (false positives) but control the proportion of these false positives in relation to true positives. This is done by adjusting the decision made for the p-value associated with each individual test to decide rejection or not. Because this will result in a higher type 1 error rate, it has higher power. This affords a higher probability of true discoveries. The step procedures control for FDR."
},
{
"code": null,
"e": 9045,
"s": 8947,
"text": "Below, I’ll provide a brief overview of available correction procedures for multiple comparisons."
},
{
"code": null,
"e": 9232,
"s": 9045,
"text": "Bonferroni CorrectionThe most conservative of corrections, the Bonferroni correction is also perhaps the most straightforward in its approach. Simply divide α by the number of tests (m)."
},
{
"code": null,
"e": 9373,
"s": 9232,
"text": "However, with many tests, α* will become very small. This reduces power, which means that we are very unlikely to make any true discoveries."
},
{
"code": null,
"e": 9408,
"s": 9373,
"text": "Sidak Correctionα* = 1-(1-α)^(1/m)"
},
{
"code": null,
"e": 9705,
"s": 9408,
"text": "Holm’s Step-Down ProcedureAn update of the Bonferroni correction, this procedure is more powerful. Rather than controlling the FMER, Holm’s procedure controls for the false discovery rate (FDR) and performed after conducting all hypothesis tests and finding associated p-values at α within a set."
},
{
"code": null,
"e": 9830,
"s": 9705,
"text": "The step-down procedure is best illustrated with an example. Say we have three hypotheses, each with the associated p-value:"
},
{
"code": null,
"e": 9857,
"s": 9830,
"text": "H1: 0.025H2: 0.003H3: 0.01"
},
{
"code": null,
"e": 9906,
"s": 9857,
"text": "Step 1: Order p-values from smallest to greatest"
},
{
"code": null,
"e": 9933,
"s": 9906,
"text": "H2: 0.003H3: 0.01H1: 0.025"
},
{
"code": null,
"e": 10013,
"s": 9933,
"text": "Step 2: Use the Holm-Bonferroni formula for the first-ranked (smallest) p-value"
},
{
"code": null,
"e": 10031,
"s": 10013,
"text": "α* = α/(n-rank+1)"
},
{
"code": null,
"e": 10058,
"s": 10031,
"text": "α* = 0.05/(3–1+1) = 0.0167"
},
{
"code": null,
"e": 10134,
"s": 10058,
"text": "Step 3: Compare the first-ranked p-value with the α* calculated from Step 2"
},
{
"code": null,
"e": 10149,
"s": 10134,
"text": "0.003 < 0.0167"
},
{
"code": null,
"e": 10226,
"s": 10149,
"text": "Because the p-value for H2 is less than the calculated α*, we can reject H2."
},
{
"code": null,
"e": 10475,
"s": 10226,
"text": "Move onto the next ranked p-value and repeat steps 2–3, calculating the α* for its respective rank and comparing it to that p-value. Continue until you reach the first non-rejected hypothesis. You would then fail to reject all following hypotheses."
},
{
"code": null,
"e": 10691,
"s": 10475,
"text": "Hochberg’s Step-Up ProcedureMore powerful than Holm’s step-down procedure, Hochberg’s step-up procedure also seeks to control the FDR and follows a similar process, only p-values are ranked from largest to smallest."
},
{
"code": null,
"e": 10937,
"s": 10691,
"text": "For each ranked p-value, it is compared to the α* calculated for its respective rank (same formula as Holm’s procedure). Testing continues until you reach the first non-rejected hypothesis. You would then fail to reject all following hypotheses."
},
{
"code": null,
"e": 11110,
"s": 10937,
"text": "For the purposes of this blog post, I will only briefly refer to two other well-known correction methods, which are a bit more involved than this blog post can accommodate."
},
{
"code": null,
"e": 11352,
"s": 11110,
"text": "Tukey’s ProcedureTukey’s procedure is a single-step multiple comparison test and is only applicable if you are interested in comparing all possible pairs of means; it does so simultaneously. It is essentially a t-test that corrects for FWER."
},
{
"code": null,
"e": 11502,
"s": 11352,
"text": "Dunnet’s CorrectionDunnet’s correction is similar to Tukey’s procedure except that it involves the comparison of every mean to a single control mean."
},
{
"code": null,
"e": 11811,
"s": 11502,
"text": "Both these procedures make use of the ANOVA test which allows you to test multiple groups, to see if there is a significant difference between any of the groups (null hypothesis: μ1 = μ2=...=μk). Tukey’s procedure or Dunnet’s correction can then allow you to identify which pairs are significantly different."
}
] |
EasyGUI – Text Box - GeeksforGeeks | 14 Mar, 2022
Text Box : It is used to show and get the text to/from the user, text can be edited using any keyboard input, it takes input in form of string. It displays the title, message to be displayed, place to alter the given text and a pair of “Ok”, “Cancel” button which is used confirm the text. It is similar to enter text but used to show large text and it word-wrap the given text, below is how the enter box looks like
In order to do this we will use textbox methodSyntax : textbox(message, title, text)Argument : It takes 3 arguments, first string i.e message/information to be displayed, second string i.e title of the window and third is string which is the editable textReturn : It returns the altered text and None if cancel is pressed
Example : In this we will create a text box with editable text, and will show the specific text on the screen according to the altered text, below is the implementation
Python3
# importing easygui modulefrom easygui import * # message to be displayedmessage = "Below is the text to edit" # window titletitle = "Window Title GfG" # long texttext = ["EasyGUI is a module for very simple, very easy GUI ","programming in Python. EasyGUI is different from other","GUI generators in that EasyGUI is NOT event-driven."] # creating a multi password boxoutput = textbox(message, title, text) # showing the outputprint("Altered Text ")print("================")print(output)
Output :
Altered Text
================
EasyGUI is a module for very simple, very easy GUI programming in Python. EasyGUI is different from otherGUI generators in that EasyGUI is NOT event-driven. geeksforgeeks
Another Example : In this we will create a text box without any editable text, and will show the specific text on the screen according to the altered text, below is the implementation
Python3
# importing easygui modulefrom easygui import * # message to be displayedmessage = "Below is the text to edit" # window titletitle = "Window Title GfG" # creating a multi password boxoutput = textbox(message, title) # showing the outputprint("Altered Text ")print("================")print(output)
Output :
Altered Text
================
Welcome to geeksforgeeks ajkbkjbajxblcblc;c
sumitgumber28
Python-EasyGUI
Python-gui
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 24397,
"s": 24369,
"text": "\n14 Mar, 2022"
},
{
"code": null,
"e": 24816,
"s": 24397,
"text": "Text Box : It is used to show and get the text to/from the user, text can be edited using any keyboard input, it takes input in form of string. It displays the title, message to be displayed, place to alter the given text and a pair of “Ok”, “Cancel” button which is used confirm the text. It is similar to enter text but used to show large text and it word-wrap the given text, below is how the enter box looks like "
},
{
"code": null,
"e": 25142,
"s": 24818,
"text": "In order to do this we will use textbox methodSyntax : textbox(message, title, text)Argument : It takes 3 arguments, first string i.e message/information to be displayed, second string i.e title of the window and third is string which is the editable textReturn : It returns the altered text and None if cancel is pressed "
},
{
"code": null,
"e": 25313,
"s": 25142,
"text": "Example : In this we will create a text box with editable text, and will show the specific text on the screen according to the altered text, below is the implementation "
},
{
"code": null,
"e": 25321,
"s": 25313,
"text": "Python3"
},
{
"code": "# importing easygui modulefrom easygui import * # message to be displayedmessage = \"Below is the text to edit\" # window titletitle = \"Window Title GfG\" # long texttext = [\"EasyGUI is a module for very simple, very easy GUI \",\"programming in Python. EasyGUI is different from other\",\"GUI generators in that EasyGUI is NOT event-driven.\"] # creating a multi password boxoutput = textbox(message, title, text) # showing the outputprint(\"Altered Text \")print(\"================\")print(output)",
"e": 25817,
"s": 25321,
"text": null
},
{
"code": null,
"e": 25828,
"s": 25817,
"text": "Output : "
},
{
"code": null,
"e": 26032,
"s": 25830,
"text": "Altered Text \n================\nEasyGUI is a module for very simple, very easy GUI programming in Python. EasyGUI is different from otherGUI generators in that EasyGUI is NOT event-driven. geeksforgeeks"
},
{
"code": null,
"e": 26218,
"s": 26032,
"text": "Another Example : In this we will create a text box without any editable text, and will show the specific text on the screen according to the altered text, below is the implementation "
},
{
"code": null,
"e": 26226,
"s": 26218,
"text": "Python3"
},
{
"code": "# importing easygui modulefrom easygui import * # message to be displayedmessage = \"Below is the text to edit\" # window titletitle = \"Window Title GfG\" # creating a multi password boxoutput = textbox(message, title) # showing the outputprint(\"Altered Text \")print(\"================\")print(output)",
"e": 26532,
"s": 26226,
"text": null
},
{
"code": null,
"e": 26543,
"s": 26532,
"text": "Output : "
},
{
"code": null,
"e": 26620,
"s": 26545,
"text": "Altered Text \n================\nWelcome to geeksforgeeks ajkbkjbajxblcblc;c"
},
{
"code": null,
"e": 26636,
"s": 26622,
"text": "sumitgumber28"
},
{
"code": null,
"e": 26651,
"s": 26636,
"text": "Python-EasyGUI"
},
{
"code": null,
"e": 26662,
"s": 26651,
"text": "Python-gui"
},
{
"code": null,
"e": 26669,
"s": 26662,
"text": "Python"
},
{
"code": null,
"e": 26767,
"s": 26669,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26776,
"s": 26767,
"text": "Comments"
},
{
"code": null,
"e": 26789,
"s": 26776,
"text": "Old Comments"
},
{
"code": null,
"e": 26807,
"s": 26789,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26842,
"s": 26807,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26864,
"s": 26842,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26896,
"s": 26864,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26926,
"s": 26896,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26968,
"s": 26926,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27011,
"s": 26968,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27055,
"s": 27011,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27080,
"s": 27055,
"text": "sum() function in Python"
}
] |
LISP - CLOS | Common LISP predated the advance of object-oriented programming by couple of decades. However, it object-orientation was incorporated into it at a later stage.
The defclass macro allows creating user-defined classes. It establishes a class as a data type. It has the following syntax −
(defclass class-name (superclass-name*)
(slot-description*)
class-option*))
The slots are variables that store data, or fields.
A slot-description has the form (slot-name slot-option*), where each option is a keyword followed by a name, expression and other options. Most commonly used slot options are −
:accessor function-name
:accessor function-name
:initform expression
:initform expression
:initarg symbol
:initarg symbol
For example, let us define a Box class, with three slots length, breadth, and height.
(defclass Box ()
(length
breadth
height)
)
Unless the slots have values that can be accessed, read or written to, classes are pretty useless.
You can specify accessors for each slot when you define a class. For example, take our Box class −
(defclass Box ()
((length :accessor length)
(breadth :accessor breadth)
(height :accessor height)
)
)
You can also specify separate accessor names for reading and writing a slot.
(defclass Box ()
((length :reader get-length :writer set-length)
(breadth :reader get-breadth :writer set-breadth)
(height :reader get-height :writer set-height)
)
)
The generic function make-instance creates and returns a new instance of a class.
It has the following syntax −
(make-instance class {initarg value}*)
Let us create a Box class, with three slots, length, breadth and height. We will use three slot accessors to set the values in these fields.
Create a new source code file named main.lisp and type the following code in it.
(defclass box ()
((length :accessor box-length)
(breadth :accessor box-breadth)
(height :accessor box-height)
)
)
(setf item (make-instance 'box))
(setf (box-length item) 10)
(setf (box-breadth item) 10)
(setf (box-height item) 5)
(format t "Length of the Box is ~d~%" (box-length item))
(format t "Breadth of the Box is ~d~%" (box-breadth item))
(format t "Height of the Box is ~d~%" (box-height item))
When you execute the code, it returns the following result −
Length of the Box is 10
Breadth of the Box is 10
Height of the Box is 5
The defmethod macro allows you to define a method inside the class. The following example extends our Box class to include a method named volume.
Create a new source code file named main.lisp and type the following code in it.
(defclass box ()
((length :accessor box-length)
(breadth :accessor box-breadth)
(height :accessor box-height)
(volume :reader volume)
)
)
; method calculating volume
(defmethod volume ((object box))
(* (box-length object) (box-breadth object)(box-height object))
)
;setting the values
(setf item (make-instance 'box))
(setf (box-length item) 10)
(setf (box-breadth item) 10)
(setf (box-height item) 5)
; displaying values
(format t "Length of the Box is ~d~%" (box-length item))
(format t "Breadth of the Box is ~d~%" (box-breadth item))
(format t "Height of the Box is ~d~%" (box-height item))
(format t "Volume of the Box is ~d~%" (volume item))
When you execute the code, it returns the following result −
Length of the Box is 10
Breadth of the Box is 10
Height of the Box is 5
Volume of the Box is 500
LISP allows you to define an object in terms of another object. This is called inheritance. You can create a derived class by adding features that are new or different. The derived class inherits the functionalities of the parent class.
The following example explains this −
Create a new source code file named main.lisp and type the following code in it.
(defclass box ()
((length :accessor box-length)
(breadth :accessor box-breadth)
(height :accessor box-height)
(volume :reader volume)
)
)
; method calculating volume
(defmethod volume ((object box))
(* (box-length object) (box-breadth object)(box-height object))
)
;wooden-box class inherits the box class
(defclass wooden-box (box)
((price :accessor box-price)))
;setting the values
(setf item (make-instance 'wooden-box))
(setf (box-length item) 10)
(setf (box-breadth item) 10)
(setf (box-height item) 5)
(setf (box-price item) 1000)
; displaying values
(format t "Length of the Wooden Box is ~d~%" (box-length item))
(format t "Breadth of the Wooden Box is ~d~%" (box-breadth item))
(format t "Height of the Wooden Box is ~d~%" (box-height item))
(format t "Volume of the Wooden Box is ~d~%" (volume item))
(format t "Price of the Wooden Box is ~d~%" (box-price item))
When you execute the code, it returns the following result −
Length of the Wooden Box is 10
Breadth of the Wooden Box is 10
Height of the Wooden Box is 5
Volume of the Wooden Box is 500
Price of the Wooden Box is 1000
79 Lectures
7 hours
Arnold Higuit
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2220,
"s": 2060,
"text": "Common LISP predated the advance of object-oriented programming by couple of decades. However, it object-orientation was incorporated into it at a later stage."
},
{
"code": null,
"e": 2346,
"s": 2220,
"text": "The defclass macro allows creating user-defined classes. It establishes a class as a data type. It has the following syntax −"
},
{
"code": null,
"e": 2428,
"s": 2346,
"text": "(defclass class-name (superclass-name*)\n (slot-description*)\n class-option*))"
},
{
"code": null,
"e": 2480,
"s": 2428,
"text": "The slots are variables that store data, or fields."
},
{
"code": null,
"e": 2657,
"s": 2480,
"text": "A slot-description has the form (slot-name slot-option*), where each option is a keyword followed by a name, expression and other options. Most commonly used slot options are −"
},
{
"code": null,
"e": 2681,
"s": 2657,
"text": ":accessor function-name"
},
{
"code": null,
"e": 2705,
"s": 2681,
"text": ":accessor function-name"
},
{
"code": null,
"e": 2726,
"s": 2705,
"text": ":initform expression"
},
{
"code": null,
"e": 2747,
"s": 2726,
"text": ":initform expression"
},
{
"code": null,
"e": 2763,
"s": 2747,
"text": ":initarg symbol"
},
{
"code": null,
"e": 2779,
"s": 2763,
"text": ":initarg symbol"
},
{
"code": null,
"e": 2865,
"s": 2779,
"text": "For example, let us define a Box class, with three slots length, breadth, and height."
},
{
"code": null,
"e": 2921,
"s": 2865,
"text": "(defclass Box () \n (length \n breadth \n height)\n)\n"
},
{
"code": null,
"e": 3020,
"s": 2921,
"text": "Unless the slots have values that can be accessed, read or written to, classes are pretty useless."
},
{
"code": null,
"e": 3119,
"s": 3020,
"text": "You can specify accessors for each slot when you define a class. For example, take our Box class −"
},
{
"code": null,
"e": 3239,
"s": 3119,
"text": "(defclass Box ()\n ((length :accessor length)\n (breadth :accessor breadth)\n (height :accessor height)\n )\n)"
},
{
"code": null,
"e": 3316,
"s": 3239,
"text": "You can also specify separate accessor names for reading and writing a slot."
},
{
"code": null,
"e": 3500,
"s": 3316,
"text": "(defclass Box ()\n ((length :reader get-length :writer set-length)\n (breadth :reader get-breadth :writer set-breadth)\n (height :reader get-height :writer set-height)\n )\n)"
},
{
"code": null,
"e": 3582,
"s": 3500,
"text": "The generic function make-instance creates and returns a new instance of a class."
},
{
"code": null,
"e": 3612,
"s": 3582,
"text": "It has the following syntax −"
},
{
"code": null,
"e": 3652,
"s": 3612,
"text": "(make-instance class {initarg value}*)\n"
},
{
"code": null,
"e": 3793,
"s": 3652,
"text": "Let us create a Box class, with three slots, length, breadth and height. We will use three slot accessors to set the values in these fields."
},
{
"code": null,
"e": 3874,
"s": 3793,
"text": "Create a new source code file named main.lisp and type the following code in it."
},
{
"code": null,
"e": 4296,
"s": 3874,
"text": "(defclass box ()\n ((length :accessor box-length)\n (breadth :accessor box-breadth)\n (height :accessor box-height)\n )\n)\n(setf item (make-instance 'box))\n(setf (box-length item) 10)\n(setf (box-breadth item) 10)\n(setf (box-height item) 5)\n(format t \"Length of the Box is ~d~%\" (box-length item))\n(format t \"Breadth of the Box is ~d~%\" (box-breadth item))\n(format t \"Height of the Box is ~d~%\" (box-height item))"
},
{
"code": null,
"e": 4357,
"s": 4296,
"text": "When you execute the code, it returns the following result −"
},
{
"code": null,
"e": 4430,
"s": 4357,
"text": "Length of the Box is 10\nBreadth of the Box is 10\nHeight of the Box is 5\n"
},
{
"code": null,
"e": 4576,
"s": 4430,
"text": "The defmethod macro allows you to define a method inside the class. The following example extends our Box class to include a method named volume."
},
{
"code": null,
"e": 4657,
"s": 4576,
"text": "Create a new source code file named main.lisp and type the following code in it."
},
{
"code": null,
"e": 5343,
"s": 4657,
"text": "(defclass box ()\n ((length :accessor box-length)\n (breadth :accessor box-breadth)\n (height :accessor box-height)\n (volume :reader volume)\n )\n)\n\n; method calculating volume \n\n(defmethod volume ((object box))\n (* (box-length object) (box-breadth object)(box-height object))\n)\n\n ;setting the values \n\n(setf item (make-instance 'box))\n(setf (box-length item) 10)\n(setf (box-breadth item) 10)\n(setf (box-height item) 5)\n\n; displaying values\n\n(format t \"Length of the Box is ~d~%\" (box-length item))\n(format t \"Breadth of the Box is ~d~%\" (box-breadth item))\n(format t \"Height of the Box is ~d~%\" (box-height item))\n(format t \"Volume of the Box is ~d~%\" (volume item))"
},
{
"code": null,
"e": 5404,
"s": 5343,
"text": "When you execute the code, it returns the following result −"
},
{
"code": null,
"e": 5502,
"s": 5404,
"text": "Length of the Box is 10\nBreadth of the Box is 10\nHeight of the Box is 5\nVolume of the Box is 500\n"
},
{
"code": null,
"e": 5739,
"s": 5502,
"text": "LISP allows you to define an object in terms of another object. This is called inheritance. You can create a derived class by adding features that are new or different. The derived class inherits the functionalities of the parent class."
},
{
"code": null,
"e": 5777,
"s": 5739,
"text": "The following example explains this −"
},
{
"code": null,
"e": 5858,
"s": 5777,
"text": "Create a new source code file named main.lisp and type the following code in it."
},
{
"code": null,
"e": 6770,
"s": 5858,
"text": "(defclass box ()\n ((length :accessor box-length)\n (breadth :accessor box-breadth)\n (height :accessor box-height)\n (volume :reader volume)\n )\n)\n\n; method calculating volume \n(defmethod volume ((object box))\n (* (box-length object) (box-breadth object)(box-height object))\n)\n \n;wooden-box class inherits the box class \n(defclass wooden-box (box)\n((price :accessor box-price)))\n\n;setting the values \n(setf item (make-instance 'wooden-box))\n(setf (box-length item) 10)\n(setf (box-breadth item) 10)\n(setf (box-height item) 5)\n(setf (box-price item) 1000)\n\n; displaying values\n(format t \"Length of the Wooden Box is ~d~%\" (box-length item))\n(format t \"Breadth of the Wooden Box is ~d~%\" (box-breadth item))\n(format t \"Height of the Wooden Box is ~d~%\" (box-height item))\n(format t \"Volume of the Wooden Box is ~d~%\" (volume item))\n(format t \"Price of the Wooden Box is ~d~%\" (box-price item))"
},
{
"code": null,
"e": 6831,
"s": 6770,
"text": "When you execute the code, it returns the following result −"
},
{
"code": null,
"e": 6989,
"s": 6831,
"text": "Length of the Wooden Box is 10\nBreadth of the Wooden Box is 10\nHeight of the Wooden Box is 5\nVolume of the Wooden Box is 500\nPrice of the Wooden Box is 1000\n"
},
{
"code": null,
"e": 7022,
"s": 6989,
"text": "\n 79 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 7037,
"s": 7022,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 7044,
"s": 7037,
"text": " Print"
},
{
"code": null,
"e": 7055,
"s": 7044,
"text": " Add Notes"
}
] |
How to merge rows in MySQL? | To merge rows in MySQL, use GROUP_CONCAT().
Let us first create a table−
mysql> create table DemoTable734 (
Id int,
Name varchar(100)
);
Query OK, 0 rows affected (0.73 sec)
Insert some records in the table using insert command−
mysql> insert into DemoTable734 values(101,'John');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable734 values(102,'John');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable734 values(103,'Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable734 values(104,'Chris');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable734 values(104,'Chris');
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement−
mysql> select *from DemoTable734;
This will produce the following output -
+------+-------+
| Id | Name |
+------+-------+
| 101 | John |
| 102 | John |
| 103 | Chris |
| 104 | Chris |
| 104 | Chris |
+------+-------+
5 rows in set (0.00 sec)
Following is the query to merge rows−
mysql> select Name,group_concat(Distinct Id SEPARATOR ',') from DemoTable734 group by Name;
This will produce the following output -
+-------+-----------------------------------------+
| Name | group_concat(Distinct Id SEPARATOR ',') |
+-------+-----------------------------------------+
| Chris | 103,104 |
| John | 101,102 |
+-------+-----------------------------------------+
2 rows in set (0.04 sec) | [
{
"code": null,
"e": 1106,
"s": 1062,
"text": "To merge rows in MySQL, use GROUP_CONCAT()."
},
{
"code": null,
"e": 1135,
"s": 1106,
"text": "Let us first create a table−"
},
{
"code": null,
"e": 1242,
"s": 1135,
"text": "mysql> create table DemoTable734 (\n Id int,\n Name varchar(100)\n);\nQuery OK, 0 rows affected (0.73 sec)"
},
{
"code": null,
"e": 1297,
"s": 1242,
"text": "Insert some records in the table using insert command−"
},
{
"code": null,
"e": 1740,
"s": 1297,
"text": "mysql> insert into DemoTable734 values(101,'John');\nQuery OK, 1 row affected (0.23 sec)\nmysql> insert into DemoTable734 values(102,'John');\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into DemoTable734 values(103,'Chris');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable734 values(104,'Chris');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable734 values(104,'Chris');\nQuery OK, 1 row affected (0.13 sec)"
},
{
"code": null,
"e": 1799,
"s": 1740,
"text": "Display all records from the table using select statement−"
},
{
"code": null,
"e": 1833,
"s": 1799,
"text": "mysql> select *from DemoTable734;"
},
{
"code": null,
"e": 1874,
"s": 1833,
"text": "This will produce the following output -"
},
{
"code": null,
"e": 2052,
"s": 1874,
"text": "+------+-------+\n| Id | Name |\n+------+-------+\n| 101 | John |\n| 102 | John |\n| 103 | Chris |\n| 104 | Chris |\n| 104 | Chris |\n+------+-------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2090,
"s": 2052,
"text": "Following is the query to merge rows−"
},
{
"code": null,
"e": 2182,
"s": 2090,
"text": "mysql> select Name,group_concat(Distinct Id SEPARATOR ',') from DemoTable734 group by Name;"
},
{
"code": null,
"e": 2223,
"s": 2182,
"text": "This will produce the following output -"
},
{
"code": null,
"e": 2560,
"s": 2223,
"text": "+-------+-----------------------------------------+\n| Name | group_concat(Distinct Id SEPARATOR ',') |\n+-------+-----------------------------------------+\n| Chris | 103,104 |\n| John | 101,102 |\n+-------+-----------------------------------------+\n2 rows in set (0.04 sec)"
}
] |
Subsets and Splits