title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Cron Jobs in Arduino
|
The CronAlarms library in Arduino helps you set cron jobs in Arduino. If you aren't aware of cron jobs, they are scheduled tasks to be carried out at a fixed time interval. An example can be sending a health packet to a server every day at midnight.
In order to install this library, search for CronAlarms in the Library Manager and install the library by Martin Laclaustra.
Once installed, go to - File → Examples → CronAlarms.
Open CronAlarms_example. If you go through the example, you will see that they are doing the following −
Set the time to Saturday 8:29:00am Jan 1 2011, using the tm struct (time library)
Set the time to Saturday 8:29:00am Jan 1 2011, using the tm struct (time library)
Sets 6 Cron alarms, daily, weekly, at interval of few seconds, and even a one-time triggered non-repeating alarm.
Sets 6 Cron alarms, daily, weekly, at interval of few seconds, and even a one-time triggered non-repeating alarm.
The one-time triggered non-repeating alarm, in fact, disables the 2-second cron.
The one-time triggered non-repeating alarm, in fact, disables the 2-second cron.
Within the loop, the current time is printed every second.
Within the loop, the current time is printed every second.
The cron creation syntax is -
CronID_t create(const char * cronstring, OnTick_t onTickHandler, bool isOneShot);
Where
cronstring provides the cron interval,
cronstring provides the cron interval,
onTickHandler is the function that will be called when the alarm is triggered,
onTickHandler is the function that will be called when the alarm is triggered,
isOneShot determines if the alarm is repeating or is a one-time interval.
isOneShot determines if the alarm is repeating or is a one-time interval.
This function returns a cron ID, which can be used to reference the alarm elsewhere in the code, as is done in the 10-second alarm, to disable the 2-second alarm, using Cron.free().
//creating the 2-second repeating alarm and 10-second single-shot alarm
// timer for every 2 seconds
id = Cron.create("*/2 * * * * *", Repeats2, false);
// called once after 10 seconds
Cron.create("*/10 * * * * *", OnceOnly, true);
// 2-second alarm function
void Repeats2() {
Serial.println("2 second timer");
}
//disabling 2-second alarm within the 10-second alarm
void OnceOnly() {
Serial.println("This timer only triggers once, stop the 2 second timer");
// use Cron.free(id) to disable a timer and recycle its memory.
Cron.free(id);
// optional, but safest to "forget" the ID after memory recycled
id = dtINVALID_ALARM_ID;
// you can also use Cron.disable() to turn the timer off, but keep
// it in memory, to turn back on later with Alarm.enable().
}
The most important part of creating the CronAlarm is the cron string. Its syntax is −
"seconds minutes hours days_of_month month days_of_week"
A * for any of these means 'all values'. Thus,
"0 30 8 * * *" → Indicates trigger at 8:30:00 every day.
"0 30 8 * * *" → Indicates trigger at 8:30:00 every day.
"30 30 8 * * 6" → Indicates 8:30 trigger at 8:30:30 every Saturday (day_of_week = 6)
"30 30 8 * * 6" → Indicates 8:30 trigger at 8:30:30 every Saturday (day_of_week = 6)
A / in the expression indicates interval.
A / in the expression indicates interval.
"*/15 * * * * *" → Indicates every 15 seconds.
"*/15 * * * * *" → Indicates every 15 seconds.
If you run this example on your Arduino, the Serial Monitor output will be −
As you can see, the alarms get triggered as expected.
|
[
{
"code": null,
"e": 1312,
"s": 1062,
"text": "The CronAlarms library in Arduino helps you set cron jobs in Arduino. If you aren't aware of cron jobs, they are scheduled tasks to be carried out at a fixed time interval. An example can be sending a health packet to a server every day at midnight."
},
{
"code": null,
"e": 1437,
"s": 1312,
"text": "In order to install this library, search for CronAlarms in the Library Manager and install the library by Martin Laclaustra."
},
{
"code": null,
"e": 1491,
"s": 1437,
"text": "Once installed, go to - File → Examples → CronAlarms."
},
{
"code": null,
"e": 1596,
"s": 1491,
"text": "Open CronAlarms_example. If you go through the example, you will see that they are doing the following −"
},
{
"code": null,
"e": 1678,
"s": 1596,
"text": "Set the time to Saturday 8:29:00am Jan 1 2011, using the tm struct (time library)"
},
{
"code": null,
"e": 1760,
"s": 1678,
"text": "Set the time to Saturday 8:29:00am Jan 1 2011, using the tm struct (time library)"
},
{
"code": null,
"e": 1874,
"s": 1760,
"text": "Sets 6 Cron alarms, daily, weekly, at interval of few seconds, and even a one-time triggered non-repeating alarm."
},
{
"code": null,
"e": 1988,
"s": 1874,
"text": "Sets 6 Cron alarms, daily, weekly, at interval of few seconds, and even a one-time triggered non-repeating alarm."
},
{
"code": null,
"e": 2069,
"s": 1988,
"text": "The one-time triggered non-repeating alarm, in fact, disables the 2-second cron."
},
{
"code": null,
"e": 2150,
"s": 2069,
"text": "The one-time triggered non-repeating alarm, in fact, disables the 2-second cron."
},
{
"code": null,
"e": 2209,
"s": 2150,
"text": "Within the loop, the current time is printed every second."
},
{
"code": null,
"e": 2268,
"s": 2209,
"text": "Within the loop, the current time is printed every second."
},
{
"code": null,
"e": 2298,
"s": 2268,
"text": "The cron creation syntax is -"
},
{
"code": null,
"e": 2380,
"s": 2298,
"text": "CronID_t create(const char * cronstring, OnTick_t onTickHandler, bool isOneShot);"
},
{
"code": null,
"e": 2386,
"s": 2380,
"text": "Where"
},
{
"code": null,
"e": 2425,
"s": 2386,
"text": "cronstring provides the cron interval,"
},
{
"code": null,
"e": 2464,
"s": 2425,
"text": "cronstring provides the cron interval,"
},
{
"code": null,
"e": 2543,
"s": 2464,
"text": "onTickHandler is the function that will be called when the alarm is triggered,"
},
{
"code": null,
"e": 2622,
"s": 2543,
"text": "onTickHandler is the function that will be called when the alarm is triggered,"
},
{
"code": null,
"e": 2696,
"s": 2622,
"text": "isOneShot determines if the alarm is repeating or is a one-time interval."
},
{
"code": null,
"e": 2770,
"s": 2696,
"text": "isOneShot determines if the alarm is repeating or is a one-time interval."
},
{
"code": null,
"e": 2952,
"s": 2770,
"text": "This function returns a cron ID, which can be used to reference the alarm elsewhere in the code, as is done in the 10-second alarm, to disable the 2-second alarm, using Cron.free()."
},
{
"code": null,
"e": 3737,
"s": 2952,
"text": "//creating the 2-second repeating alarm and 10-second single-shot alarm\n\n// timer for every 2 seconds\nid = Cron.create(\"*/2 * * * * *\", Repeats2, false);\n\n// called once after 10 seconds\nCron.create(\"*/10 * * * * *\", OnceOnly, true);\n\n// 2-second alarm function\nvoid Repeats2() {\n Serial.println(\"2 second timer\");\n}\n\n//disabling 2-second alarm within the 10-second alarm\nvoid OnceOnly() {\n Serial.println(\"This timer only triggers once, stop the 2 second timer\");\n // use Cron.free(id) to disable a timer and recycle its memory.\n Cron.free(id);\n // optional, but safest to \"forget\" the ID after memory recycled\n id = dtINVALID_ALARM_ID;\n // you can also use Cron.disable() to turn the timer off, but keep\n // it in memory, to turn back on later with Alarm.enable().\n}"
},
{
"code": null,
"e": 3823,
"s": 3737,
"text": "The most important part of creating the CronAlarm is the cron string. Its syntax is −"
},
{
"code": null,
"e": 3880,
"s": 3823,
"text": "\"seconds minutes hours days_of_month month days_of_week\""
},
{
"code": null,
"e": 3927,
"s": 3880,
"text": "A * for any of these means 'all values'. Thus,"
},
{
"code": null,
"e": 3984,
"s": 3927,
"text": "\"0 30 8 * * *\" → Indicates trigger at 8:30:00 every day."
},
{
"code": null,
"e": 4041,
"s": 3984,
"text": "\"0 30 8 * * *\" → Indicates trigger at 8:30:00 every day."
},
{
"code": null,
"e": 4126,
"s": 4041,
"text": "\"30 30 8 * * 6\" → Indicates 8:30 trigger at 8:30:30 every Saturday (day_of_week = 6)"
},
{
"code": null,
"e": 4211,
"s": 4126,
"text": "\"30 30 8 * * 6\" → Indicates 8:30 trigger at 8:30:30 every Saturday (day_of_week = 6)"
},
{
"code": null,
"e": 4253,
"s": 4211,
"text": "A / in the expression indicates interval."
},
{
"code": null,
"e": 4295,
"s": 4253,
"text": "A / in the expression indicates interval."
},
{
"code": null,
"e": 4342,
"s": 4295,
"text": "\"*/15 * * * * *\" → Indicates every 15 seconds."
},
{
"code": null,
"e": 4389,
"s": 4342,
"text": "\"*/15 * * * * *\" → Indicates every 15 seconds."
},
{
"code": null,
"e": 4466,
"s": 4389,
"text": "If you run this example on your Arduino, the Serial Monitor output will be −"
},
{
"code": null,
"e": 4520,
"s": 4466,
"text": "As you can see, the alarms get triggered as expected."
}
] |
An Easy Tool to Correctly Transform Non-Linear Data For Linear Regression | by Kevin Babitz | Towards Data Science
|
Two important assumptions for linear regression are that the residuals are independent from each other and that there is constant variance in these errors (also known as homoscedasticity). This basically means that when we draw our regression line, we want a relatively equal number of errors on the top and bottom of our line across the entire line.
There are many cases where variables we would like to build a model for are not linearly correlated. This leads to failures for the above assumptions when fitting linear regression models to them. We may apply transformation functions to these variables in order to make the relationship linear. The following figure is useful in helping us decide what transformation to apply to non-linear data that we are working with.
The goal of this article is to demonstrate how to use this diagram to make transformations to your data. Before we get into examples, the way you can read this diagram is:
If you see data that looks like the curve in the top left, you can try to decrease the power of x and/or increase the power of y.If you see data that looks like the curve in the top right, you can try to increase the power of x and/or increase the power of y.If you see data that looks like the curve in the bottom right, you can try to increase the power of x and/or decrease the power of y.If you see data that looks like the curve in the bottom left, you can try to decrease the power of x and/or decrease the power of y.
If you see data that looks like the curve in the top left, you can try to decrease the power of x and/or increase the power of y.
If you see data that looks like the curve in the top right, you can try to increase the power of x and/or increase the power of y.
If you see data that looks like the curve in the bottom right, you can try to increase the power of x and/or decrease the power of y.
If you see data that looks like the curve in the bottom left, you can try to decrease the power of x and/or decrease the power of y.
Interestingly, there are not a lot of resources on this rule on Google (only a few thousand search results). This is a simple and powerful framework for quickly determining a transformation to use which allows you to potentially fit a linear model on non-linear data.
For this article, we will be using data generated from the following python function:
def random_data(p=1, size=200, noise_sd = .1, q=1): x = list(np.linspace(0.01, 1, size)) y = [(3 + 5 * x_val ** p + (random.normalvariate(0,noise_sd))) ** (1/q) for x_val in x] return x, y
The two important variables to understand above are p and q. The variable p represents the power being applied to the x values and q represents the inverse of the power being applied to y.
We are generating size values for x between 0.01 and 1 with equal intervals between each value. We are adding 3 and scaling the y values by 5 in order to avoid negative numbers which can cause issues with the rule we are discussing in this article. Finally, we are adding a bit of noise to the data using random.normalvariate(mean, sd) in order to make the data not perfectly fit the transformations we would like to demonstrate.
Let’s get started with an example of data that would be classified under the bottom right corner of the figure above.
We see that the data does not have a great linear relationship when we attempt to fit a least-squares linear regression line to it.
The diagram tells us to try decreasing the power of y or increasing the power of x. Below we see that increasing the power of x gives us a significantly better linear relationship and fit.
It is important to remember to consider a different transformation can have the same shape. Namely, the data could be generated with an increased power of y and require transforming the y variable for a better linear fit.
In this case, it would be appropriate to decrease the power of y for a better linear fit.
In the above examples, we were able to see how to apply the Tukey and Mosteller Bulging Rule to randomly generated data (specifically conforming to the bottom right corner of the diagram).
It is important to note that we already knew what the correct transformation was because we selected the parameters for the data during the data generation process. In practice, you will have to try the different transformations in the specific quadrant of the diagram to find the best transformation. The diagram is meant to be a helpful guide in quickly determining which ones to try.
Another thing to note is that this simple rule has some limitations. Specifically, it gives a good starting point for the direction to go in when transforming the data, but not the best possible transformation. Consider the Box-Cox transformation for a more complex and accurate framework (although the Tukey and Mosteller rule does a relatively good job as an approximation and this type of precision does not necessarily yield meaningful improvements to your models). Some code in R comparing the two rules can be found here.
Another thing to note is that a lot of these transformations require positive variable values to work. Thus, the rule may not be able to be applied to data with negative values or may require additional work to ensure all values are positive.
Thank you for taking your time to read this article and I hope it helps you in building your next model.
|
[
{
"code": null,
"e": 522,
"s": 171,
"text": "Two important assumptions for linear regression are that the residuals are independent from each other and that there is constant variance in these errors (also known as homoscedasticity). This basically means that when we draw our regression line, we want a relatively equal number of errors on the top and bottom of our line across the entire line."
},
{
"code": null,
"e": 944,
"s": 522,
"text": "There are many cases where variables we would like to build a model for are not linearly correlated. This leads to failures for the above assumptions when fitting linear regression models to them. We may apply transformation functions to these variables in order to make the relationship linear. The following figure is useful in helping us decide what transformation to apply to non-linear data that we are working with."
},
{
"code": null,
"e": 1116,
"s": 944,
"text": "The goal of this article is to demonstrate how to use this diagram to make transformations to your data. Before we get into examples, the way you can read this diagram is:"
},
{
"code": null,
"e": 1641,
"s": 1116,
"text": "If you see data that looks like the curve in the top left, you can try to decrease the power of x and/or increase the power of y.If you see data that looks like the curve in the top right, you can try to increase the power of x and/or increase the power of y.If you see data that looks like the curve in the bottom right, you can try to increase the power of x and/or decrease the power of y.If you see data that looks like the curve in the bottom left, you can try to decrease the power of x and/or decrease the power of y."
},
{
"code": null,
"e": 1771,
"s": 1641,
"text": "If you see data that looks like the curve in the top left, you can try to decrease the power of x and/or increase the power of y."
},
{
"code": null,
"e": 1902,
"s": 1771,
"text": "If you see data that looks like the curve in the top right, you can try to increase the power of x and/or increase the power of y."
},
{
"code": null,
"e": 2036,
"s": 1902,
"text": "If you see data that looks like the curve in the bottom right, you can try to increase the power of x and/or decrease the power of y."
},
{
"code": null,
"e": 2169,
"s": 2036,
"text": "If you see data that looks like the curve in the bottom left, you can try to decrease the power of x and/or decrease the power of y."
},
{
"code": null,
"e": 2437,
"s": 2169,
"text": "Interestingly, there are not a lot of resources on this rule on Google (only a few thousand search results). This is a simple and powerful framework for quickly determining a transformation to use which allows you to potentially fit a linear model on non-linear data."
},
{
"code": null,
"e": 2523,
"s": 2437,
"text": "For this article, we will be using data generated from the following python function:"
},
{
"code": null,
"e": 2724,
"s": 2523,
"text": "def random_data(p=1, size=200, noise_sd = .1, q=1): x = list(np.linspace(0.01, 1, size)) y = [(3 + 5 * x_val ** p + (random.normalvariate(0,noise_sd))) ** (1/q) for x_val in x] return x, y"
},
{
"code": null,
"e": 2913,
"s": 2724,
"text": "The two important variables to understand above are p and q. The variable p represents the power being applied to the x values and q represents the inverse of the power being applied to y."
},
{
"code": null,
"e": 3343,
"s": 2913,
"text": "We are generating size values for x between 0.01 and 1 with equal intervals between each value. We are adding 3 and scaling the y values by 5 in order to avoid negative numbers which can cause issues with the rule we are discussing in this article. Finally, we are adding a bit of noise to the data using random.normalvariate(mean, sd) in order to make the data not perfectly fit the transformations we would like to demonstrate."
},
{
"code": null,
"e": 3461,
"s": 3343,
"text": "Let’s get started with an example of data that would be classified under the bottom right corner of the figure above."
},
{
"code": null,
"e": 3593,
"s": 3461,
"text": "We see that the data does not have a great linear relationship when we attempt to fit a least-squares linear regression line to it."
},
{
"code": null,
"e": 3782,
"s": 3593,
"text": "The diagram tells us to try decreasing the power of y or increasing the power of x. Below we see that increasing the power of x gives us a significantly better linear relationship and fit."
},
{
"code": null,
"e": 4004,
"s": 3782,
"text": "It is important to remember to consider a different transformation can have the same shape. Namely, the data could be generated with an increased power of y and require transforming the y variable for a better linear fit."
},
{
"code": null,
"e": 4094,
"s": 4004,
"text": "In this case, it would be appropriate to decrease the power of y for a better linear fit."
},
{
"code": null,
"e": 4283,
"s": 4094,
"text": "In the above examples, we were able to see how to apply the Tukey and Mosteller Bulging Rule to randomly generated data (specifically conforming to the bottom right corner of the diagram)."
},
{
"code": null,
"e": 4670,
"s": 4283,
"text": "It is important to note that we already knew what the correct transformation was because we selected the parameters for the data during the data generation process. In practice, you will have to try the different transformations in the specific quadrant of the diagram to find the best transformation. The diagram is meant to be a helpful guide in quickly determining which ones to try."
},
{
"code": null,
"e": 5198,
"s": 4670,
"text": "Another thing to note is that this simple rule has some limitations. Specifically, it gives a good starting point for the direction to go in when transforming the data, but not the best possible transformation. Consider the Box-Cox transformation for a more complex and accurate framework (although the Tukey and Mosteller rule does a relatively good job as an approximation and this type of precision does not necessarily yield meaningful improvements to your models). Some code in R comparing the two rules can be found here."
},
{
"code": null,
"e": 5441,
"s": 5198,
"text": "Another thing to note is that a lot of these transformations require positive variable values to work. Thus, the rule may not be able to be applied to data with negative values or may require additional work to ensure all values are positive."
}
] |
Python | Pandas Timestamp.fromtimestamp - GeeksforGeeks
|
14 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Timestamp.fromtimestamp() function return a Timestamp object when passed an integer which represents the timestamp value.
Syntax :Timestamp.fromtimestamp()
Parameters : integer
Return : Timestamp
Example #1: Use Timestamp.fromtimestamp() function to return a Timestamp object from the passed value.
# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.fromtimestamp() function to return a Timestamp object from the passed value.
# convert to a Timestamp objectts.fromtimestamp(992345678)
Output :
As we can see in the output, the Timestamp.fromtimestamp() function has returned a new Timestamp object constructed from the passed value.
Example #2: Use Timestamp.fromtimestamp() function to return a Timestamp object from the passed value.
# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.fromtimestamp() function to return a Timestamp object from the passed value.
# convert to a Timestamp objectts.fromtimestamp(634816)
Output :
As we can see in the output, the Timestamp.fromtimestamp() function has returned a new Timestamp object constructed from the passed value.
Python Pandas-Timestamp
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n14 Jan, 2019"
},
{
"code": null,
"e": 25751,
"s": 25537,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 25880,
"s": 25751,
"text": "Pandas Timestamp.fromtimestamp() function return a Timestamp object when passed an integer which represents the timestamp value."
},
{
"code": null,
"e": 25914,
"s": 25880,
"text": "Syntax :Timestamp.fromtimestamp()"
},
{
"code": null,
"e": 25935,
"s": 25914,
"text": "Parameters : integer"
},
{
"code": null,
"e": 25954,
"s": 25935,
"text": "Return : Timestamp"
},
{
"code": null,
"e": 26057,
"s": 25954,
"text": "Example #1: Use Timestamp.fromtimestamp() function to return a Timestamp object from the passed value."
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts)",
"e": 26284,
"s": 26057,
"text": null
},
{
"code": null,
"e": 26293,
"s": 26284,
"text": "Output :"
},
{
"code": null,
"e": 26400,
"s": 26293,
"text": "Now we will use the Timestamp.fromtimestamp() function to return a Timestamp object from the passed value."
},
{
"code": "# convert to a Timestamp objectts.fromtimestamp(992345678)",
"e": 26459,
"s": 26400,
"text": null
},
{
"code": null,
"e": 26468,
"s": 26459,
"text": "Output :"
},
{
"code": null,
"e": 26607,
"s": 26468,
"text": "As we can see in the output, the Timestamp.fromtimestamp() function has returned a new Timestamp object constructed from the passed value."
},
{
"code": null,
"e": 26710,
"s": 26607,
"text": "Example #2: Use Timestamp.fromtimestamp() function to return a Timestamp object from the passed value."
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts)",
"e": 26937,
"s": 26710,
"text": null
},
{
"code": null,
"e": 26946,
"s": 26937,
"text": "Output :"
},
{
"code": null,
"e": 27053,
"s": 26946,
"text": "Now we will use the Timestamp.fromtimestamp() function to return a Timestamp object from the passed value."
},
{
"code": "# convert to a Timestamp objectts.fromtimestamp(634816)",
"e": 27109,
"s": 27053,
"text": null
},
{
"code": null,
"e": 27118,
"s": 27109,
"text": "Output :"
},
{
"code": null,
"e": 27257,
"s": 27118,
"text": "As we can see in the output, the Timestamp.fromtimestamp() function has returned a new Timestamp object constructed from the passed value."
},
{
"code": null,
"e": 27281,
"s": 27257,
"text": "Python Pandas-Timestamp"
},
{
"code": null,
"e": 27295,
"s": 27281,
"text": "Python-pandas"
},
{
"code": null,
"e": 27302,
"s": 27295,
"text": "Python"
},
{
"code": null,
"e": 27400,
"s": 27302,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27432,
"s": 27400,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27474,
"s": 27432,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27516,
"s": 27474,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27543,
"s": 27516,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27599,
"s": 27543,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27621,
"s": 27599,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27660,
"s": 27621,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27691,
"s": 27660,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27720,
"s": 27691,
"text": "Create a directory in Python"
}
] |
jQuery | serializeArray() with Examples - GeeksforGeeks
|
13 Feb, 2019
The serializeArray() is an inbuilt method in jQuery which is used to create a JavaScript array of objects that is ready to be encoded as a JSON string. It operates on a jQuery collection of forms and/or form controls. The controls can be of several types. JSON string is a text and can convert any JavaScript object into JSON, and send JSON to the server.Syntax:
$(selector).serializeArray()
Parameter: It does not accept any parameter.
Return Value: It return a string of objects.
jQuery code to show the working of serializeArray() method:
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $("button").click(function() { var x = $("form").serializeArray(); $.each(x, function(i, field) { $("#d").append(field.name + ":" + field.value + ":::"); }); }); }); </script> <style> #d1 { width: 300px; height: 100px; padding: 20px; border: 2px solid green; margin-bottom: 10px; } </style></head> <body> <div id="d1"> <form action=""> Site name: <input type="text" name="SiteName" value="GeeksforGeeks"> <br> <br> Contributor name: <input type="text" name="ContributorName" value="KundanJha"> <br> </form> <!-- click on this button --> <button>Click here!</button> </div> <div id="d"></div> </body> </html>
Output:Before clicking on the “Click here!” button-
After clicking on the “Click here!” button-
jQuery-AJAX
JavaScript
JQuery
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 append HTML code to a div using JavaScript ?
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to fetch data from JSON file and display in HTML table using jQuery ?
|
[
{
"code": null,
"e": 25394,
"s": 25366,
"text": "\n13 Feb, 2019"
},
{
"code": null,
"e": 25757,
"s": 25394,
"text": "The serializeArray() is an inbuilt method in jQuery which is used to create a JavaScript array of objects that is ready to be encoded as a JSON string. It operates on a jQuery collection of forms and/or form controls. The controls can be of several types. JSON string is a text and can convert any JavaScript object into JSON, and send JSON to the server.Syntax:"
},
{
"code": null,
"e": 25787,
"s": 25757,
"text": "$(selector).serializeArray()\n"
},
{
"code": null,
"e": 25832,
"s": 25787,
"text": "Parameter: It does not accept any parameter."
},
{
"code": null,
"e": 25877,
"s": 25832,
"text": "Return Value: It return a string of objects."
},
{
"code": null,
"e": 25937,
"s": 25877,
"text": "jQuery code to show the working of serializeArray() method:"
},
{
"code": "<html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $(\"button\").click(function() { var x = $(\"form\").serializeArray(); $.each(x, function(i, field) { $(\"#d\").append(field.name + \":\" + field.value + \":::\"); }); }); }); </script> <style> #d1 { width: 300px; height: 100px; padding: 20px; border: 2px solid green; margin-bottom: 10px; } </style></head> <body> <div id=\"d1\"> <form action=\"\"> Site name: <input type=\"text\" name=\"SiteName\" value=\"GeeksforGeeks\"> <br> <br> Contributor name: <input type=\"text\" name=\"ContributorName\" value=\"KundanJha\"> <br> </form> <!-- click on this button --> <button>Click here!</button> </div> <div id=\"d\"></div> </body> </html>",
"e": 27050,
"s": 25937,
"text": null
},
{
"code": null,
"e": 27102,
"s": 27050,
"text": "Output:Before clicking on the “Click here!” button-"
},
{
"code": null,
"e": 27146,
"s": 27102,
"text": "After clicking on the “Click here!” button-"
},
{
"code": null,
"e": 27158,
"s": 27146,
"text": "jQuery-AJAX"
},
{
"code": null,
"e": 27169,
"s": 27158,
"text": "JavaScript"
},
{
"code": null,
"e": 27176,
"s": 27169,
"text": "JQuery"
},
{
"code": null,
"e": 27274,
"s": 27176,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27314,
"s": 27274,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27359,
"s": 27314,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27420,
"s": 27359,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27492,
"s": 27420,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27544,
"s": 27492,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 27590,
"s": 27544,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 27619,
"s": 27590,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 27682,
"s": 27619,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 27759,
"s": 27682,
"text": "How to change the background color after clicking the button in JavaScript ?"
}
] |
TCS CodeVita 9 ( Zone 1) 2020 | Constellation - GeeksforGeeks
|
06 Apr, 2022
Three characters {#, *, . } represents a constellation of stars and galaxies in space. Each galaxy is demarcated by # characters. There can be one or many stars in a given galaxy. Stars can only be in the shape of vowels {A, E, I, O, U}. A collection of * in the shape of the vowels is a star. A star is contained in a 3×3 block. Stars cannot be overlapping. The dot (.) character denotes empty space.
Given a matrix mat[][] of dimensions 3×N consisting of {#, *, .} character, the task is to find the galaxy and stars within them.
Examples:
Input: N = 18, mat[][] = {{* . * # * * * # * * * # * * * . * .}, {* . * # * . * # . * . # * * * * * *}, {* * * # * * * # * * * # * * * * . *}}Output: U#O#I#EAExplanation:It can be seen that the stars make the image of the alphabets U, O, I, E and A respectively.
Input: N = 12, mat[][] = {{* . * # . * * * # . * .}, {* . * # . . * . # * * *}, {* * * # . * * * # * . *}}Output: U#I#AExplanation:It can be seen that the stars make the image of the alphabet U, I and A.
Approach: The idea is to traverse the matrix column-wise using the variable i from the range [0, N – 1] and check if the given arrangement of {#, *, . } forms a galaxy, an empty space, or a vowel. There arise the following cases:
When all ‘#’ is encountered in the given column: In this case, print ‘#’ and continue traversing the matrix.
When all ‘.’ is encountered in the given column: In this case, skip the current column and continue traversing the matrix.
For all other cases check if the given arrangement of {#, *, .} forms a vowel, then print the vowel and update the column index i to (i + 3).
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 print the vowels(stars)// in order of their occurrence within// the given galaxyvoid printGalaxy( vector<vector<char> > mat, int n){ // Iterate the matrix column-wise for (int i = 0; i < n; i++) { // If all '#' is encountered // in the given column, print '#' if (mat[0][i] == '#' && mat[1][i] == '#' && mat[2][i] == '#') { cout << '#'; } // If all '.' is encountered in // the given column, skip the // current column else if (mat[0][i] == '.' && mat[1][i] == '.' && mat[2][i] == '.') { } // If above cases fail else { char a, b, c, a1, b1; char c1, a2, b2, c2; int x1 = i; a = mat[0][x1]; b = mat[0][x1 + 1]; c = mat[0][x1 + 2]; a1 = mat[1][x1]; b1 = mat[1][x1 + 1]; c1 = mat[1][x1 + 2]; a2 = mat[2][x1]; b2 = mat[2][x1 + 1]; c2 = mat[2][x1 + 2]; // Check if the arrangement // of '.' and '*' forms // character 'A' if (a == '.' && b == '*' && c == '.' && a1 == '*' && b1 == '*' && c1 == '*' && a2 == '*' && b2 == '.' && c2 == '*') { // If true, print A cout << "A"; // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'E' if (a == '*' && b == '*' && c == '*' && a1 == '*' && b1 == '*' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print E cout << "E"; // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'I' if (a == '*' && b == '*' && c == '*' && a1 == '.' && b1 == '*' && c1 == '.' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print I cout << "I"; // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'O' if (a == '*' && b == '*' && c == '*' && a1 == '*' && b1 == '.' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print O cout << "O"; // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'U' if (a == '*' && b == '.' && c == '*' && a1 == '*' && b1 == '.' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If True, print U cout << "U"; // Increment column number i = i + 2; } } }} // Driver Codeint main(){ // Given n, number of columns int N = 18; // Given matrix vector<vector<char> > mat = { { '*', '.', '*', '#', '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '.', '*', '.' }, { '*', '.', '*', '#', '*', '.', '*', '#', '.', '*', '.', '#', '*', '*', '*', '*', '*', '*' }, { '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '*', '.', '*' } }; // Function Call printGalaxy(mat, N); return 0;}
// Java program for the above approachimport java.io.*; class GFG{ // Function to print the vowels(stars) // in order of their occurrence within // the given galaxy static void printGalaxy(char mat[][], int n) { // Iterate the matrix column-wise for (int i = 0; i < n; i++) { // If all '#' is encountered // in the given column, print '#' if (mat[0][i] == '#' && mat[1][i] == '#' && mat[2][i] == '#') { System.out.print('#'); } // If all '.' is encountered in // the given column, skip the // current column else if (mat[0][i] == '.' && mat[1][i] == '.' && mat[2][i] == '.') { } // If above cases fail else { char a, b, c, a1, b1; char c1, a2, b2, c2; int x1 = i; a = mat[0][x1]; b = mat[0][x1 + 1]; c = mat[0][x1 + 2]; a1 = mat[1][x1]; b1 = mat[1][x1 + 1]; c1 = mat[1][x1 + 2]; a2 = mat[2][x1]; b2 = mat[2][x1 + 1]; c2 = mat[2][x1 + 2]; // Check if the arrangement // of '.' and '*' forms // character 'A' if (a == '.' && b == '*' && c == '.' && a1 == '*' && b1 == '*' && c1 == '*' && a2 == '*' && b2 == '.' && c2 == '*') { // If true, print A System.out.print("A"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'E' if (a == '*' && b == '*' && c == '*' && a1 == '*' && b1 == '*' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print E System.out.print("E"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'I' if (a == '*' && b == '*' && c == '*' && a1 == '.' && b1 == '*' && c1 == '.' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print I System.out.print("I"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'O' if (a == '*' && b == '*' && c == '*' && a1 == '*' && b1 == '.' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print O System.out.print("O"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'U' if (a == '*' && b == '.' && c == '*' && a1 == '*' && b1 == '.' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If True, print U System.out.print("U"); // Increment column number i = i + 2; } } } } // Driver Code public static void main(String[] args) { // Given n, number of columns int N = 18; // Given matrix char mat[][] = { { '*', '.', '*', '#', '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '.', '*', '.' }, { '*', '.', '*', '#', '*', '.', '*', '#', '.', '*', '.', '#', '*', '*', '*', '*', '*', '*' }, { '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '*', '.', '*' } }; // Function Call printGalaxy(mat, N); }} // This code is contributed by Potta Lokesh
# Python program for the above approach # Function to print vowels(stars)# in order of their occurrence within# the given galaxydef printGalaxy(mat, n): # Iterate the matrix column-wise for i in range(n - 2): # If all '#' is encountered # in the given column, pr'#' if (mat[0][i] == '#' and mat[1][i] == '#' and mat[2][i] == '#'): print('#',end=""); # If all '.' is encountered in # the given column, skip the # current column elif(mat[0][i] == '.' and mat[1][i] == '.' and mat[2][i] == '.'): p = 0; # If above cases fail else: x1 = i; a = mat[0][x1]; b = mat[0][x1 + 1]; c = mat[0][x1 + 2]; a1 = mat[1][x1]; b1 = mat[1][x1 + 1]; c1 = mat[1][x1 + 2]; a2 = mat[2][x1]; b2 = mat[2][x1 + 1]; c2 = mat[2][x1 + 2]; # Check if the arrangement # of '.' and '*' forms # character 'A' if (a == '.' and b == '*' and c == '.' and a1 == '*' and b1 == '*' and c1 == '*' and a2 == '*' and b2 == '.' and c2 == '*'): # If True, prA print("A",end=""); # Increment column number i = i + 2; # Check if the arrangement # of '.' and '*' forms # character 'E' if (a == '*' and b == '*' and c == '*' and a1 == '*' and b1 == '*' and c1 == '*' and a2 == '*' and b2 == '*' and c2 == '*'): # If True, prE print("E",end=""); # Increment column number i = i + 2; # Check if the arrangement # of '.' and '*' forms # character 'I' if (a == '*' and b == '*' and c == '*' and a1 == '.' and b1 == '*' and c1 == '.' and a2 == '*' and b2 == '*' and c2 == '*'): # If True, prI print("I",end=""); # Increment column number i = i + 2; # Check if the arrangement # of '.' and '*' forms # character 'O' if (a == '*' and b == '*' and c == '*' and a1 == '*' and b1 == '.' and c1 == '*' and a2 == '*' and b2 == '*' and c2 == '*'): # If True, prO print("O",end=""); # Increment column number i = i + 2; # Check if the arrangement # of '.' and '*' forms # character 'U' if (a == '*' and b == '.' and c == '*' and a1 == '*' and b1 == '.' and c1 == '*' and a2 == '*' and b2 == '*' and c2 == '*'): # If True, prU print("U",end=""); # Increment column number i = i + 2; # Driver Codeif __name__ == '__main__': # Given n, number of columns N = 18; # Given matrix mat = [[ '*', '.', '*', '#', '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '.', '*', '.'] , [ '*', '.', '*', '#', '*', '.', '*', '#', '.', '*', '.', '#', '*', '*', '*', '*', '*', '*' ], [ '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '*', '.', '*' ] ]; # Function Call printGalaxy(mat, N); # This code is contributed by umadevi9616
// C# program for the above approachusing System; public class GFG{ // Function to print the vowels(stars) // in order of their occurrence within // the given galaxy static void printGalaxy(char [,]mat, int n) { // Iterate the matrix column-wise for (int i = 0; i < n; i++) { // If all '#' is encountered // in the given column, print '#' if (mat[0,i] == '#' && mat[1,i] == '#' && mat[2,i] == '#') { Console.Write('#'); } // If all '.' is encountered in // the given column, skip the // current column else if (mat[0,i] == '.' && mat[1,i] == '.' && mat[2,i] == '.') { } // If above cases fail else { char a, b, c, a1, b1; char c1, a2, b2, c2; int x1 = i; a = mat[0,x1]; b = mat[0,x1 + 1]; c = mat[0,x1 + 2]; a1 = mat[1,x1]; b1 = mat[1,x1 + 1]; c1 = mat[1,x1 + 2]; a2 = mat[2,x1]; b2 = mat[2,x1 + 1]; c2 = mat[2,x1 + 2]; // Check if the arrangement // of '.' and '*' forms // character 'A' if (a == '.' && b == '*' && c == '.' && a1 == '*' && b1 == '*' && c1 == '*' && a2 == '*' && b2 == '.' && c2 == '*') { // If true, print A Console.Write("A"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'E' if (a == '*' && b == '*' && c == '*' && a1 == '*' && b1 == '*' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print E Console.Write("E"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'I' if (a == '*' && b == '*' && c == '*' && a1 == '.' && b1 == '*' && c1 == '.' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print I Console.Write("I"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'O' if (a == '*' && b == '*' && c == '*' && a1 == '*' && b1 == '.' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print O Console.Write("O"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'U' if (a == '*' && b == '.' && c == '*' && a1 == '*' && b1 == '.' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If True, print U Console.Write("U"); // Increment column number i = i + 2; } } } } // Driver Code public static void Main(String[] args) { // Given n, number of columns int N = 18; // Given matrix char [,]mat = { { '*', '.', '*', '#', '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '.', '*', '.' }, { '*', '.', '*', '#', '*', '.', '*', '#', '.', '*', '.', '#', '*', '*', '*', '*', '*', '*' }, { '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '*', '.', '*' } }; // Function Call printGalaxy(mat, N); }} // This code is contributed by Amit Katiyar
<script> // Javascript program for the above approach // Function to print the vowels(stars)// in order of their occurrence within// the given galaxyfunction printGalaxy(mat, n){ // Iterate the matrix column-wise for (let i = 0; i < n; i++) { // If all '#' is encountered // in the given column, print '#' if (mat[0][i] == '#' && mat[1][i] == '#' && mat[2][i] == '#') { document.write('#'); } // If all '.' is encountered in // the given column, skip the // current column else if (mat[0][i] == '.' && mat[1][i] == '.' && mat[2][i] == '.') { } // If above cases fail else { let a, b, c, a1, b1; let c1, a2, b2, c2; let x1 = i; a = mat[0][x1]; b = mat[0][x1 + 1]; c = mat[0][x1 + 2]; a1 = mat[1][x1]; b1 = mat[1][x1 + 1]; c1 = mat[1][x1 + 2]; a2 = mat[2][x1]; b2 = mat[2][x1 + 1]; c2 = mat[2][x1 + 2]; // Check if the arrangement // of '.' and '*' forms // character 'A' if (a == '.' && b == '*' && c == '.' && a1 == '*' && b1 == '*' && c1 == '*' && a2 == '*' && b2 == '.' && c2 == '*') { // If true, print A document.write("A"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'E' if (a == '*' && b == '*' && c == '*' && a1 == '*' && b1 == '*' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print E document.write("E"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'I' if (a == '*' && b == '*' && c == '*' && a1 == '.' && b1 == '*' && c1 == '.' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print I document.write("I"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'O' if (a == '*' && b == '*' && c == '*' && a1 == '*' && b1 == '.' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print O document.write("O"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'U' if (a == '*' && b == '.' && c == '*' && a1 == '*' && b1 == '.' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If True, print U document.write("U"); // Increment column number i = i + 2; } } }} // Driver Code // Given n, number of columns let N = 18; // Given matrix let mat = [ [ '*', '.', '*', '#', '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '.', '*', '.' ], [ '*', '.', '*', '#', '*', '.', '*', '#', '.', '*', '.', '#', '*', '*', '*', '*', '*', '*' ], [ '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '*', '.', '*' ] ]; // Function Call printGalaxy(mat, N); // This code is contributed by gfgking.</script>
U#O#I#EA
Time Complexity: O(N)Auxiliary Space: O(1)
lokeshpotta20
gfgking
amit143katiyar
umadevi9616
khushboogoyal499
interview-preparation
TCS
TCS-coding-questions
Matrix
TCS
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum size square sub-matrix with all 1s
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Count all possible paths from top left to bottom right of a mXn matrix
Maximum size rectangle binary sub-matrix with all 1s
Program to multiply two matrices
Min Cost Path | DP-6
Printing all solutions in N-Queen Problem
Rotate a matrix by 90 degree in clockwise direction without using any extra space
The Celebrity Problem
Python program to multiply two matrices
|
[
{
"code": null,
"e": 26435,
"s": 26407,
"text": "\n06 Apr, 2022"
},
{
"code": null,
"e": 26837,
"s": 26435,
"text": "Three characters {#, *, . } represents a constellation of stars and galaxies in space. Each galaxy is demarcated by # characters. There can be one or many stars in a given galaxy. Stars can only be in the shape of vowels {A, E, I, O, U}. A collection of * in the shape of the vowels is a star. A star is contained in a 3×3 block. Stars cannot be overlapping. The dot (.) character denotes empty space."
},
{
"code": null,
"e": 26967,
"s": 26837,
"text": "Given a matrix mat[][] of dimensions 3×N consisting of {#, *, .} character, the task is to find the galaxy and stars within them."
},
{
"code": null,
"e": 26977,
"s": 26967,
"text": "Examples:"
},
{
"code": null,
"e": 27240,
"s": 26977,
"text": "Input: N = 18, mat[][] = {{* . * # * * * # * * * # * * * . * .}, {* . * # * . * # . * . # * * * * * *}, {* * * # * * * # * * * # * * * * . *}}Output: U#O#I#EAExplanation:It can be seen that the stars make the image of the alphabets U, O, I, E and A respectively."
},
{
"code": null,
"e": 27444,
"s": 27240,
"text": "Input: N = 12, mat[][] = {{* . * # . * * * # . * .}, {* . * # . . * . # * * *}, {* * * # . * * * # * . *}}Output: U#I#AExplanation:It can be seen that the stars make the image of the alphabet U, I and A."
},
{
"code": null,
"e": 27674,
"s": 27444,
"text": "Approach: The idea is to traverse the matrix column-wise using the variable i from the range [0, N – 1] and check if the given arrangement of {#, *, . } forms a galaxy, an empty space, or a vowel. There arise the following cases:"
},
{
"code": null,
"e": 27783,
"s": 27674,
"text": "When all ‘#’ is encountered in the given column: In this case, print ‘#’ and continue traversing the matrix."
},
{
"code": null,
"e": 27906,
"s": 27783,
"text": "When all ‘.’ is encountered in the given column: In this case, skip the current column and continue traversing the matrix."
},
{
"code": null,
"e": 28048,
"s": 27906,
"text": "For all other cases check if the given arrangement of {#, *, .} forms a vowel, then print the vowel and update the column index i to (i + 3)."
},
{
"code": null,
"e": 28099,
"s": 28048,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28103,
"s": 28099,
"text": "C++"
},
{
"code": null,
"e": 28108,
"s": 28103,
"text": "Java"
},
{
"code": null,
"e": 28116,
"s": 28108,
"text": "Python3"
},
{
"code": null,
"e": 28119,
"s": 28116,
"text": "C#"
},
{
"code": null,
"e": 28130,
"s": 28119,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print the vowels(stars)// in order of their occurrence within// the given galaxyvoid printGalaxy( vector<vector<char> > mat, int n){ // Iterate the matrix column-wise for (int i = 0; i < n; i++) { // If all '#' is encountered // in the given column, print '#' if (mat[0][i] == '#' && mat[1][i] == '#' && mat[2][i] == '#') { cout << '#'; } // If all '.' is encountered in // the given column, skip the // current column else if (mat[0][i] == '.' && mat[1][i] == '.' && mat[2][i] == '.') { } // If above cases fail else { char a, b, c, a1, b1; char c1, a2, b2, c2; int x1 = i; a = mat[0][x1]; b = mat[0][x1 + 1]; c = mat[0][x1 + 2]; a1 = mat[1][x1]; b1 = mat[1][x1 + 1]; c1 = mat[1][x1 + 2]; a2 = mat[2][x1]; b2 = mat[2][x1 + 1]; c2 = mat[2][x1 + 2]; // Check if the arrangement // of '.' and '*' forms // character 'A' if (a == '.' && b == '*' && c == '.' && a1 == '*' && b1 == '*' && c1 == '*' && a2 == '*' && b2 == '.' && c2 == '*') { // If true, print A cout << \"A\"; // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'E' if (a == '*' && b == '*' && c == '*' && a1 == '*' && b1 == '*' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print E cout << \"E\"; // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'I' if (a == '*' && b == '*' && c == '*' && a1 == '.' && b1 == '*' && c1 == '.' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print I cout << \"I\"; // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'O' if (a == '*' && b == '*' && c == '*' && a1 == '*' && b1 == '.' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print O cout << \"O\"; // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'U' if (a == '*' && b == '.' && c == '*' && a1 == '*' && b1 == '.' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If True, print U cout << \"U\"; // Increment column number i = i + 2; } } }} // Driver Codeint main(){ // Given n, number of columns int N = 18; // Given matrix vector<vector<char> > mat = { { '*', '.', '*', '#', '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '.', '*', '.' }, { '*', '.', '*', '#', '*', '.', '*', '#', '.', '*', '.', '#', '*', '*', '*', '*', '*', '*' }, { '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '*', '.', '*' } }; // Function Call printGalaxy(mat, N); return 0;}",
"e": 32021,
"s": 28130,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*; class GFG{ // Function to print the vowels(stars) // in order of their occurrence within // the given galaxy static void printGalaxy(char mat[][], int n) { // Iterate the matrix column-wise for (int i = 0; i < n; i++) { // If all '#' is encountered // in the given column, print '#' if (mat[0][i] == '#' && mat[1][i] == '#' && mat[2][i] == '#') { System.out.print('#'); } // If all '.' is encountered in // the given column, skip the // current column else if (mat[0][i] == '.' && mat[1][i] == '.' && mat[2][i] == '.') { } // If above cases fail else { char a, b, c, a1, b1; char c1, a2, b2, c2; int x1 = i; a = mat[0][x1]; b = mat[0][x1 + 1]; c = mat[0][x1 + 2]; a1 = mat[1][x1]; b1 = mat[1][x1 + 1]; c1 = mat[1][x1 + 2]; a2 = mat[2][x1]; b2 = mat[2][x1 + 1]; c2 = mat[2][x1 + 2]; // Check if the arrangement // of '.' and '*' forms // character 'A' if (a == '.' && b == '*' && c == '.' && a1 == '*' && b1 == '*' && c1 == '*' && a2 == '*' && b2 == '.' && c2 == '*') { // If true, print A System.out.print(\"A\"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'E' if (a == '*' && b == '*' && c == '*' && a1 == '*' && b1 == '*' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print E System.out.print(\"E\"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'I' if (a == '*' && b == '*' && c == '*' && a1 == '.' && b1 == '*' && c1 == '.' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print I System.out.print(\"I\"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'O' if (a == '*' && b == '*' && c == '*' && a1 == '*' && b1 == '.' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print O System.out.print(\"O\"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'U' if (a == '*' && b == '.' && c == '*' && a1 == '*' && b1 == '.' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If True, print U System.out.print(\"U\"); // Increment column number i = i + 2; } } } } // Driver Code public static void main(String[] args) { // Given n, number of columns int N = 18; // Given matrix char mat[][] = { { '*', '.', '*', '#', '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '.', '*', '.' }, { '*', '.', '*', '#', '*', '.', '*', '#', '.', '*', '.', '#', '*', '*', '*', '*', '*', '*' }, { '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '*', '.', '*' } }; // Function Call printGalaxy(mat, N); }} // This code is contributed by Potta Lokesh",
"e": 36320,
"s": 32021,
"text": null
},
{
"code": "# Python program for the above approach # Function to print vowels(stars)# in order of their occurrence within# the given galaxydef printGalaxy(mat, n): # Iterate the matrix column-wise for i in range(n - 2): # If all '#' is encountered # in the given column, pr'#' if (mat[0][i] == '#' and mat[1][i] == '#' and mat[2][i] == '#'): print('#',end=\"\"); # If all '.' is encountered in # the given column, skip the # current column elif(mat[0][i] == '.' and mat[1][i] == '.' and mat[2][i] == '.'): p = 0; # If above cases fail else: x1 = i; a = mat[0][x1]; b = mat[0][x1 + 1]; c = mat[0][x1 + 2]; a1 = mat[1][x1]; b1 = mat[1][x1 + 1]; c1 = mat[1][x1 + 2]; a2 = mat[2][x1]; b2 = mat[2][x1 + 1]; c2 = mat[2][x1 + 2]; # Check if the arrangement # of '.' and '*' forms # character 'A' if (a == '.' and b == '*' and c == '.' and a1 == '*' and b1 == '*' and c1 == '*' and a2 == '*' and b2 == '.' and c2 == '*'): # If True, prA print(\"A\",end=\"\"); # Increment column number i = i + 2; # Check if the arrangement # of '.' and '*' forms # character 'E' if (a == '*' and b == '*' and c == '*' and a1 == '*' and b1 == '*' and c1 == '*' and a2 == '*' and b2 == '*' and c2 == '*'): # If True, prE print(\"E\",end=\"\"); # Increment column number i = i + 2; # Check if the arrangement # of '.' and '*' forms # character 'I' if (a == '*' and b == '*' and c == '*' and a1 == '.' and b1 == '*' and c1 == '.' and a2 == '*' and b2 == '*' and c2 == '*'): # If True, prI print(\"I\",end=\"\"); # Increment column number i = i + 2; # Check if the arrangement # of '.' and '*' forms # character 'O' if (a == '*' and b == '*' and c == '*' and a1 == '*' and b1 == '.' and c1 == '*' and a2 == '*' and b2 == '*' and c2 == '*'): # If True, prO print(\"O\",end=\"\"); # Increment column number i = i + 2; # Check if the arrangement # of '.' and '*' forms # character 'U' if (a == '*' and b == '.' and c == '*' and a1 == '*' and b1 == '.' and c1 == '*' and a2 == '*' and b2 == '*' and c2 == '*'): # If True, prU print(\"U\",end=\"\"); # Increment column number i = i + 2; # Driver Codeif __name__ == '__main__': # Given n, number of columns N = 18; # Given matrix mat = [[ '*', '.', '*', '#', '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '.', '*', '.'] , [ '*', '.', '*', '#', '*', '.', '*', '#', '.', '*', '.', '#', '*', '*', '*', '*', '*', '*' ], [ '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '*', '.', '*' ] ]; # Function Call printGalaxy(mat, N); # This code is contributed by umadevi9616",
"e": 39748,
"s": 36320,
"text": null
},
{
"code": "// C# program for the above approachusing System; public class GFG{ // Function to print the vowels(stars) // in order of their occurrence within // the given galaxy static void printGalaxy(char [,]mat, int n) { // Iterate the matrix column-wise for (int i = 0; i < n; i++) { // If all '#' is encountered // in the given column, print '#' if (mat[0,i] == '#' && mat[1,i] == '#' && mat[2,i] == '#') { Console.Write('#'); } // If all '.' is encountered in // the given column, skip the // current column else if (mat[0,i] == '.' && mat[1,i] == '.' && mat[2,i] == '.') { } // If above cases fail else { char a, b, c, a1, b1; char c1, a2, b2, c2; int x1 = i; a = mat[0,x1]; b = mat[0,x1 + 1]; c = mat[0,x1 + 2]; a1 = mat[1,x1]; b1 = mat[1,x1 + 1]; c1 = mat[1,x1 + 2]; a2 = mat[2,x1]; b2 = mat[2,x1 + 1]; c2 = mat[2,x1 + 2]; // Check if the arrangement // of '.' and '*' forms // character 'A' if (a == '.' && b == '*' && c == '.' && a1 == '*' && b1 == '*' && c1 == '*' && a2 == '*' && b2 == '.' && c2 == '*') { // If true, print A Console.Write(\"A\"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'E' if (a == '*' && b == '*' && c == '*' && a1 == '*' && b1 == '*' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print E Console.Write(\"E\"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'I' if (a == '*' && b == '*' && c == '*' && a1 == '.' && b1 == '*' && c1 == '.' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print I Console.Write(\"I\"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'O' if (a == '*' && b == '*' && c == '*' && a1 == '*' && b1 == '.' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print O Console.Write(\"O\"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'U' if (a == '*' && b == '.' && c == '*' && a1 == '*' && b1 == '.' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If True, print U Console.Write(\"U\"); // Increment column number i = i + 2; } } } } // Driver Code public static void Main(String[] args) { // Given n, number of columns int N = 18; // Given matrix char [,]mat = { { '*', '.', '*', '#', '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '.', '*', '.' }, { '*', '.', '*', '#', '*', '.', '*', '#', '.', '*', '.', '#', '*', '*', '*', '*', '*', '*' }, { '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '*', '.', '*' } }; // Function Call printGalaxy(mat, N); }} // This code is contributed by Amit Katiyar",
"e": 44020,
"s": 39748,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to print the vowels(stars)// in order of their occurrence within// the given galaxyfunction printGalaxy(mat, n){ // Iterate the matrix column-wise for (let i = 0; i < n; i++) { // If all '#' is encountered // in the given column, print '#' if (mat[0][i] == '#' && mat[1][i] == '#' && mat[2][i] == '#') { document.write('#'); } // If all '.' is encountered in // the given column, skip the // current column else if (mat[0][i] == '.' && mat[1][i] == '.' && mat[2][i] == '.') { } // If above cases fail else { let a, b, c, a1, b1; let c1, a2, b2, c2; let x1 = i; a = mat[0][x1]; b = mat[0][x1 + 1]; c = mat[0][x1 + 2]; a1 = mat[1][x1]; b1 = mat[1][x1 + 1]; c1 = mat[1][x1 + 2]; a2 = mat[2][x1]; b2 = mat[2][x1 + 1]; c2 = mat[2][x1 + 2]; // Check if the arrangement // of '.' and '*' forms // character 'A' if (a == '.' && b == '*' && c == '.' && a1 == '*' && b1 == '*' && c1 == '*' && a2 == '*' && b2 == '.' && c2 == '*') { // If true, print A document.write(\"A\"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'E' if (a == '*' && b == '*' && c == '*' && a1 == '*' && b1 == '*' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print E document.write(\"E\"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'I' if (a == '*' && b == '*' && c == '*' && a1 == '.' && b1 == '*' && c1 == '.' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print I document.write(\"I\"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'O' if (a == '*' && b == '*' && c == '*' && a1 == '*' && b1 == '.' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If true, print O document.write(\"O\"); // Increment column number i = i + 2; } // Check if the arrangement // of '.' and '*' forms // character 'U' if (a == '*' && b == '.' && c == '*' && a1 == '*' && b1 == '.' && c1 == '*' && a2 == '*' && b2 == '*' && c2 == '*') { // If True, print U document.write(\"U\"); // Increment column number i = i + 2; } } }} // Driver Code // Given n, number of columns let N = 18; // Given matrix let mat = [ [ '*', '.', '*', '#', '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '.', '*', '.' ], [ '*', '.', '*', '#', '*', '.', '*', '#', '.', '*', '.', '#', '*', '*', '*', '*', '*', '*' ], [ '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '#', '*', '*', '*', '*', '.', '*' ] ]; // Function Call printGalaxy(mat, N); // This code is contributed by gfgking.</script>",
"e": 47909,
"s": 44020,
"text": null
},
{
"code": null,
"e": 47918,
"s": 47909,
"text": "U#O#I#EA"
},
{
"code": null,
"e": 47963,
"s": 47920,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 47977,
"s": 47963,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 47985,
"s": 47977,
"text": "gfgking"
},
{
"code": null,
"e": 48000,
"s": 47985,
"text": "amit143katiyar"
},
{
"code": null,
"e": 48012,
"s": 48000,
"text": "umadevi9616"
},
{
"code": null,
"e": 48029,
"s": 48012,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 48051,
"s": 48029,
"text": "interview-preparation"
},
{
"code": null,
"e": 48055,
"s": 48051,
"text": "TCS"
},
{
"code": null,
"e": 48076,
"s": 48055,
"text": "TCS-coding-questions"
},
{
"code": null,
"e": 48083,
"s": 48076,
"text": "Matrix"
},
{
"code": null,
"e": 48087,
"s": 48083,
"text": "TCS"
},
{
"code": null,
"e": 48094,
"s": 48087,
"text": "Matrix"
},
{
"code": null,
"e": 48192,
"s": 48094,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 48235,
"s": 48192,
"text": "Maximum size square sub-matrix with all 1s"
},
{
"code": null,
"e": 48297,
"s": 48235,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
},
{
"code": null,
"e": 48368,
"s": 48297,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 48421,
"s": 48368,
"text": "Maximum size rectangle binary sub-matrix with all 1s"
},
{
"code": null,
"e": 48454,
"s": 48421,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 48475,
"s": 48454,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 48517,
"s": 48475,
"text": "Printing all solutions in N-Queen Problem"
},
{
"code": null,
"e": 48599,
"s": 48517,
"text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space"
},
{
"code": null,
"e": 48621,
"s": 48599,
"text": "The Celebrity Problem"
}
] |
Best way to make a d3.js visualization layout responsive - GeeksforGeeks
|
29 Jul, 2021
D3 stands for Data-Driven Documents. It is an open-source JavaScript library that is used to create interactive data visualizations in the browser using HTML, SVG, and CSS. The huge amount of data is being generated in today’s world, which is very difficult to store and analyze. Visual representations of data are the most effective means of conveying information stored and D3 provides the ease and flexibility to create these data visualizations.
A simple way to make any SVG or D3.js chart responsive. Here we will be using D3.js to make bar graph responsive.Approach for creating d3.js visualization responsive: Let’s look at some of the important concepts we have learned, which will be implementing through HTML code below.
Select an element to perform operation.
d3.select("body");
Use .append() method to add an element.
var svg = d3.select("body").append("svg");
set.attr() is used to set the attribute (height/width)
svg.attr({"width":500, "height":500});
Last step is to append the data to DOM.
var data_values = [15, 33, 20, 90, 10, 55, 60, 75, 58, 12];
// Create rectangles
var bars = svg.selectAll("rect")
.data(data_values)
.enter()
.append("rect")
.attr("width", "25px")
.attr("height", function(d){ return d; });
Now to make the chart responsive, replace the set height and width of the chart, with a viewBox attribute using the same height and width values.
.attr("viewBox", `0 0 300 600`)
Size of the chart is pre-defined with the height 300 and width 600.
const svg = d3
.select("#chart")
.append("svg")
.attr("height", 300)
.attr("width", 600);
Example:
HTML
<!DOCTYPE html><html> <head> <title> What is the best way to make a d3.js visualization layout responsive? </title> <style> #chart { background: steelblue; border: 1px solid black; } rect { fill: magenta; } </style> </head> <body> <div id="chart"></div> <script src='https://d3js.org/d3.v5.min.js'></script> <script id="rendered-js"> const margin = { top: 10, right: 20, bottom: 30, left: 30 }; // Dimensions: 400 x 400 // used for the initial rendering // width to height proportion // its preserved as the chart is resized const width = 600 - margin.left - margin.right; const height = 300 - margin.top - margin.bottom; const data = [15, 33, 20, 90, 10, 55, 60, 75, 58, 12]; const xScale = d3.scaleBand(). padding(0.2). domain(data). range([0, width]); const yScale = d3.scaleLinear(). domain([0, 100]). range([height, 0]); const svg = d3.select('#chart'). append('svg'). attr('width', width + margin.left + margin.right). attr('height', height + margin.top + margin.bottom). call(responsivefy) // Call responsivefy to make the chart responsive .append('g'). attr('transform', `translate(${margin.left}, ${margin.top})`); svg.selectAll('rect'). data(data). enter(). append('rect'). attr('x', d => xScale(d)). attr('y', d => yScale(d)). attr('width', d => xScale.bandwidth()). attr('height', d => height - yScale(d)); svg.append('g').call(d3.axisLeft(yScale)); svg.append('g'). attr('transform', `translate(0, ${height})`). call(d3.axisBottom(xScale)); function responsivefy(svg) { // Container is the DOM element, svg is appended. // Then we measure the container and find its // aspect ratio. const container = d3.select(svg.node().parentNode), width = parseInt(svg.style('width'), 10), height = parseInt(svg.style('height'), 10), aspect = width / height; // Add viewBox attribute to set the value to initial size // add preserveAspectRatio attribute to specify how to scale // and call resize so that svg resizes on page load svg.attr('viewBox', `0 0 ${width} ${height}`). attr('preserveAspectRatio', 'xMinYMid'). call(resize); d3.select(window).on('resize.' + container.attr('id'), resize); function resize() { const targetWidth = parseInt(container.style('width')); svg.attr('width', targetWidth); svg.attr('height', Math.round(targetWidth / aspect)); } } </script></body> </html>
Output: The graph created is resized when the window size is changed, instead of cutting the edge of the graph:
Screen dimension 720*546
Screen dimension 590*546
Screen dimension 330*546
adnanirshad158
D3.js
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n29 Jul, 2021"
},
{
"code": null,
"e": 26995,
"s": 26545,
"text": "D3 stands for Data-Driven Documents. It is an open-source JavaScript library that is used to create interactive data visualizations in the browser using HTML, SVG, and CSS. The huge amount of data is being generated in today’s world, which is very difficult to store and analyze. Visual representations of data are the most effective means of conveying information stored and D3 provides the ease and flexibility to create these data visualizations."
},
{
"code": null,
"e": 27276,
"s": 26995,
"text": "A simple way to make any SVG or D3.js chart responsive. Here we will be using D3.js to make bar graph responsive.Approach for creating d3.js visualization responsive: Let’s look at some of the important concepts we have learned, which will be implementing through HTML code below."
},
{
"code": null,
"e": 27317,
"s": 27276,
"text": "Select an element to perform operation. "
},
{
"code": null,
"e": 27336,
"s": 27317,
"text": "d3.select(\"body\");"
},
{
"code": null,
"e": 27377,
"s": 27336,
"text": "Use .append() method to add an element. "
},
{
"code": null,
"e": 27420,
"s": 27377,
"text": "var svg = d3.select(\"body\").append(\"svg\");"
},
{
"code": null,
"e": 27476,
"s": 27420,
"text": "set.attr() is used to set the attribute (height/width) "
},
{
"code": null,
"e": 27516,
"s": 27476,
"text": "svg.attr({\"width\":500, \"height\":500}); "
},
{
"code": null,
"e": 27557,
"s": 27516,
"text": "Last step is to append the data to DOM. "
},
{
"code": null,
"e": 27783,
"s": 27557,
"text": "var data_values = [15, 33, 20, 90, 10, 55, 60, 75, 58, 12];\n\n// Create rectangles \nvar bars = svg.selectAll(\"rect\")\n.data(data_values)\n.enter()\n.append(\"rect\")\n.attr(\"width\", \"25px\")\n.attr(\"height\", function(d){ return d; });"
},
{
"code": null,
"e": 27930,
"s": 27783,
"text": "Now to make the chart responsive, replace the set height and width of the chart, with a viewBox attribute using the same height and width values. "
},
{
"code": null,
"e": 27962,
"s": 27930,
"text": ".attr(\"viewBox\", `0 0 300 600`)"
},
{
"code": null,
"e": 28031,
"s": 27962,
"text": "Size of the chart is pre-defined with the height 300 and width 600. "
},
{
"code": null,
"e": 28121,
"s": 28031,
"text": "const svg = d3\n.select(\"#chart\")\n.append(\"svg\")\n.attr(\"height\", 300)\n.attr(\"width\", 600);"
},
{
"code": null,
"e": 28132,
"s": 28121,
"text": "Example: "
},
{
"code": null,
"e": 28137,
"s": 28132,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> What is the best way to make a d3.js visualization layout responsive? </title> <style> #chart { background: steelblue; border: 1px solid black; } rect { fill: magenta; } </style> </head> <body> <div id=\"chart\"></div> <script src='https://d3js.org/d3.v5.min.js'></script> <script id=\"rendered-js\"> const margin = { top: 10, right: 20, bottom: 30, left: 30 }; // Dimensions: 400 x 400 // used for the initial rendering // width to height proportion // its preserved as the chart is resized const width = 600 - margin.left - margin.right; const height = 300 - margin.top - margin.bottom; const data = [15, 33, 20, 90, 10, 55, 60, 75, 58, 12]; const xScale = d3.scaleBand(). padding(0.2). domain(data). range([0, width]); const yScale = d3.scaleLinear(). domain([0, 100]). range([height, 0]); const svg = d3.select('#chart'). append('svg'). attr('width', width + margin.left + margin.right). attr('height', height + margin.top + margin.bottom). call(responsivefy) // Call responsivefy to make the chart responsive .append('g'). attr('transform', `translate(${margin.left}, ${margin.top})`); svg.selectAll('rect'). data(data). enter(). append('rect'). attr('x', d => xScale(d)). attr('y', d => yScale(d)). attr('width', d => xScale.bandwidth()). attr('height', d => height - yScale(d)); svg.append('g').call(d3.axisLeft(yScale)); svg.append('g'). attr('transform', `translate(0, ${height})`). call(d3.axisBottom(xScale)); function responsivefy(svg) { // Container is the DOM element, svg is appended. // Then we measure the container and find its // aspect ratio. const container = d3.select(svg.node().parentNode), width = parseInt(svg.style('width'), 10), height = parseInt(svg.style('height'), 10), aspect = width / height; // Add viewBox attribute to set the value to initial size // add preserveAspectRatio attribute to specify how to scale // and call resize so that svg resizes on page load svg.attr('viewBox', `0 0 ${width} ${height}`). attr('preserveAspectRatio', 'xMinYMid'). call(resize); d3.select(window).on('resize.' + container.attr('id'), resize); function resize() { const targetWidth = parseInt(container.style('width')); svg.attr('width', targetWidth); svg.attr('height', Math.round(targetWidth / aspect)); } } </script></body> </html>",
"e": 31202,
"s": 28137,
"text": null
},
{
"code": null,
"e": 31315,
"s": 31202,
"text": "Output: The graph created is resized when the window size is changed, instead of cutting the edge of the graph: "
},
{
"code": null,
"e": 31341,
"s": 31315,
"text": "Screen dimension 720*546 "
},
{
"code": null,
"e": 31367,
"s": 31341,
"text": "Screen dimension 590*546 "
},
{
"code": null,
"e": 31393,
"s": 31367,
"text": "Screen dimension 330*546 "
},
{
"code": null,
"e": 31410,
"s": 31395,
"text": "adnanirshad158"
},
{
"code": null,
"e": 31416,
"s": 31410,
"text": "D3.js"
},
{
"code": null,
"e": 31423,
"s": 31416,
"text": "Picked"
},
{
"code": null,
"e": 31434,
"s": 31423,
"text": "JavaScript"
},
{
"code": null,
"e": 31451,
"s": 31434,
"text": "Web Technologies"
},
{
"code": null,
"e": 31478,
"s": 31451,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 31576,
"s": 31478,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31616,
"s": 31576,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31677,
"s": 31616,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 31718,
"s": 31677,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 31740,
"s": 31718,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 31794,
"s": 31740,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 31834,
"s": 31794,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31867,
"s": 31834,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31910,
"s": 31867,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 31960,
"s": 31910,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
C | Data Types | Question 2 - GeeksforGeeks
|
28 Jun, 2021
Which of the following is not a valid declaration in C?
1. short int x;
2. signed short x;
3. short x;
4. unsigned short x;
(A) 3 and 4(B) 2(C) 1(D) All are validAnswer: (D)Explanation: All are valid. First 3 mean the same thing. 4th means unsigned.Quiz of this Question
C-Data Types
Data Types
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
Substring in C++
Core Dump (Segmentation fault) in C/C++
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
C | File Handling | Question 1
C | Arrays | Question 7
C | Misc | Question 7
|
[
{
"code": null,
"e": 25577,
"s": 25549,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25633,
"s": 25577,
"text": "Which of the following is not a valid declaration in C?"
},
{
"code": "1. short int x;",
"e": 25649,
"s": 25633,
"text": null
},
{
"code": "2. signed short x;",
"e": 25668,
"s": 25649,
"text": null
},
{
"code": "3. short x;",
"e": 25680,
"s": 25668,
"text": null
},
{
"code": "4. unsigned short x;",
"e": 25701,
"s": 25680,
"text": null
},
{
"code": null,
"e": 25848,
"s": 25701,
"text": "(A) 3 and 4(B) 2(C) 1(D) All are validAnswer: (D)Explanation: All are valid. First 3 mean the same thing. 4th means unsigned.Quiz of this Question"
},
{
"code": null,
"e": 25861,
"s": 25848,
"text": "C-Data Types"
},
{
"code": null,
"e": 25872,
"s": 25861,
"text": "Data Types"
},
{
"code": null,
"e": 25883,
"s": 25872,
"text": "C Language"
},
{
"code": null,
"e": 25890,
"s": 25883,
"text": "C Quiz"
},
{
"code": null,
"e": 25988,
"s": 25890,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26023,
"s": 25988,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 26069,
"s": 26023,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 26091,
"s": 26069,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 26108,
"s": 26091,
"text": "Substring in C++"
},
{
"code": null,
"e": 26148,
"s": 26108,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 26190,
"s": 26148,
"text": "Compiling a C program:- Behind the Scenes"
},
{
"code": null,
"e": 26233,
"s": 26190,
"text": "Operator Precedence and Associativity in C"
},
{
"code": null,
"e": 26264,
"s": 26233,
"text": "C | File Handling | Question 1"
},
{
"code": null,
"e": 26288,
"s": 26264,
"text": "C | Arrays | Question 7"
}
] |
HTML | DOM scrollIntoView() Method - GeeksforGeeks
|
18 Nov, 2019
The scrollIntoView() method scrolls the specified element into the visible area of the browser window.
Syntax:
document.getElementById("id").scrollIntoView(alignTo);
Parameters:
alignTo: It is a Boolean type parameter containing true or false value. The default value is set to true.true: Scroll the element to the top of its window.false: Scroll the element to the bottom of its window.Note that the underlying terminology is not ‘top’ or ‘bottom’, I’ll get into that in the next section.So, it’s just like hovering through elements in the respective window with a button assigned with specific coordinates of the window or an element.
true: Scroll the element to the top of its window.
false: Scroll the element to the bottom of its window.
Note that the underlying terminology is not ‘top’ or ‘bottom’, I’ll get into that in the next section.So, it’s just like hovering through elements in the respective window with a button assigned with specific coordinates of the window or an element.
Example:
<!DOCTYPE html><html> <head> <style> #element { height: 200px; width: 350px; overflow: auto; background: green; } #content1 { margin: 500px; height: 100px; width: 1000px; background-color: white; } #content2 { margin: 500px; height: 50px; width: 1000px; background-color: grey; } #content3 { margin: 500px; height: 150px; width: 1000px; background-color: coral; } </style> <script> function myFunction1() { var e = document.getElementById("content1"); e.scrollIntoView(false); // Makes the element } function myFunction2() { var e = document.getElementById("content2"); e.scrollIntoView(true); } function myFunction3() { var e = document.getElementById("content3"); e.scrollIntoView(); // Default is true } </script></head> <body> <center> <h1 style="color: green">GeeksforGeeks</h1> <button onclick="myFunction1()">Scroll to element-1</button> <br> <button onclick="myFunction2()">Scroll to element-2</button> <br> <button onclick="myFunction3()">Scroll to element-3</button> <br> <br> <div id="element"> <h2 style="color: white"> Click on the scroll button to see that elements in a click.</h2> <div id="content1"> <h2 align="left">Element-1</h2> </div> <div id="content2"> <h2 align="left">Element-2</h2> </div> <div id="content3"> <h2 align="left">Element-3</h2> </div> </div> </center></body> </html>
Output:
So, in the above, the shift between the items is not being done smooth, it’s just jumping between elements.To make it look cool, object arguments comes in handy for this use.
Syntax:
document.getElementById("id").scrollIntoView({
behavior: smooth | auto;
block: start | center | end | nearest;
inline: start | center | end | nearest;
});
The behavior object determines the smoothness of the scroll has two modes ‘smooth’ and ‘auto’.The block object determines at which part of the block the element view should get started.The inline object determines at which alignment of the element should the view start.
Example:
<!DOCTYPE html><html> <head> <style> #element { height: 200px; width: 350px; overflow: auto; background: green; } #content1 { margin: 500px; height: 100px; width: 1000px; background-color: white; } #content2 { margin: 500px; height: 50px; width: 1000px; background-color: grey; } </style> <script> function myFunction1() { var e = document.getElementById("content1"); e.scrollIntoView({ block: 'start', behavior: 'smooth', inline: 'start' }); } function myFunction2() { var e = document.getElementById("content2"); // Ends the block to the window // Bottom and aligns the view to the center e.scrollIntoView({ block: 'end', behavior: 'smooth', inline: 'center' }); } </script></head> <body> <center> <h1 style="color: green">GeeksforGeeks</h1> <button onclick="myFunction1()"> Scroll to element-1 </button> <br> <button onclick="myFunction2()"> Scroll to element-2 </button> <br> <br> <br> <div id="element"> <h2 style="color: white"> Click on the scroll button to see that elements in a click. </h2> <div id="content1"> <h2 align="left">Element-1 aligned to start</h2> </div> <div id="content2"> <h2>Element-2 aligned to center</h2> </div> </div> </center></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-DOM
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
HTTP headers | Content-Type
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26331,
"s": 26303,
"text": "\n18 Nov, 2019"
},
{
"code": null,
"e": 26434,
"s": 26331,
"text": "The scrollIntoView() method scrolls the specified element into the visible area of the browser window."
},
{
"code": null,
"e": 26442,
"s": 26434,
"text": "Syntax:"
},
{
"code": null,
"e": 26497,
"s": 26442,
"text": "document.getElementById(\"id\").scrollIntoView(alignTo);"
},
{
"code": null,
"e": 26509,
"s": 26497,
"text": "Parameters:"
},
{
"code": null,
"e": 26968,
"s": 26509,
"text": "alignTo: It is a Boolean type parameter containing true or false value. The default value is set to true.true: Scroll the element to the top of its window.false: Scroll the element to the bottom of its window.Note that the underlying terminology is not ‘top’ or ‘bottom’, I’ll get into that in the next section.So, it’s just like hovering through elements in the respective window with a button assigned with specific coordinates of the window or an element."
},
{
"code": null,
"e": 27019,
"s": 26968,
"text": "true: Scroll the element to the top of its window."
},
{
"code": null,
"e": 27074,
"s": 27019,
"text": "false: Scroll the element to the bottom of its window."
},
{
"code": null,
"e": 27324,
"s": 27074,
"text": "Note that the underlying terminology is not ‘top’ or ‘bottom’, I’ll get into that in the next section.So, it’s just like hovering through elements in the respective window with a button assigned with specific coordinates of the window or an element."
},
{
"code": null,
"e": 27333,
"s": 27324,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <style> #element { height: 200px; width: 350px; overflow: auto; background: green; } #content1 { margin: 500px; height: 100px; width: 1000px; background-color: white; } #content2 { margin: 500px; height: 50px; width: 1000px; background-color: grey; } #content3 { margin: 500px; height: 150px; width: 1000px; background-color: coral; } </style> <script> function myFunction1() { var e = document.getElementById(\"content1\"); e.scrollIntoView(false); // Makes the element } function myFunction2() { var e = document.getElementById(\"content2\"); e.scrollIntoView(true); } function myFunction3() { var e = document.getElementById(\"content3\"); e.scrollIntoView(); // Default is true } </script></head> <body> <center> <h1 style=\"color: green\">GeeksforGeeks</h1> <button onclick=\"myFunction1()\">Scroll to element-1</button> <br> <button onclick=\"myFunction2()\">Scroll to element-2</button> <br> <button onclick=\"myFunction3()\">Scroll to element-3</button> <br> <br> <div id=\"element\"> <h2 style=\"color: white\"> Click on the scroll button to see that elements in a click.</h2> <div id=\"content1\"> <h2 align=\"left\">Element-1</h2> </div> <div id=\"content2\"> <h2 align=\"left\">Element-2</h2> </div> <div id=\"content3\"> <h2 align=\"left\">Element-3</h2> </div> </div> </center></body> </html>",
"e": 29255,
"s": 27333,
"text": null
},
{
"code": null,
"e": 29263,
"s": 29255,
"text": "Output:"
},
{
"code": null,
"e": 29438,
"s": 29263,
"text": "So, in the above, the shift between the items is not being done smooth, it’s just jumping between elements.To make it look cool, object arguments comes in handy for this use."
},
{
"code": null,
"e": 29446,
"s": 29438,
"text": "Syntax:"
},
{
"code": null,
"e": 29608,
"s": 29446,
"text": "document.getElementById(\"id\").scrollIntoView({\n behavior: smooth | auto;\n block: start | center | end | nearest;\n inline: start | center | end | nearest;\n});\n"
},
{
"code": null,
"e": 29879,
"s": 29608,
"text": "The behavior object determines the smoothness of the scroll has two modes ‘smooth’ and ‘auto’.The block object determines at which part of the block the element view should get started.The inline object determines at which alignment of the element should the view start."
},
{
"code": null,
"e": 29888,
"s": 29879,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <style> #element { height: 200px; width: 350px; overflow: auto; background: green; } #content1 { margin: 500px; height: 100px; width: 1000px; background-color: white; } #content2 { margin: 500px; height: 50px; width: 1000px; background-color: grey; } </style> <script> function myFunction1() { var e = document.getElementById(\"content1\"); e.scrollIntoView({ block: 'start', behavior: 'smooth', inline: 'start' }); } function myFunction2() { var e = document.getElementById(\"content2\"); // Ends the block to the window // Bottom and aligns the view to the center e.scrollIntoView({ block: 'end', behavior: 'smooth', inline: 'center' }); } </script></head> <body> <center> <h1 style=\"color: green\">GeeksforGeeks</h1> <button onclick=\"myFunction1()\"> Scroll to element-1 </button> <br> <button onclick=\"myFunction2()\"> Scroll to element-2 </button> <br> <br> <br> <div id=\"element\"> <h2 style=\"color: white\"> Click on the scroll button to see that elements in a click. </h2> <div id=\"content1\"> <h2 align=\"left\">Element-1 aligned to start</h2> </div> <div id=\"content2\"> <h2>Element-2 aligned to center</h2> </div> </div> </center></body> </html>",
"e": 31702,
"s": 29888,
"text": null
},
{
"code": null,
"e": 31710,
"s": 31702,
"text": "Output:"
},
{
"code": null,
"e": 31847,
"s": 31710,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 31856,
"s": 31847,
"text": "HTML-DOM"
},
{
"code": null,
"e": 31863,
"s": 31856,
"text": "Picked"
},
{
"code": null,
"e": 31868,
"s": 31863,
"text": "HTML"
},
{
"code": null,
"e": 31885,
"s": 31868,
"text": "Web Technologies"
},
{
"code": null,
"e": 31890,
"s": 31885,
"text": "HTML"
},
{
"code": null,
"e": 31988,
"s": 31890,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32012,
"s": 31988,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 32062,
"s": 32012,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 32103,
"s": 32062,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 32140,
"s": 32103,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 32168,
"s": 32140,
"text": "HTTP headers | Content-Type"
},
{
"code": null,
"e": 32208,
"s": 32168,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32241,
"s": 32208,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32286,
"s": 32241,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32329,
"s": 32286,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to Convert Float to Datetime in Pandas DataFrame? - GeeksforGeeks
|
29 Aug, 2020
Pandas Dataframe provides the freedom to change the data type of column values. We can change them from Integers to Float type, Integer to Datetime, String to Integer, Float to Datetime, etc. For converting float to DateTime we use pandas.to_datetime() function and following syntax is used :
Syntax: pandas.to_datetime(arg, errors=’raise’, dayfirst=False, yearfirst=False, utc=None, box=True, format=None, exact=True, unit=None, infer_datetime_format=False, origin=’unix’, cache=False)
Example 1: Converting one column from float to ‘yyyymmdd’ format using pandas.to_datetime()
Python3
# importing pandas libraryimport pandas as pd # Initializing the nested list # with Data setplayer_list = [[20200112.0,'Mathematics'], [20200114.0,'English'], [20200116.0,'Physics'], [20200119.0,'Chemistry'], [20200121.0,'French'], [20200124.0,'Biology'], [20200129.0,'Sanskrit']] # creating a pandas dataframedf = pd.DataFrame(player_list,columns=['Dates','Test']) # printing dataframe print(df)print() # checking the type print(df.dtypes)
Output:
After changing the datatype.
Python3
# converting the float to datetime format df['Dates'] = pd.to_datetime(df['Dates'], format='%Y%m%d') # printing dataframe print(df)print() print(df.dtypes)
Output:
In the above example, we change the data type of column ‘Dates‘ from ‘float64‘ to ‘datetime64[ns]‘ type.
Example 2: If the data frame column is in yymmdd format and we have to convert it to yyyymmdd format
Python3
# importing pandas libraryimport pandas as pd # Initializing the nested list with # Data setplayer_list = [[180112.0,'Mathematics'], [180114.0,'English'], [180116.0,'Physics'], [180119.0,'Chemistry'], [180121.0,'French'], [180124.0,'Biology'], [180129.0,'Sanskrit']] # creating a pandas dataframedf = pd.DataFrame(player_list,columns=['Dates','Test']) # printing dataframe print(df)print() # checking the type print(df.dtypes)
Output:
After changing the datatype.
Python3
# converting the float to datetime format df['Dates'] = pd.to_datetime(df['Dates'], format='%y%m%d') # printing dataframe print(df)print() print(df.dtypes)
Output:
In the above example, we change the data type of column ‘Dates‘ from ‘float64‘ to ‘datetime64[ns]‘ and format from ‘yymmdd‘ to ‘yyyymmdd‘.
Example 3: When we have to convert the float column to Date and Time format
Python3
# importing pandas libraryimport pandas as pd # Initializing the nested list with Data setplayer_list = [[20200112082520.0,'Mathematics'], [20200114085020.0,'English'], [20200116093529.0,'Physics'], [20200119101530.0,'Chemistry'], [20200121104060.0,'French'], [20200124113541.0,'Biology'], [20200129125023.0,'Sanskrit']] # creating a pandas dataframedf = pd.DataFrame(player_list,columns=['Dates','Test']) # printing dataframe print(df)print() # checking the type print(df.dtypes)
Output:
After changing the datatype.
Python3
# converting the float to datetime format df['Dates'] = pd.to_datetime(df['Dates'], format='%Y%m%d%H%M%S') # printing dataframe print(df)print() print(df.dtypes)
Output:
In the above example, we change the data type of column ‘Dates‘ from ‘float64‘ to ‘datetime64[ns]‘ and format to Date and Time
Example 4: Converting multiple columns from float to ‘yyyymmdd‘ format using pandas.to_datetime()
Python3
# importing pandas libraryimport pandas as pd # Initializing the nested list with Data setplayer_list = [[20200112.0,'Mathematics',20200113.0], [20200114.0,'English',20200115.0], [20200116.0,'Physics',20200117.0], [20200119.0,'Chemistry',20200120.0], [20200121.0,'French',20200122.0], [20200124.0,'Biology',20200125.0], [20200129.0,'Sanskrit',20200130.0]] # creating a pandas dataframedf = pd.DataFrame(player_list,columns=['Starting_Date','Test','Ending_Date']) # printing dataframe print(df)print() # checking the type print(df.dtypes)
Output:
After changing the datatype.
Python3
# converting the float to datetime format # in multiple columnsdf['Starting_Date'] = pd.to_datetime(df['Starting_Date'], format='%Y%m%d') df['Ending_Date'] = pd.to_datetime(df['Ending_Date'], format='%Y%m%d') # printing dataframe print(df)print() print(df.dtypes)
Output:
In the above example, we change the data type of columns ‘Starting_Date‘ and ‘Ending_Date‘ from ‘float64‘ to ‘datetime64[ns]‘ type.
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 25830,
"s": 25537,
"text": "Pandas Dataframe provides the freedom to change the data type of column values. We can change them from Integers to Float type, Integer to Datetime, String to Integer, Float to Datetime, etc. For converting float to DateTime we use pandas.to_datetime() function and following syntax is used :"
},
{
"code": null,
"e": 26024,
"s": 25830,
"text": "Syntax: pandas.to_datetime(arg, errors=’raise’, dayfirst=False, yearfirst=False, utc=None, box=True, format=None, exact=True, unit=None, infer_datetime_format=False, origin=’unix’, cache=False)"
},
{
"code": null,
"e": 26116,
"s": 26024,
"text": "Example 1: Converting one column from float to ‘yyyymmdd’ format using pandas.to_datetime()"
},
{
"code": null,
"e": 26124,
"s": 26116,
"text": "Python3"
},
{
"code": "# importing pandas libraryimport pandas as pd # Initializing the nested list # with Data setplayer_list = [[20200112.0,'Mathematics'], [20200114.0,'English'], [20200116.0,'Physics'], [20200119.0,'Chemistry'], [20200121.0,'French'], [20200124.0,'Biology'], [20200129.0,'Sanskrit']] # creating a pandas dataframedf = pd.DataFrame(player_list,columns=['Dates','Test']) # printing dataframe print(df)print() # checking the type print(df.dtypes)",
"e": 26657,
"s": 26124,
"text": null
},
{
"code": null,
"e": 26665,
"s": 26657,
"text": "Output:"
},
{
"code": null,
"e": 26694,
"s": 26665,
"text": "After changing the datatype."
},
{
"code": null,
"e": 26702,
"s": 26694,
"text": "Python3"
},
{
"code": "# converting the float to datetime format df['Dates'] = pd.to_datetime(df['Dates'], format='%Y%m%d') # printing dataframe print(df)print() print(df.dtypes)",
"e": 26861,
"s": 26702,
"text": null
},
{
"code": null,
"e": 26869,
"s": 26861,
"text": "Output:"
},
{
"code": null,
"e": 26974,
"s": 26869,
"text": "In the above example, we change the data type of column ‘Dates‘ from ‘float64‘ to ‘datetime64[ns]‘ type."
},
{
"code": null,
"e": 27075,
"s": 26974,
"text": "Example 2: If the data frame column is in yymmdd format and we have to convert it to yyyymmdd format"
},
{
"code": null,
"e": 27083,
"s": 27075,
"text": "Python3"
},
{
"code": "# importing pandas libraryimport pandas as pd # Initializing the nested list with # Data setplayer_list = [[180112.0,'Mathematics'], [180114.0,'English'], [180116.0,'Physics'], [180119.0,'Chemistry'], [180121.0,'French'], [180124.0,'Biology'], [180129.0,'Sanskrit']] # creating a pandas dataframedf = pd.DataFrame(player_list,columns=['Dates','Test']) # printing dataframe print(df)print() # checking the type print(df.dtypes)",
"e": 27598,
"s": 27083,
"text": null
},
{
"code": null,
"e": 27606,
"s": 27598,
"text": "Output:"
},
{
"code": null,
"e": 27635,
"s": 27606,
"text": "After changing the datatype."
},
{
"code": null,
"e": 27643,
"s": 27635,
"text": "Python3"
},
{
"code": "# converting the float to datetime format df['Dates'] = pd.to_datetime(df['Dates'], format='%y%m%d') # printing dataframe print(df)print() print(df.dtypes)",
"e": 27802,
"s": 27643,
"text": null
},
{
"code": null,
"e": 27810,
"s": 27802,
"text": "Output:"
},
{
"code": null,
"e": 27949,
"s": 27810,
"text": "In the above example, we change the data type of column ‘Dates‘ from ‘float64‘ to ‘datetime64[ns]‘ and format from ‘yymmdd‘ to ‘yyyymmdd‘."
},
{
"code": null,
"e": 28025,
"s": 27949,
"text": "Example 3: When we have to convert the float column to Date and Time format"
},
{
"code": null,
"e": 28033,
"s": 28025,
"text": "Python3"
},
{
"code": "# importing pandas libraryimport pandas as pd # Initializing the nested list with Data setplayer_list = [[20200112082520.0,'Mathematics'], [20200114085020.0,'English'], [20200116093529.0,'Physics'], [20200119101530.0,'Chemistry'], [20200121104060.0,'French'], [20200124113541.0,'Biology'], [20200129125023.0,'Sanskrit']] # creating a pandas dataframedf = pd.DataFrame(player_list,columns=['Dates','Test']) # printing dataframe print(df)print() # checking the type print(df.dtypes)",
"e": 28602,
"s": 28033,
"text": null
},
{
"code": null,
"e": 28610,
"s": 28602,
"text": "Output:"
},
{
"code": null,
"e": 28639,
"s": 28610,
"text": "After changing the datatype."
},
{
"code": null,
"e": 28647,
"s": 28639,
"text": "Python3"
},
{
"code": "# converting the float to datetime format df['Dates'] = pd.to_datetime(df['Dates'], format='%Y%m%d%H%M%S') # printing dataframe print(df)print() print(df.dtypes)",
"e": 28812,
"s": 28647,
"text": null
},
{
"code": null,
"e": 28820,
"s": 28812,
"text": "Output:"
},
{
"code": null,
"e": 28947,
"s": 28820,
"text": "In the above example, we change the data type of column ‘Dates‘ from ‘float64‘ to ‘datetime64[ns]‘ and format to Date and Time"
},
{
"code": null,
"e": 29045,
"s": 28947,
"text": "Example 4: Converting multiple columns from float to ‘yyyymmdd‘ format using pandas.to_datetime()"
},
{
"code": null,
"e": 29053,
"s": 29045,
"text": "Python3"
},
{
"code": "# importing pandas libraryimport pandas as pd # Initializing the nested list with Data setplayer_list = [[20200112.0,'Mathematics',20200113.0], [20200114.0,'English',20200115.0], [20200116.0,'Physics',20200117.0], [20200119.0,'Chemistry',20200120.0], [20200121.0,'French',20200122.0], [20200124.0,'Biology',20200125.0], [20200129.0,'Sanskrit',20200130.0]] # creating a pandas dataframedf = pd.DataFrame(player_list,columns=['Starting_Date','Test','Ending_Date']) # printing dataframe print(df)print() # checking the type print(df.dtypes)",
"e": 29679,
"s": 29053,
"text": null
},
{
"code": null,
"e": 29687,
"s": 29679,
"text": "Output:"
},
{
"code": null,
"e": 29716,
"s": 29687,
"text": "After changing the datatype."
},
{
"code": null,
"e": 29724,
"s": 29716,
"text": "Python3"
},
{
"code": "# converting the float to datetime format # in multiple columnsdf['Starting_Date'] = pd.to_datetime(df['Starting_Date'], format='%Y%m%d') df['Ending_Date'] = pd.to_datetime(df['Ending_Date'], format='%Y%m%d') # printing dataframe print(df)print() print(df.dtypes)",
"e": 30062,
"s": 29724,
"text": null
},
{
"code": null,
"e": 30070,
"s": 30062,
"text": "Output:"
},
{
"code": null,
"e": 30202,
"s": 30070,
"text": "In the above example, we change the data type of columns ‘Starting_Date‘ and ‘Ending_Date‘ from ‘float64‘ to ‘datetime64[ns]‘ type."
},
{
"code": null,
"e": 30226,
"s": 30202,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 30249,
"s": 30226,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 30263,
"s": 30249,
"text": "Python-pandas"
},
{
"code": null,
"e": 30270,
"s": 30263,
"text": "Python"
},
{
"code": null,
"e": 30368,
"s": 30270,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30400,
"s": 30368,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30442,
"s": 30400,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30484,
"s": 30442,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30511,
"s": 30484,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30567,
"s": 30511,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30589,
"s": 30567,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30628,
"s": 30589,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30659,
"s": 30628,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30688,
"s": 30659,
"text": "Create a directory in Python"
}
] |
Multiple Inheritance in PHP - GeeksforGeeks
|
01 Aug, 2021
Multiple Inheritance is the property of the Object Oriented Programming languages in which child class or sub class can inherit the properties of the multiple parent classes or super classes.PHP doesn’t support multiple inheritance but by using Interfaces in PHP or using Traits in PHP instead of classes, we can implement it.
Traits (Using Class along with Traits): The trait is a type of class which enables multiple inheritance. Classes, case classes, objects, and traits can all extend no more than one class but can extend multiple traits at the same time.Syntax:
class child_class_name extends parent_class_name {
use trait_name;
...
...
child_class functions
}
Example:
<?php // Class Geeksclass Geeks { public function sayhello() { echo "Hello"; }} // Trait forGeekstrait forGeeks { public function sayfor() { echo " Geeks"; }} class Sample extends Geeks { use forGeeks; public function geeksforgeeks() { echo "\nGeeksforGeeks"; } } $test = new Sample();$test->sayhello();$test->sayfor();$test->geeksforgeeks();?>
Hello Geeks
GeeksforGeeks
In the above program “traits” has been used along with parent class. There is “class” named “Geeks” which contains function sayhello() and a “trait” named “forGeeks” which contains function geeksforgeeks() and there is child class named “Sample” and we are creating the object of this class named “test” and using it we are invoking all the functions of a class and a trait.
Traits (Using Multiple Traits): Multiple Traits can be inserted into a class by listing them in the use statement, separated by commas.Syntax:
class child_class_name {
use trait_name;
...
...
child_class functions
}
Example:
<?php // trait Geekstrait Geeks { public function sayhello() { echo "Hello"; } } // trait forGeekstrait forGeeks { public function sayfor() { echo " Geeks"; } } class Sample { use Geeks; use forGeeks; public function geeksforgeeks() { echo "\nGeeksforGeeks"; } } $test = new Sample();$test->sayhello();$test->sayfor();$test->geeksforgeeks();?>
Hello Geeks
GeeksforGeeks
In the above program “traits” has been used. There are two traits named “Geeks” which contains function sayhello() and “forGeeks” which contains function geeksforgeeks() respectively and there is a child class “Sample” and we are creating the object of this class named “test” and using it we are invoking all the functions of traits.
Interface (Using Class along with Interface):Syntax:
class child_class_name extends parent_class_name implements interface_name1, ...
Example:
<?php class A { public function insideA() { echo "I am in class A"; }} interface B { public function insideB();} class Multiple extends A implements B { function insideB() { echo "\nI am in interface"; } public function insidemultiple() { echo "\nI am in inherited class"; }} $geeks = new multiple();$geeks->insideA();$geeks->insideB();$geeks->insidemultiple();?>
I am in class A
I am in interface
I am in inherited class
In the above program Interface “B” has been used along with the class “A” to implement multiple inheritance. The important point to remember is, it can’t define the function inside interface, it should be defined inside the child class “Multiple”. We are invoking all the functions using the child class (Multiple) object named “geeks”.
Interface (Using Multiple Interface):
Syntax:
class child_class_name implements interface_name1, interface_name2, ...
Example:
<?php interface C { public function insideC();} interface B { public function insideB();} class Multiple implements B, C { // Function of the interface B function insideB() { echo "\nI am in interface B"; } // Function of the interface C function insideC() { echo "\nI am in interface C"; } public function insidemultiple() { echo "\nI am in inherited class"; }} $geeks = new multiple();$geeks->insideC();$geeks->insideB();$geeks->insidemultiple();?>
I am in interface C
I am in interface B
I am in inherited class
In the above program multiple interfaces has been used to implement multiple inheritance. In above example there are two interfaces named “B” and “C” those are playing the role of the base classes and there is child class named “Multiple” and we are invoking all the functions using its object named “geeks”.
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-OOP
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to pass JavaScript variables to PHP ?
Split a comma delimited string into an array in PHP
Download file from URL using PHP
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to pass JavaScript variables to PHP ?
Split a comma delimited string into an array in PHP
How to get parameters from a URL string in PHP?
|
[
{
"code": null,
"e": 26119,
"s": 26091,
"text": "\n01 Aug, 2021"
},
{
"code": null,
"e": 26446,
"s": 26119,
"text": "Multiple Inheritance is the property of the Object Oriented Programming languages in which child class or sub class can inherit the properties of the multiple parent classes or super classes.PHP doesn’t support multiple inheritance but by using Interfaces in PHP or using Traits in PHP instead of classes, we can implement it."
},
{
"code": null,
"e": 26688,
"s": 26446,
"text": "Traits (Using Class along with Traits): The trait is a type of class which enables multiple inheritance. Classes, case classes, objects, and traits can all extend no more than one class but can extend multiple traits at the same time.Syntax:"
},
{
"code": null,
"e": 26804,
"s": 26688,
"text": "class child_class_name extends parent_class_name {\n use trait_name;\n ...\n ...\n child_class functions\n}\n"
},
{
"code": null,
"e": 26813,
"s": 26804,
"text": "Example:"
},
{
"code": "<?php // Class Geeksclass Geeks { public function sayhello() { echo \"Hello\"; }} // Trait forGeekstrait forGeeks { public function sayfor() { echo \" Geeks\"; }} class Sample extends Geeks { use forGeeks; public function geeksforgeeks() { echo \"\\nGeeksforGeeks\"; } } $test = new Sample();$test->sayhello();$test->sayfor();$test->geeksforgeeks();?>",
"e": 27184,
"s": 26813,
"text": null
},
{
"code": null,
"e": 27211,
"s": 27184,
"text": "Hello Geeks\nGeeksforGeeks\n"
},
{
"code": null,
"e": 27586,
"s": 27211,
"text": "In the above program “traits” has been used along with parent class. There is “class” named “Geeks” which contains function sayhello() and a “trait” named “forGeeks” which contains function geeksforgeeks() and there is child class named “Sample” and we are creating the object of this class named “test” and using it we are invoking all the functions of a class and a trait."
},
{
"code": null,
"e": 27729,
"s": 27586,
"text": "Traits (Using Multiple Traits): Multiple Traits can be inserted into a class by listing them in the use statement, separated by commas.Syntax:"
},
{
"code": null,
"e": 27819,
"s": 27729,
"text": "class child_class_name {\n use trait_name;\n ...\n ...\n child_class functions\n}\n"
},
{
"code": null,
"e": 27828,
"s": 27819,
"text": "Example:"
},
{
"code": "<?php // trait Geekstrait Geeks { public function sayhello() { echo \"Hello\"; } } // trait forGeekstrait forGeeks { public function sayfor() { echo \" Geeks\"; } } class Sample { use Geeks; use forGeeks; public function geeksforgeeks() { echo \"\\nGeeksforGeeks\"; } } $test = new Sample();$test->sayhello();$test->sayfor();$test->geeksforgeeks();?>",
"e": 28200,
"s": 27828,
"text": null
},
{
"code": null,
"e": 28227,
"s": 28200,
"text": "Hello Geeks\nGeeksforGeeks\n"
},
{
"code": null,
"e": 28562,
"s": 28227,
"text": "In the above program “traits” has been used. There are two traits named “Geeks” which contains function sayhello() and “forGeeks” which contains function geeksforgeeks() respectively and there is a child class “Sample” and we are creating the object of this class named “test” and using it we are invoking all the functions of traits."
},
{
"code": null,
"e": 28615,
"s": 28562,
"text": "Interface (Using Class along with Interface):Syntax:"
},
{
"code": null,
"e": 28696,
"s": 28615,
"text": "class child_class_name extends parent_class_name implements interface_name1, ..."
},
{
"code": null,
"e": 28705,
"s": 28696,
"text": "Example:"
},
{
"code": "<?php class A { public function insideA() { echo \"I am in class A\"; }} interface B { public function insideB();} class Multiple extends A implements B { function insideB() { echo \"\\nI am in interface\"; } public function insidemultiple() { echo \"\\nI am in inherited class\"; }} $geeks = new multiple();$geeks->insideA();$geeks->insideB();$geeks->insidemultiple();?>",
"e": 29110,
"s": 28705,
"text": null
},
{
"code": null,
"e": 29169,
"s": 29110,
"text": "I am in class A\nI am in interface\nI am in inherited class\n"
},
{
"code": null,
"e": 29506,
"s": 29169,
"text": "In the above program Interface “B” has been used along with the class “A” to implement multiple inheritance. The important point to remember is, it can’t define the function inside interface, it should be defined inside the child class “Multiple”. We are invoking all the functions using the child class (Multiple) object named “geeks”."
},
{
"code": null,
"e": 29544,
"s": 29506,
"text": "Interface (Using Multiple Interface):"
},
{
"code": null,
"e": 29552,
"s": 29544,
"text": "Syntax:"
},
{
"code": null,
"e": 29624,
"s": 29552,
"text": "class child_class_name implements interface_name1, interface_name2, ..."
},
{
"code": null,
"e": 29633,
"s": 29624,
"text": "Example:"
},
{
"code": "<?php interface C { public function insideC();} interface B { public function insideB();} class Multiple implements B, C { // Function of the interface B function insideB() { echo \"\\nI am in interface B\"; } // Function of the interface C function insideC() { echo \"\\nI am in interface C\"; } public function insidemultiple() { echo \"\\nI am in inherited class\"; }} $geeks = new multiple();$geeks->insideC();$geeks->insideB();$geeks->insidemultiple();?>",
"e": 30146,
"s": 29633,
"text": null
},
{
"code": null,
"e": 30211,
"s": 30146,
"text": "I am in interface C\nI am in interface B\nI am in inherited class\n"
},
{
"code": null,
"e": 30520,
"s": 30211,
"text": "In the above program multiple interfaces has been used to implement multiple inheritance. In above example there are two interfaces named “B” and “C” those are playing the role of the base classes and there is child class named “Multiple” and we are invoking all the functions using its object named “geeks”."
},
{
"code": null,
"e": 30689,
"s": 30520,
"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": 30697,
"s": 30689,
"text": "PHP-OOP"
},
{
"code": null,
"e": 30704,
"s": 30697,
"text": "Picked"
},
{
"code": null,
"e": 30708,
"s": 30704,
"text": "PHP"
},
{
"code": null,
"e": 30721,
"s": 30708,
"text": "PHP Programs"
},
{
"code": null,
"e": 30738,
"s": 30721,
"text": "Web Technologies"
},
{
"code": null,
"e": 30742,
"s": 30738,
"text": "PHP"
},
{
"code": null,
"e": 30840,
"s": 30742,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30880,
"s": 30840,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 30925,
"s": 30880,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 30967,
"s": 30925,
"text": "How to pass JavaScript variables to PHP ?"
},
{
"code": null,
"e": 31019,
"s": 30967,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 31052,
"s": 31019,
"text": "Download file from URL using PHP"
},
{
"code": null,
"e": 31092,
"s": 31052,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 31144,
"s": 31092,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 31186,
"s": 31144,
"text": "How to pass JavaScript variables to PHP ?"
},
{
"code": null,
"e": 31238,
"s": 31186,
"text": "Split a comma delimited string into an array in PHP"
}
] |
PyQt5 QCalendarWidget - Setting Enter Event - GeeksforGeeks
|
25 Nov, 2021
In this article we will see how we can implement the enter event for the QCalendarWidget. A enter event is sent to the calendar when the mouse cursor enters the calendar. This event handler can be reimplemented in a subclass to receive calendar enter events which are passed in the event parameter.Below is the Calendar class code
# QCalendarWidget Class
class Calendar(QCalendarWidget):
# constructor
def __init__(self, parent=None):
super(Calendar, self).__init__(parent)
# overriding the enter event
def enterEvent(self, event):
# setting to the text to the label
window.label.setText("Enter Event Take place")
Implementation steps: 1. Create a Calendar class that inherits the QCalendarWidget 2. Inside the Calendar class override the enterEvent and inside the event set the text to the label 3. Create a main window class 4. Create a Calendar object inside the main window 5. Set various properties to the calendar
Below is the implementation
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys # QCalendarWidget Classclass Calendar(QCalendarWidget): # constructor def __init__(self, parent = None): super(Calendar, self).__init__(parent) # overriding the enter event def enterEvent(self, event): # setting to the text to the label window.label.setText("Enter Event Take place") # overriding the leave event def leaveEvent(self, event): # setting to the text to the label window.label.setText("Leave Event Take place") class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 650, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QCalendarWidget object # as Calendar class inherits QCalendarWidget self.calendar = Calendar(self) # setting geometry to the calendar self.calendar.setGeometry(50, 10, 400, 250) # setting cursor self.calendar.setCursor(Qt.PointingHandCursor) # creating label to show the properties self.label = QLabel(self) # setting geometry to the label self.label.setGeometry(100, 280, 250, 60) # making label multi line self.label.setWordWrap(True) # setting text to the label self.label.setText("No Event") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
clintra
Python PyQt-QCalendarWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Defaultdict in Python
Enumerate() in Python
sum() function in Python
Python String | replace()
How to Install PIP on Windows ?
Deque in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Stack in Python
|
[
{
"code": null,
"e": 25729,
"s": 25701,
"text": "\n25 Nov, 2021"
},
{
"code": null,
"e": 26062,
"s": 25729,
"text": "In this article we will see how we can implement the enter event for the QCalendarWidget. A enter event is sent to the calendar when the mouse cursor enters the calendar. This event handler can be reimplemented in a subclass to receive calendar enter events which are passed in the event parameter.Below is the Calendar class code "
},
{
"code": null,
"e": 26392,
"s": 26062,
"text": "# QCalendarWidget Class\nclass Calendar(QCalendarWidget):\n \n # constructor\n def __init__(self, parent=None):\n super(Calendar, self).__init__(parent)\n\n # overriding the enter event\n def enterEvent(self, event):\n\n # setting to the text to the label\n window.label.setText(\"Enter Event Take place\")"
},
{
"code": null,
"e": 26702,
"s": 26394,
"text": "Implementation steps: 1. Create a Calendar class that inherits the QCalendarWidget 2. Inside the Calendar class override the enterEvent and inside the event set the text to the label 3. Create a main window class 4. Create a Calendar object inside the main window 5. Set various properties to the calendar "
},
{
"code": null,
"e": 26732,
"s": 26702,
"text": "Below is the implementation "
},
{
"code": null,
"e": 26740,
"s": 26732,
"text": "Python3"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys # QCalendarWidget Classclass Calendar(QCalendarWidget): # constructor def __init__(self, parent = None): super(Calendar, self).__init__(parent) # overriding the enter event def enterEvent(self, event): # setting to the text to the label window.label.setText(\"Enter Event Take place\") # overriding the leave event def leaveEvent(self, event): # setting to the text to the label window.label.setText(\"Leave Event Take place\") class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 650, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QCalendarWidget object # as Calendar class inherits QCalendarWidget self.calendar = Calendar(self) # setting geometry to the calendar self.calendar.setGeometry(50, 10, 400, 250) # setting cursor self.calendar.setCursor(Qt.PointingHandCursor) # creating label to show the properties self.label = QLabel(self) # setting geometry to the label self.label.setGeometry(100, 280, 250, 60) # making label multi line self.label.setWordWrap(True) # setting text to the label self.label.setText(\"No Event\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 28498,
"s": 26740,
"text": null
},
{
"code": null,
"e": 28509,
"s": 28498,
"text": "Output : "
},
{
"code": null,
"e": 28519,
"s": 28511,
"text": "clintra"
},
{
"code": null,
"e": 28547,
"s": 28519,
"text": "Python PyQt-QCalendarWidget"
},
{
"code": null,
"e": 28558,
"s": 28547,
"text": "Python-gui"
},
{
"code": null,
"e": 28570,
"s": 28558,
"text": "Python-PyQt"
},
{
"code": null,
"e": 28577,
"s": 28570,
"text": "Python"
},
{
"code": null,
"e": 28675,
"s": 28577,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28693,
"s": 28675,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28715,
"s": 28693,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28737,
"s": 28715,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28762,
"s": 28737,
"text": "sum() function in Python"
},
{
"code": null,
"e": 28788,
"s": 28762,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28820,
"s": 28788,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28836,
"s": 28820,
"text": "Deque in Python"
},
{
"code": null,
"e": 28878,
"s": 28836,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28908,
"s": 28878,
"text": "Iterate over a list in Python"
}
] |
MAN Full Form - GeeksforGeeks
|
19 Aug, 2021
MAN stands for metropolitan area network and it is basically a computer network that is made by connecting multiple LAN’S. MAN covers a geographical area which is known as the metropolitan area. It serves as a connection which is larger than LAN(Local Area Network) but smaller than WAN(Wide Area Network). It generally covers the area of a city. It connects different LAN’s in an area by point to point connection. MAN also provides sharing of regional resources. MAN is very effective to use in large area like a city or a large campus.
Examples:
Cable TV network and telephone networks
Characteristics :
Area Covered – It covers an area from 5 km to 50 km which can cover a city.
Ownership – MAN is owned by a group of users rather than a single company.
High speed – MAN provides high speed network which uses shared regional resources.
Size – Size of MAN is in between WAN and LAN.
Advantages :
MAN covers a larger area than LAN.
It has less implementation cost and it uses less resources.
It provides higher security than WAN.
It can cover area as large as a city.
MAN is a faster way to connect two fast LANs together. This is due to the fast configuration of links.
In some installation of MANs, users can share their internet connection. So multiple users can get the same high-speed internet.
Disadvantages :
MAN is not easily manageable as it becomes very complex.
It requires highly skilled people to look after it.
It requires more cables for connecting the LAN’s.
It has high management cost
It covers smaller area than WAN.
It is only used in metropolitan areas.
Examples of metropolitan area network (MAN) :
Some of the examples of MAN are:-
Digital cable television
Used in government agencies
Used to connect several branches of the local school
A network of fire stations
University campuses
Networking between community colleges within the country
Cable broadband
pp_pankaj
jyoti369
naveenkumarkharwal
Computer Networks
Full Form
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced Encryption Standard (AES)
Intrusion Detection System (IDS)
Introduction and IPv4 Datagram Header
Secure Socket Layer (SSL)
Cryptography and its Types
DBA Full Form
RDBMS Full Form
HTTP Full Form
CDMA Full Form
SCTP Full Form
|
[
{
"code": null,
"e": 25780,
"s": 25752,
"text": "\n19 Aug, 2021"
},
{
"code": null,
"e": 26320,
"s": 25780,
"text": "MAN stands for metropolitan area network and it is basically a computer network that is made by connecting multiple LAN’S. MAN covers a geographical area which is known as the metropolitan area. It serves as a connection which is larger than LAN(Local Area Network) but smaller than WAN(Wide Area Network). It generally covers the area of a city. It connects different LAN’s in an area by point to point connection. MAN also provides sharing of regional resources. MAN is very effective to use in large area like a city or a large campus. "
},
{
"code": null,
"e": 26372,
"s": 26322,
"text": "Examples:\nCable TV network and telephone networks"
},
{
"code": null,
"e": 26392,
"s": 26372,
"text": "Characteristics : "
},
{
"code": null,
"e": 26468,
"s": 26392,
"text": "Area Covered – It covers an area from 5 km to 50 km which can cover a city."
},
{
"code": null,
"e": 26543,
"s": 26468,
"text": "Ownership – MAN is owned by a group of users rather than a single company."
},
{
"code": null,
"e": 26626,
"s": 26543,
"text": "High speed – MAN provides high speed network which uses shared regional resources."
},
{
"code": null,
"e": 26672,
"s": 26626,
"text": "Size – Size of MAN is in between WAN and LAN."
},
{
"code": null,
"e": 26686,
"s": 26672,
"text": "Advantages : "
},
{
"code": null,
"e": 26721,
"s": 26686,
"text": "MAN covers a larger area than LAN."
},
{
"code": null,
"e": 26781,
"s": 26721,
"text": "It has less implementation cost and it uses less resources."
},
{
"code": null,
"e": 26819,
"s": 26781,
"text": "It provides higher security than WAN."
},
{
"code": null,
"e": 26857,
"s": 26819,
"text": "It can cover area as large as a city."
},
{
"code": null,
"e": 26960,
"s": 26857,
"text": "MAN is a faster way to connect two fast LANs together. This is due to the fast configuration of links."
},
{
"code": null,
"e": 27089,
"s": 26960,
"text": "In some installation of MANs, users can share their internet connection. So multiple users can get the same high-speed internet."
},
{
"code": null,
"e": 27109,
"s": 27089,
"text": " Disadvantages : "
},
{
"code": null,
"e": 27166,
"s": 27109,
"text": "MAN is not easily manageable as it becomes very complex."
},
{
"code": null,
"e": 27218,
"s": 27166,
"text": "It requires highly skilled people to look after it."
},
{
"code": null,
"e": 27268,
"s": 27218,
"text": "It requires more cables for connecting the LAN’s."
},
{
"code": null,
"e": 27296,
"s": 27268,
"text": "It has high management cost"
},
{
"code": null,
"e": 27329,
"s": 27296,
"text": "It covers smaller area than WAN."
},
{
"code": null,
"e": 27368,
"s": 27329,
"text": "It is only used in metropolitan areas."
},
{
"code": null,
"e": 27414,
"s": 27368,
"text": "Examples of metropolitan area network (MAN) :"
},
{
"code": null,
"e": 27449,
"s": 27414,
"text": " Some of the examples of MAN are:-"
},
{
"code": null,
"e": 27474,
"s": 27449,
"text": "Digital cable television"
},
{
"code": null,
"e": 27502,
"s": 27474,
"text": "Used in government agencies"
},
{
"code": null,
"e": 27555,
"s": 27502,
"text": "Used to connect several branches of the local school"
},
{
"code": null,
"e": 27582,
"s": 27555,
"text": "A network of fire stations"
},
{
"code": null,
"e": 27602,
"s": 27582,
"text": "University campuses"
},
{
"code": null,
"e": 27659,
"s": 27602,
"text": "Networking between community colleges within the country"
},
{
"code": null,
"e": 27675,
"s": 27659,
"text": "Cable broadband"
},
{
"code": null,
"e": 27685,
"s": 27675,
"text": "pp_pankaj"
},
{
"code": null,
"e": 27694,
"s": 27685,
"text": "jyoti369"
},
{
"code": null,
"e": 27713,
"s": 27694,
"text": "naveenkumarkharwal"
},
{
"code": null,
"e": 27731,
"s": 27713,
"text": "Computer Networks"
},
{
"code": null,
"e": 27741,
"s": 27731,
"text": "Full Form"
},
{
"code": null,
"e": 27759,
"s": 27741,
"text": "Computer Networks"
},
{
"code": null,
"e": 27857,
"s": 27759,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27892,
"s": 27857,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 27925,
"s": 27892,
"text": "Intrusion Detection System (IDS)"
},
{
"code": null,
"e": 27963,
"s": 27925,
"text": "Introduction and IPv4 Datagram Header"
},
{
"code": null,
"e": 27989,
"s": 27963,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 28016,
"s": 27989,
"text": "Cryptography and its Types"
},
{
"code": null,
"e": 28030,
"s": 28016,
"text": "DBA Full Form"
},
{
"code": null,
"e": 28046,
"s": 28030,
"text": "RDBMS Full Form"
},
{
"code": null,
"e": 28061,
"s": 28046,
"text": "HTTP Full Form"
},
{
"code": null,
"e": 28076,
"s": 28061,
"text": "CDMA Full Form"
}
] |
Find two numbers B and C such that their product is A and their GCD is maximum - GeeksforGeeks
|
19 Jan, 2022
Given a positive integer, A. The task is to find two numbers B and C such that their product is A and their GCD should be maximum.
Examples:
Input: A = 72Output: 12 6Explanation: The product of 12 and 6 is 72 and GCD(12, 6) is 6 which is maximum possible.
Input: A = 54Output: 6 9Explanation: The product of 6 and 9 is 54, gcd(6, 9) is 3 which is maximum possible.
Approach: This problem can be solved by generating Prime factors of A. To maximize GCD the only possible way is to choose different prime factors so that product of them would give the maximum GCD. Follow the steps given below to solve the problem.
Create a function say, primeFactors() to find all the prime factors of a number.
Firstly call primeFactors() and pass A and an array is passed by reference to store all prime factors in a sorted manner.
Iterate over the prime factor array, and distribute all the factors of A to B and C alternatively such that,B = primefactor[0] * primefactor[2] * primefactor[4] – – – and so on.C = primefactor[1] * primefactor[3] * primefactor[5] – – – and so on.
B = primefactor[0] * primefactor[2] * primefactor[4] – – – and so on.
C = primefactor[1] * primefactor[3] * primefactor[5] – – – and so on.
Output the numbers B and C separated by space.
For Example: N = 72Prime Factorization of 72 = 2 * 2 * 2 * 3 * 3. primefactor[] = {2, 2, 2, 3, 3}B = primefactor[0] * primefactor[2] * primefactor[4] => 2 * 2 * 3 = 12.C = primefactor[1] * primefactor[3] => 2 * 3 = 6.Hence, B = 12 and C = 6.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to stores prime factors// of a number in a vector.void primeFactors(int A, vector<int>& prime){ while (A % 2 == 0) { prime.push_back(2); A = A / 2; } for (int i = 3; i <= sqrt(A); i += 2) { while (A % i == 0) { prime.push_back(i); A = A / i; } } if (A > 2) prime.push_back(A);} // Find the numbers B and C// such that gcd(B, C) is max// and product is A.void maxPairGCD(int A){ // Vector to store prime factors vector<int> prime; primeFactors(A, prime); int B = 1, C = 1; int temp = 0; for (int i = 0; i < prime.size(); i++) { if (temp == 0) B *= prime[i]; else C *= prime[i]; temp = temp ^ 1; } cout << B << " " << C;} // Driver codeint main(){ int A = 72; // Function Call maxPairGCD(A); return 0;}
// Java program to implement// the above approachimport java.util.ArrayList; class GFG{ // Function to stores prime factors // of a number in a vector. static void primeFactors(int A, ArrayList<Integer> prime) { while (A % 2 == 0) { prime.add(2); A = A / 2; } for (int i = 3; i <= Math.sqrt(A); i += 2) { while (A % i == 0) { prime.add(i); A = A / i; } } if (A > 2) prime.add(A); } // Find the numbers B and C // such that gcd(B, C) is max // and product is A. static void maxPairGCD(int A) { // Vector to store prime factors ArrayList<Integer> prime = new ArrayList<Integer>(); primeFactors(A, prime); int B = 1, C = 1; int temp = 0; for (int i = 0; i < prime.size(); i++) { if (temp == 0) B *= prime.get(i); else C *= prime.get(i); temp = temp ^ 1; } System.out.println(B + " " + C); } // Driver code public static void main(String args[]) { int A = 72; // Function Call maxPairGCD(A); }} // This code is contributed by Saurabh Jaiswal
# Python 3 program for above approachimport math # Function to stores prime factors# of a number in a vector.def primeFactors(A, prime): while (A % 2 == 0): prime.append(2) A = A / 2 for i in range(3, int(math.sqrt(A)) + 1, 2): while (A % i == 0): prime.append(i) A = A / i if (A > 2): prime.append(A) # Find the numbers B and C# such that gcd(B, C) is max# and product is A.def maxPairGCD(A): # Vector to store prime factors prime = [] primeFactors(A, prime) B = 1 C = 1 temp = 0 for i in range(len(prime)): if (temp == 0): B *= prime[i] else: C *= prime[i] temp = temp ^ 1 print(B, C) # Driver codeif __name__ == "__main__": A = 72 # Function Call maxPairGCD(A) # This code is contributed by ukasp.
// C# program to implement// the above approachusing System;using System.Collections; class GFG{ // Function to stores prime factors // of a number in a vector. static void primeFactors(int A, ArrayList prime) { while (A % 2 == 0) { prime.Add(2); A = A / 2; } for (int i = 3; i <= Math.Sqrt(A); i += 2) { while (A % i == 0) { prime.Add(i); A = A / i; } } if (A > 2) prime.Add(A); } // Find the numbers B and C // such that gcd(B, C) is max // and product is A. static void maxPairGCD(int A) { // Vector to store prime factors ArrayList prime = new ArrayList(); primeFactors(A, prime); int B = 1, C = 1; int temp = 0; for (int i = 0; i < prime.Count; i++) { if (temp == 0) B *= (int)prime[i]; else C *= (int)prime[i]; temp = temp ^ 1; } Console.Write(B + " " + C); } // Driver code public static void Main() { int A = 72; // Function Call maxPairGCD(A); }} // This code is contributed by Samim Hossain Mondal.
<script> // JavaScript code for the above approach // Function to stores prime factors // of a number in a vector. function primeFactors(A, prime) { while (A % 2 == 0) { prime.push(2); A = A / 2; } for (let i = 3; i <= Math.sqrt(A); i += 2) { while (A % i == 0) { prime.push(i); A = A / i; } } if (A > 2) prime.push(A); return prime; } // Find the numbers B and C // such that gcd(B, C) is max // and product is A. function maxPairGCD(A) { // Vector to store prime factors let prime = []; prime = primeFactors(A, prime); let B = 1, C = 1; let temp = 0; for (let i = 0; i < prime.length; i++) { if (temp == 0) B *= prime[i]; else C *= prime[i]; temp = temp ^ 1; } document.write(B + " " + C) } // Driver code let A = 72; // Function Call maxPairGCD(A); // This code is contributed by Potta Lokesh </script>
12 6
Time Complexity: O(Sqrt(A) )Auxiliary Space: O(log(A))
lokeshpotta20
samim2000
ukasp
_saurabh_jaiswal
GCD-LCM
Prime Number
sieve
Greedy
Mathematical
Greedy
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Optimal Page Replacement Algorithm
Program for Best Fit algorithm in Memory Management
Program for First Fit algorithm in Memory Management
Bin Packing Problem (Minimize number of used Bins)
Max Flow Problem Introduction
Program for Fibonacci numbers
C++ Data Types
Set in C++ Standard Template Library (STL)
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
|
[
{
"code": null,
"e": 26537,
"s": 26509,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 26668,
"s": 26537,
"text": "Given a positive integer, A. The task is to find two numbers B and C such that their product is A and their GCD should be maximum."
},
{
"code": null,
"e": 26679,
"s": 26668,
"text": "Examples: "
},
{
"code": null,
"e": 26796,
"s": 26679,
"text": "Input: A = 72Output: 12 6Explanation: The product of 12 and 6 is 72 and GCD(12, 6) is 6 which is maximum possible. "
},
{
"code": null,
"e": 26906,
"s": 26796,
"text": "Input: A = 54Output: 6 9Explanation: The product of 6 and 9 is 54, gcd(6, 9) is 3 which is maximum possible. "
},
{
"code": null,
"e": 27156,
"s": 26906,
"text": "Approach: This problem can be solved by generating Prime factors of A. To maximize GCD the only possible way is to choose different prime factors so that product of them would give the maximum GCD. Follow the steps given below to solve the problem. "
},
{
"code": null,
"e": 27237,
"s": 27156,
"text": "Create a function say, primeFactors() to find all the prime factors of a number."
},
{
"code": null,
"e": 27359,
"s": 27237,
"text": "Firstly call primeFactors() and pass A and an array is passed by reference to store all prime factors in a sorted manner."
},
{
"code": null,
"e": 27606,
"s": 27359,
"text": "Iterate over the prime factor array, and distribute all the factors of A to B and C alternatively such that,B = primefactor[0] * primefactor[2] * primefactor[4] – – – and so on.C = primefactor[1] * primefactor[3] * primefactor[5] – – – and so on."
},
{
"code": null,
"e": 27676,
"s": 27606,
"text": "B = primefactor[0] * primefactor[2] * primefactor[4] – – – and so on."
},
{
"code": null,
"e": 27746,
"s": 27676,
"text": "C = primefactor[1] * primefactor[3] * primefactor[5] – – – and so on."
},
{
"code": null,
"e": 27793,
"s": 27746,
"text": "Output the numbers B and C separated by space."
},
{
"code": null,
"e": 28035,
"s": 27793,
"text": "For Example: N = 72Prime Factorization of 72 = 2 * 2 * 2 * 3 * 3. primefactor[] = {2, 2, 2, 3, 3}B = primefactor[0] * primefactor[2] * primefactor[4] => 2 * 2 * 3 = 12.C = primefactor[1] * primefactor[3] => 2 * 3 = 6.Hence, B = 12 and C = 6."
},
{
"code": null,
"e": 28086,
"s": 28035,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 28090,
"s": 28086,
"text": "C++"
},
{
"code": null,
"e": 28095,
"s": 28090,
"text": "Java"
},
{
"code": null,
"e": 28103,
"s": 28095,
"text": "Python3"
},
{
"code": null,
"e": 28106,
"s": 28103,
"text": "C#"
},
{
"code": null,
"e": 28117,
"s": 28106,
"text": "Javascript"
},
{
"code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to stores prime factors// of a number in a vector.void primeFactors(int A, vector<int>& prime){ while (A % 2 == 0) { prime.push_back(2); A = A / 2; } for (int i = 3; i <= sqrt(A); i += 2) { while (A % i == 0) { prime.push_back(i); A = A / i; } } if (A > 2) prime.push_back(A);} // Find the numbers B and C// such that gcd(B, C) is max// and product is A.void maxPairGCD(int A){ // Vector to store prime factors vector<int> prime; primeFactors(A, prime); int B = 1, C = 1; int temp = 0; for (int i = 0; i < prime.size(); i++) { if (temp == 0) B *= prime[i]; else C *= prime[i]; temp = temp ^ 1; } cout << B << \" \" << C;} // Driver codeint main(){ int A = 72; // Function Call maxPairGCD(A); return 0;}",
"e": 29064,
"s": 28117,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.ArrayList; class GFG{ // Function to stores prime factors // of a number in a vector. static void primeFactors(int A, ArrayList<Integer> prime) { while (A % 2 == 0) { prime.add(2); A = A / 2; } for (int i = 3; i <= Math.sqrt(A); i += 2) { while (A % i == 0) { prime.add(i); A = A / i; } } if (A > 2) prime.add(A); } // Find the numbers B and C // such that gcd(B, C) is max // and product is A. static void maxPairGCD(int A) { // Vector to store prime factors ArrayList<Integer> prime = new ArrayList<Integer>(); primeFactors(A, prime); int B = 1, C = 1; int temp = 0; for (int i = 0; i < prime.size(); i++) { if (temp == 0) B *= prime.get(i); else C *= prime.get(i); temp = temp ^ 1; } System.out.println(B + \" \" + C); } // Driver code public static void main(String args[]) { int A = 72; // Function Call maxPairGCD(A); }} // This code is contributed by Saurabh Jaiswal",
"e": 30153,
"s": 29064,
"text": null
},
{
"code": "# Python 3 program for above approachimport math # Function to stores prime factors# of a number in a vector.def primeFactors(A, prime): while (A % 2 == 0): prime.append(2) A = A / 2 for i in range(3, int(math.sqrt(A)) + 1, 2): while (A % i == 0): prime.append(i) A = A / i if (A > 2): prime.append(A) # Find the numbers B and C# such that gcd(B, C) is max# and product is A.def maxPairGCD(A): # Vector to store prime factors prime = [] primeFactors(A, prime) B = 1 C = 1 temp = 0 for i in range(len(prime)): if (temp == 0): B *= prime[i] else: C *= prime[i] temp = temp ^ 1 print(B, C) # Driver codeif __name__ == \"__main__\": A = 72 # Function Call maxPairGCD(A) # This code is contributed by ukasp.",
"e": 31005,
"s": 30153,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections; class GFG{ // Function to stores prime factors // of a number in a vector. static void primeFactors(int A, ArrayList prime) { while (A % 2 == 0) { prime.Add(2); A = A / 2; } for (int i = 3; i <= Math.Sqrt(A); i += 2) { while (A % i == 0) { prime.Add(i); A = A / i; } } if (A > 2) prime.Add(A); } // Find the numbers B and C // such that gcd(B, C) is max // and product is A. static void maxPairGCD(int A) { // Vector to store prime factors ArrayList prime = new ArrayList(); primeFactors(A, prime); int B = 1, C = 1; int temp = 0; for (int i = 0; i < prime.Count; i++) { if (temp == 0) B *= (int)prime[i]; else C *= (int)prime[i]; temp = temp ^ 1; } Console.Write(B + \" \" + C); } // Driver code public static void Main() { int A = 72; // Function Call maxPairGCD(A); }} // This code is contributed by Samim Hossain Mondal.",
"e": 32053,
"s": 31005,
"text": null
},
{
"code": "<script> // JavaScript code for the above approach // Function to stores prime factors // of a number in a vector. function primeFactors(A, prime) { while (A % 2 == 0) { prime.push(2); A = A / 2; } for (let i = 3; i <= Math.sqrt(A); i += 2) { while (A % i == 0) { prime.push(i); A = A / i; } } if (A > 2) prime.push(A); return prime; } // Find the numbers B and C // such that gcd(B, C) is max // and product is A. function maxPairGCD(A) { // Vector to store prime factors let prime = []; prime = primeFactors(A, prime); let B = 1, C = 1; let temp = 0; for (let i = 0; i < prime.length; i++) { if (temp == 0) B *= prime[i]; else C *= prime[i]; temp = temp ^ 1; } document.write(B + \" \" + C) } // Driver code let A = 72; // Function Call maxPairGCD(A); // This code is contributed by Potta Lokesh </script>",
"e": 33353,
"s": 32053,
"text": null
},
{
"code": null,
"e": 33358,
"s": 33353,
"text": "12 6"
},
{
"code": null,
"e": 33415,
"s": 33360,
"text": "Time Complexity: O(Sqrt(A) )Auxiliary Space: O(log(A))"
},
{
"code": null,
"e": 33431,
"s": 33417,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 33441,
"s": 33431,
"text": "samim2000"
},
{
"code": null,
"e": 33447,
"s": 33441,
"text": "ukasp"
},
{
"code": null,
"e": 33464,
"s": 33447,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 33472,
"s": 33464,
"text": "GCD-LCM"
},
{
"code": null,
"e": 33485,
"s": 33472,
"text": "Prime Number"
},
{
"code": null,
"e": 33491,
"s": 33485,
"text": "sieve"
},
{
"code": null,
"e": 33498,
"s": 33491,
"text": "Greedy"
},
{
"code": null,
"e": 33511,
"s": 33498,
"text": "Mathematical"
},
{
"code": null,
"e": 33518,
"s": 33511,
"text": "Greedy"
},
{
"code": null,
"e": 33531,
"s": 33518,
"text": "Mathematical"
},
{
"code": null,
"e": 33544,
"s": 33531,
"text": "Prime Number"
},
{
"code": null,
"e": 33550,
"s": 33544,
"text": "sieve"
},
{
"code": null,
"e": 33648,
"s": 33550,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33683,
"s": 33648,
"text": "Optimal Page Replacement Algorithm"
},
{
"code": null,
"e": 33735,
"s": 33683,
"text": "Program for Best Fit algorithm in Memory Management"
},
{
"code": null,
"e": 33788,
"s": 33735,
"text": "Program for First Fit algorithm in Memory Management"
},
{
"code": null,
"e": 33839,
"s": 33788,
"text": "Bin Packing Problem (Minimize number of used Bins)"
},
{
"code": null,
"e": 33869,
"s": 33839,
"text": "Max Flow Problem Introduction"
},
{
"code": null,
"e": 33899,
"s": 33869,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 33914,
"s": 33899,
"text": "C++ Data Types"
},
{
"code": null,
"e": 33957,
"s": 33914,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 33981,
"s": 33957,
"text": "Merge two sorted arrays"
}
] |
Python - Group Elements in Matrix - GeeksforGeeks
|
30 Dec, 2020
Given a Matrix with two columns, group 2nd column elements on basis of 1st column.
Input : test_list = [[5, 8], [2, 0], [5, 4], [2, 3], [2, 9]]Output : {5: [8, 4], 2: [0, 3, 9]}Explanation : 8 and 4 are mapped to 5 in Matrix, all others to 2.
Input : test_list = [[2, 8], [2, 0], [2, 4], [2, 3], [2, 9]]Output : {2: [8, 4, 0, 3, 9]}Explanation : All mapped to 2.
Method #1 : Using dictionary comprehension + loop
This is one of the ways in which this task can be performed. In this, we construct the dictionary with empty list values from row 1 and then run a loop to assign values into it.
Python3
# Python3 code to demonstrate working of # Group Elements in Matrix# Using dictionary comprehension + loop # initializing listtest_list = [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]] # printing original listprint("The original list : " + str(test_list)) # initializing empty dictionary with default empty list res = {idx[0]: [] for idx in test_list} # using loop for groupingfor idx in test_list: res[idx[0]].append(idx[1]) # printing result print("The Grouped Matrix : " + str(res))
The original list : [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]
The Grouped Matrix : {5: [8, 4], 2: [0, 3], 7: [9]}
Method #2 : Using loop + defaultdict()
This is similar to above method. The difference being that initial empty mesh is created using defaultdict().
Python3
# Python3 code to demonstrate working of # Group Elements in Matrix# Using loop + defaultdict()from collections import defaultdict # initializing listtest_list = [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]] # printing original listprint("The original list : " + str(test_list)) # initializing empty dictionary using defaultdictres = defaultdict(list) # using loop for groupingfor idx in test_list: res[idx[0]].append(idx[1]) # printing result print("The Grouped Matrix : " + str(dict(res)))
The original list : [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]
The Grouped Matrix : {5: [8, 4], 2: [0, 3], 7: [9]}
Python dictionary-programs
Python matrix-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n30 Dec, 2020"
},
{
"code": null,
"e": 25620,
"s": 25537,
"text": "Given a Matrix with two columns, group 2nd column elements on basis of 1st column."
},
{
"code": null,
"e": 25780,
"s": 25620,
"text": "Input : test_list = [[5, 8], [2, 0], [5, 4], [2, 3], [2, 9]]Output : {5: [8, 4], 2: [0, 3, 9]}Explanation : 8 and 4 are mapped to 5 in Matrix, all others to 2."
},
{
"code": null,
"e": 25900,
"s": 25780,
"text": "Input : test_list = [[2, 8], [2, 0], [2, 4], [2, 3], [2, 9]]Output : {2: [8, 4, 0, 3, 9]}Explanation : All mapped to 2."
},
{
"code": null,
"e": 25950,
"s": 25900,
"text": "Method #1 : Using dictionary comprehension + loop"
},
{
"code": null,
"e": 26128,
"s": 25950,
"text": "This is one of the ways in which this task can be performed. In this, we construct the dictionary with empty list values from row 1 and then run a loop to assign values into it."
},
{
"code": null,
"e": 26136,
"s": 26128,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Group Elements in Matrix# Using dictionary comprehension + loop # initializing listtest_list = [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]] # printing original listprint(\"The original list : \" + str(test_list)) # initializing empty dictionary with default empty list res = {idx[0]: [] for idx in test_list} # using loop for groupingfor idx in test_list: res[idx[0]].append(idx[1]) # printing result print(\"The Grouped Matrix : \" + str(res))",
"e": 26624,
"s": 26136,
"text": null
},
{
"code": null,
"e": 26738,
"s": 26624,
"text": "The original list : [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]\nThe Grouped Matrix : {5: [8, 4], 2: [0, 3], 7: [9]}\n"
},
{
"code": null,
"e": 26777,
"s": 26738,
"text": "Method #2 : Using loop + defaultdict()"
},
{
"code": null,
"e": 26887,
"s": 26777,
"text": "This is similar to above method. The difference being that initial empty mesh is created using defaultdict()."
},
{
"code": null,
"e": 26895,
"s": 26887,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Group Elements in Matrix# Using loop + defaultdict()from collections import defaultdict # initializing listtest_list = [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]] # printing original listprint(\"The original list : \" + str(test_list)) # initializing empty dictionary using defaultdictres = defaultdict(list) # using loop for groupingfor idx in test_list: res[idx[0]].append(idx[1]) # printing result print(\"The Grouped Matrix : \" + str(dict(res)))",
"e": 27390,
"s": 26895,
"text": null
},
{
"code": null,
"e": 27504,
"s": 27390,
"text": "The original list : [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]\nThe Grouped Matrix : {5: [8, 4], 2: [0, 3], 7: [9]}\n"
},
{
"code": null,
"e": 27531,
"s": 27504,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 27553,
"s": 27531,
"text": "Python matrix-program"
},
{
"code": null,
"e": 27560,
"s": 27553,
"text": "Python"
},
{
"code": null,
"e": 27576,
"s": 27560,
"text": "Python Programs"
},
{
"code": null,
"e": 27674,
"s": 27576,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27706,
"s": 27674,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27748,
"s": 27706,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27790,
"s": 27748,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27846,
"s": 27790,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27873,
"s": 27846,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27895,
"s": 27873,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27934,
"s": 27895,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27980,
"s": 27934,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28018,
"s": 27980,
"text": "Python | Convert a list to dictionary"
}
] |
Python | Find closest number to k in given list - GeeksforGeeks
|
17 Oct, 2019
Given a list of numbers and a variable K, where K is also a number, write a Python program to find the number in a list which is closest to the given number K.
Examples:
Input : lst = [3.64, 5.2, 9.42, 9.35, 8.5, 8], K = 9.1
Output : 9.35
Input : lst = [9, 11, 5, 3, 25, 18], K = 6
Output : 5
Method #1 : Using min() method
In this approach, we use min method from Python and apply a key that finds the absolute difference of each element with K, and returns the element having minimum difference.
# Python3 program to find Closest number in a list def closest(lst, K): return lst[min(range(len(lst)), key = lambda i: abs(lst[i]-K))] # Driver codelst = [3.64, 5.2, 9.42, 9.35, 8.5, 8]K = 9.1print(closest(lst, K))
9.35
Method #2 : Using numpy module
This approach applies the same method but using numpy module. First we convert the given list to an array. Find absolute difference with K of each element, and return the minimum from it.
# Python3 program to find Closest number in a listimport numpy as npdef closest(lst, K): lst = np.asarray(lst) idx = (np.abs(lst - K)).argmin() return lst[idx] # Driver codelst = [3.64, 5.2, 9.42, 9.35, 8.5, 8]K = 9.1print(closest(lst, K))
9.35
nidhi_biet
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 26147,
"s": 26119,
"text": "\n17 Oct, 2019"
},
{
"code": null,
"e": 26307,
"s": 26147,
"text": "Given a list of numbers and a variable K, where K is also a number, write a Python program to find the number in a list which is closest to the given number K."
},
{
"code": null,
"e": 26317,
"s": 26307,
"text": "Examples:"
},
{
"code": null,
"e": 26442,
"s": 26317,
"text": "Input : lst = [3.64, 5.2, 9.42, 9.35, 8.5, 8], K = 9.1\nOutput : 9.35\n\nInput : lst = [9, 11, 5, 3, 25, 18], K = 6\nOutput : 5\n"
},
{
"code": null,
"e": 26474,
"s": 26442,
"text": " Method #1 : Using min() method"
},
{
"code": null,
"e": 26648,
"s": 26474,
"text": "In this approach, we use min method from Python and apply a key that finds the absolute difference of each element with K, and returns the element having minimum difference."
},
{
"code": "# Python3 program to find Closest number in a list def closest(lst, K): return lst[min(range(len(lst)), key = lambda i: abs(lst[i]-K))] # Driver codelst = [3.64, 5.2, 9.42, 9.35, 8.5, 8]K = 9.1print(closest(lst, K))",
"e": 26879,
"s": 26648,
"text": null
},
{
"code": null,
"e": 26885,
"s": 26879,
"text": "9.35\n"
},
{
"code": null,
"e": 26917,
"s": 26885,
"text": " Method #2 : Using numpy module"
},
{
"code": null,
"e": 27105,
"s": 26917,
"text": "This approach applies the same method but using numpy module. First we convert the given list to an array. Find absolute difference with K of each element, and return the minimum from it."
},
{
"code": "# Python3 program to find Closest number in a listimport numpy as npdef closest(lst, K): lst = np.asarray(lst) idx = (np.abs(lst - K)).argmin() return lst[idx] # Driver codelst = [3.64, 5.2, 9.42, 9.35, 8.5, 8]K = 9.1print(closest(lst, K))",
"e": 27368,
"s": 27105,
"text": null
},
{
"code": null,
"e": 27374,
"s": 27368,
"text": "9.35\n"
},
{
"code": null,
"e": 27385,
"s": 27374,
"text": "nidhi_biet"
},
{
"code": null,
"e": 27392,
"s": 27385,
"text": "Python"
},
{
"code": null,
"e": 27408,
"s": 27392,
"text": "Python Programs"
},
{
"code": null,
"e": 27506,
"s": 27408,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27524,
"s": 27506,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27556,
"s": 27524,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27578,
"s": 27556,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27620,
"s": 27578,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27646,
"s": 27620,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27689,
"s": 27646,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27711,
"s": 27689,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27757,
"s": 27711,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27795,
"s": 27757,
"text": "Python | Convert a list to dictionary"
}
] |
Python Program to Find the Number Occurring Odd Number of Times - GeeksforGeeks
|
28 Oct, 2019
Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space.
Examples :
Input : arr = {1, 2, 3, 2, 3, 1, 3}
Output : 3
Input : arr = {5, 7, 2, 7, 5, 2, 5}
Output : 5
Python3
# Python program to find the element occurring# odd number of times # function to find the element occurring odd# number of timesdef getOddOccurrence(arr, arr_size): for i in range(0, arr_size): count = 0 for j in range(0, arr_size): if arr[i] == arr[j]: count+= 1 if (count % 2 != 0): return arr[i] return -1 # driver code arr = [2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 ]n = len(arr)print(getOddOccurrence(arr, n)) # This code has been contributed by # Smitha Dinesh Semwal
5
A Better Solution is to use Hashing. Use array elements as key and their counts as value. Create an empty hash table. One by one traverse the given array elements and store counts. Time complexity of this solution is O(n). But it requires extra space for hashing.
Program :
Python
# Python program to find the element occurring odd number of times def getOddOccurrence(arr): # Initialize result res = 0 # Traverse the array for element in arr: # XOR with the result res = res ^ element return res # Test arrayarr = [ 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2] print "% d" % getOddOccurrence(arr)
5
Please refer complete article on Find the Number Occurring Odd Number of Times for more details!
shubham_singh
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert string dictionary to dictionary
Iterate over characters of a string in Python
Python Program for factorial of a number
Python | Convert set into a list
Python | Convert a list into a tuple
Python | Check if a variable is string
Python program to add two numbers
Add a key:value pair to dictionary in Python
Appending to list in Python dictionary
Python program to find sum of elements in list
|
[
{
"code": null,
"e": 26443,
"s": 26415,
"text": "\n28 Oct, 2019"
},
{
"code": null,
"e": 26618,
"s": 26443,
"text": "Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space."
},
{
"code": null,
"e": 26629,
"s": 26618,
"text": "Examples :"
},
{
"code": null,
"e": 26725,
"s": 26629,
"text": "Input : arr = {1, 2, 3, 2, 3, 1, 3}\nOutput : 3\n\nInput : arr = {5, 7, 2, 7, 5, 2, 5}\nOutput : 5\n"
},
{
"code": null,
"e": 26733,
"s": 26725,
"text": "Python3"
},
{
"code": "# Python program to find the element occurring# odd number of times # function to find the element occurring odd# number of timesdef getOddOccurrence(arr, arr_size): for i in range(0, arr_size): count = 0 for j in range(0, arr_size): if arr[i] == arr[j]: count+= 1 if (count % 2 != 0): return arr[i] return -1 # driver code arr = [2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 ]n = len(arr)print(getOddOccurrence(arr, n)) # This code has been contributed by # Smitha Dinesh Semwal",
"e": 27317,
"s": 26733,
"text": null
},
{
"code": null,
"e": 27320,
"s": 27317,
"text": "5\n"
},
{
"code": null,
"e": 27584,
"s": 27320,
"text": "A Better Solution is to use Hashing. Use array elements as key and their counts as value. Create an empty hash table. One by one traverse the given array elements and store counts. Time complexity of this solution is O(n). But it requires extra space for hashing."
},
{
"code": null,
"e": 27594,
"s": 27584,
"text": "Program :"
},
{
"code": null,
"e": 27601,
"s": 27594,
"text": "Python"
},
{
"code": " # Python program to find the element occurring odd number of times def getOddOccurrence(arr): # Initialize result res = 0 # Traverse the array for element in arr: # XOR with the result res = res ^ element return res # Test arrayarr = [ 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2] print \"% d\" % getOddOccurrence(arr)",
"e": 27960,
"s": 27601,
"text": null
},
{
"code": null,
"e": 27963,
"s": 27960,
"text": "5\n"
},
{
"code": null,
"e": 28060,
"s": 27963,
"text": "Please refer complete article on Find the Number Occurring Odd Number of Times for more details!"
},
{
"code": null,
"e": 28074,
"s": 28060,
"text": "shubham_singh"
},
{
"code": null,
"e": 28090,
"s": 28074,
"text": "Python Programs"
},
{
"code": null,
"e": 28188,
"s": 28090,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28237,
"s": 28188,
"text": "Python | Convert string dictionary to dictionary"
},
{
"code": null,
"e": 28283,
"s": 28237,
"text": "Iterate over characters of a string in Python"
},
{
"code": null,
"e": 28324,
"s": 28283,
"text": "Python Program for factorial of a number"
},
{
"code": null,
"e": 28357,
"s": 28324,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 28394,
"s": 28357,
"text": "Python | Convert a list into a tuple"
},
{
"code": null,
"e": 28433,
"s": 28394,
"text": "Python | Check if a variable is string"
},
{
"code": null,
"e": 28467,
"s": 28433,
"text": "Python program to add two numbers"
},
{
"code": null,
"e": 28512,
"s": 28467,
"text": "Add a key:value pair to dictionary in Python"
},
{
"code": null,
"e": 28551,
"s": 28512,
"text": "Appending to list in Python dictionary"
}
] |
Arrays.sort() in Java with examples - GeeksforGeeks
|
19 Apr, 2022
An array class is a class containing static methods that are used with arrays in order to search, sort, compare, inserting elements, or returning a string representation of an array. in an array. So let us specify the functions first and later onwards we will be discussing the same. They are as follows been present in java.util.Arrays class. Here we will be discussing out different plots using the sort() method of the Arrays class.
Arrays.sort() method consists of two variations one in which we do not pass any arguments where it sort down the complete array be it integer array or character array but if we are supposed to sort a specific part using this method of Arrays class then we overload it and pass the starting and last index to the array.
Syntax: sort() Method
Arrays.sort();
Syntax: Overloaded sort() Method
public static void sort(int[] arr, int from_Index, int to_Index) ;
Parameters: It takes three parameters as can be perceived from the syntax which is as follows:
The array to be sorted
The index of the first element, inclusive, to be sorted (Referred to as from_index)
The index of the last element, exclusive, to be sorted (Referred to as last_index)
Return Type: It does not return any value.
Now let us see the implementation of the sort() function across different scenarios of the Arrays class as follows:
Example 1:
Java
// Java Program to Sort Array of Integers// by Default Sorts in an Ascending Order// using Arrays.sort() Method // Importing Arrays class from the utility classimport java.util.Arrays; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input array int[] arr = { 13, 7, 6, 45, 21, 9, 101, 102 }; // Applying sort() method over to above array // by passing the array as an argument Arrays.sort(arr); // Printing the array after sorting System.out.println("Modified arr[] : %s", Arrays.toString(arr)); }}
Output:
Modified arr[] : [6, 7, 9, 13, 21, 45, 101, 102]
Example 2:
Java
// Java program to Sort a Subarray in Array// Using Arrays.sort() method // Importing Arrays class from java.util packageimport java.util.Arrays; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input array // It contains 8 elements as follows int[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 }; // Sort subarray from index 1 to 4, i.e., // only sort subarray {7, 6, 45, 21} and // keep other elements as it is. Arrays.sort(arr, 1, 5); // Printing the updated array which is // sorted after 2 index inclusive till 5th index System.out.println("Modified arr[] : %s", Arrays.toString(arr)); }}
Output:
Modified arr[] : [13, 6, 7, 21, 45, 9, 2, 100]
Example 3:
Java
// Java program to Sort a Subarray in Descending order// Using Arrays.sort() // Importing Collections class and arrays classes// from java.util packageimport java.util.Arrays;import java.util.Collections; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Note that we have Integer here instead of // int[] as Collections.reverseOrder doesn't // work for primitive types. Integer[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 }; // Sorts arr[] in descending order using // reverseOrder() method of Collections class // in Array.sort() as an argument to it Arrays.sort(arr, Collections.reverseOrder()); // Printing the array as generated above System.out.println("Modified arr[] : %s", Arrays.toString(arr)); }}
Output:
Modified arr[] : [100, 45, 21, 13, 9, 7, 6, 2]
Example 4:
Java
// Java program to sort an array of strings// in ascending and descending alphabetical order// Using Arrays.sort() // Importing arrays and Collections class// from java.util classimport java.util.Arrays;import java.util.Collections; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input string String arr[] = { "practice.geeksforgeeks.org", "quiz.geeksforgeeks.org", "code.geeksforgeeks.org" }; // Sorts arr[] in ascending order Arrays.sort(arr); System.out.println("Modified arr[] : \n%s\n\n", Arrays.toString(arr)); // Sorts arr[] in descending order Arrays.sort(arr, Collections.reverseOrder()); // Lastly printing the above array System.out.println("Modified arr[] : \n%s\n\n", Arrays.toString(arr)); }}
Output:
Modified arr[] :
Modified arr[] :
[quiz.geeksforgeeks.org, practice.geeksforgeeks.org, code.geeksforgeeks.org]
Now lastly we will be implementing the sort() method to the fullest because here we will be declaring our own defined criteria with the help of the Comparator interface.
Example 5:
Java
// Java program to demonstrate Working of// Comparator interface // Importing required classesimport java.io.*;import java.lang.*;import java.util.*; // Class 1// A class to represent a student.class Student { int rollno; String name, address; // Constructor public Student(int rollno, String name, String address) { // This keyword refers to current object itself this.rollno = rollno; this.name = name; this.address = address; } // Used to print student details in main() public String toString() { return this.rollno + " " + this.name + " " + this.address; }} // Class 2// Helper class extending Comparator interfaceclass Sortbyroll implements Comparator<Student> { // Used for sorting in ascending order of // roll number public int compare(Student a, Student b) { return a.rollno - b.rollno; }} // Class 3// Main classclass GFG { // Main driver method public static void main(String[] args) { Student[] arr = { new Student(111, "bbbb", "london"), new Student(131, "aaaa", "nyc"), new Student(121, "cccc", "jaipur") }; System.out.println("Unsorted"); for (int i = 0; i < arr.length; i++) System.out.println(arr[i]); // Sorting on basic as per class 1 created // (user-defined) Arrays.sort(arr, new Sortbyroll()); System.out.println("\nSorted by rollno"); for (int i = 0; i < arr.length; i++) System.out.println(arr[i]); }}
Output:
Unsorted
111 bbbb london
131 aaaa nyc
121 cccc jaipur
Sorted by rollno
111 bbbb london
121 cccc jaipur
131 aaaa nyc
Note: There is a slight difference between Arrays.sort() vs Collections.sort(). Arrays.sort works for arrays which can be of primitive data type also. Collections.sort() works for objects Collections like ArrayList, LinkedList, etc.
This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Anchit Gupta
draco_malf0y
metkar9699130773
bigo(1)
solankimayank
simmytarika5
Java-Arrays
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
Singleton Class in Java
Set in Java
Multithreading in Java
Collections in Java
Queue Interface In Java
Initializing a List in Java
Overriding in Java
LinkedList in Java
|
[
{
"code": null,
"e": 25509,
"s": 25481,
"text": "\n19 Apr, 2022"
},
{
"code": null,
"e": 25945,
"s": 25509,
"text": "An array class is a class containing static methods that are used with arrays in order to search, sort, compare, inserting elements, or returning a string representation of an array. in an array. So let us specify the functions first and later onwards we will be discussing the same. They are as follows been present in java.util.Arrays class. Here we will be discussing out different plots using the sort() method of the Arrays class."
},
{
"code": null,
"e": 26264,
"s": 25945,
"text": "Arrays.sort() method consists of two variations one in which we do not pass any arguments where it sort down the complete array be it integer array or character array but if we are supposed to sort a specific part using this method of Arrays class then we overload it and pass the starting and last index to the array."
},
{
"code": null,
"e": 26287,
"s": 26264,
"text": "Syntax: sort() Method "
},
{
"code": null,
"e": 26303,
"s": 26287,
"text": "Arrays.sort(); "
},
{
"code": null,
"e": 26336,
"s": 26303,
"text": "Syntax: Overloaded sort() Method"
},
{
"code": null,
"e": 26403,
"s": 26336,
"text": "public static void sort(int[] arr, int from_Index, int to_Index) ;"
},
{
"code": null,
"e": 26498,
"s": 26403,
"text": "Parameters: It takes three parameters as can be perceived from the syntax which is as follows:"
},
{
"code": null,
"e": 26521,
"s": 26498,
"text": "The array to be sorted"
},
{
"code": null,
"e": 26605,
"s": 26521,
"text": "The index of the first element, inclusive, to be sorted (Referred to as from_index)"
},
{
"code": null,
"e": 26688,
"s": 26605,
"text": "The index of the last element, exclusive, to be sorted (Referred to as last_index)"
},
{
"code": null,
"e": 26731,
"s": 26688,
"text": "Return Type: It does not return any value."
},
{
"code": null,
"e": 26847,
"s": 26731,
"text": "Now let us see the implementation of the sort() function across different scenarios of the Arrays class as follows:"
},
{
"code": null,
"e": 26858,
"s": 26847,
"text": "Example 1:"
},
{
"code": null,
"e": 26863,
"s": 26858,
"text": "Java"
},
{
"code": "// Java Program to Sort Array of Integers// by Default Sorts in an Ascending Order// using Arrays.sort() Method // Importing Arrays class from the utility classimport java.util.Arrays; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input array int[] arr = { 13, 7, 6, 45, 21, 9, 101, 102 }; // Applying sort() method over to above array // by passing the array as an argument Arrays.sort(arr); // Printing the array after sorting System.out.println(\"Modified arr[] : %s\", Arrays.toString(arr)); }}",
"e": 27509,
"s": 26863,
"text": null
},
{
"code": null,
"e": 27520,
"s": 27509,
"text": " Output: "
},
{
"code": null,
"e": 27569,
"s": 27520,
"text": "Modified arr[] : [6, 7, 9, 13, 21, 45, 101, 102]"
},
{
"code": null,
"e": 27580,
"s": 27569,
"text": "Example 2:"
},
{
"code": null,
"e": 27585,
"s": 27580,
"text": "Java"
},
{
"code": "// Java program to Sort a Subarray in Array// Using Arrays.sort() method // Importing Arrays class from java.util packageimport java.util.Arrays; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input array // It contains 8 elements as follows int[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 }; // Sort subarray from index 1 to 4, i.e., // only sort subarray {7, 6, 45, 21} and // keep other elements as it is. Arrays.sort(arr, 1, 5); // Printing the updated array which is // sorted after 2 index inclusive till 5th index System.out.println(\"Modified arr[] : %s\", Arrays.toString(arr)); }}",
"e": 28337,
"s": 27585,
"text": null
},
{
"code": null,
"e": 28348,
"s": 28337,
"text": " Output: "
},
{
"code": null,
"e": 28395,
"s": 28348,
"text": "Modified arr[] : [13, 6, 7, 21, 45, 9, 2, 100]"
},
{
"code": null,
"e": 28406,
"s": 28395,
"text": "Example 3:"
},
{
"code": null,
"e": 28411,
"s": 28406,
"text": "Java"
},
{
"code": "// Java program to Sort a Subarray in Descending order// Using Arrays.sort() // Importing Collections class and arrays classes// from java.util packageimport java.util.Arrays;import java.util.Collections; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Note that we have Integer here instead of // int[] as Collections.reverseOrder doesn't // work for primitive types. Integer[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 }; // Sorts arr[] in descending order using // reverseOrder() method of Collections class // in Array.sort() as an argument to it Arrays.sort(arr, Collections.reverseOrder()); // Printing the array as generated above System.out.println(\"Modified arr[] : %s\", Arrays.toString(arr)); }}",
"e": 29274,
"s": 28411,
"text": null
},
{
"code": null,
"e": 29284,
"s": 29274,
"text": " Output: "
},
{
"code": null,
"e": 29331,
"s": 29284,
"text": "Modified arr[] : [100, 45, 21, 13, 9, 7, 6, 2]"
},
{
"code": null,
"e": 29342,
"s": 29331,
"text": "Example 4:"
},
{
"code": null,
"e": 29347,
"s": 29342,
"text": "Java"
},
{
"code": "// Java program to sort an array of strings// in ascending and descending alphabetical order// Using Arrays.sort() // Importing arrays and Collections class// from java.util classimport java.util.Arrays;import java.util.Collections; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input string String arr[] = { \"practice.geeksforgeeks.org\", \"quiz.geeksforgeeks.org\", \"code.geeksforgeeks.org\" }; // Sorts arr[] in ascending order Arrays.sort(arr); System.out.println(\"Modified arr[] : \\n%s\\n\\n\", Arrays.toString(arr)); // Sorts arr[] in descending order Arrays.sort(arr, Collections.reverseOrder()); // Lastly printing the above array System.out.println(\"Modified arr[] : \\n%s\\n\\n\", Arrays.toString(arr)); }}",
"e": 30293,
"s": 29347,
"text": null
},
{
"code": null,
"e": 30302,
"s": 30293,
"text": "Output: "
},
{
"code": null,
"e": 30417,
"s": 30302,
"text": "Modified arr[] : \n\n\nModified arr[] : \n[quiz.geeksforgeeks.org, practice.geeksforgeeks.org, code.geeksforgeeks.org]"
},
{
"code": null,
"e": 30587,
"s": 30417,
"text": "Now lastly we will be implementing the sort() method to the fullest because here we will be declaring our own defined criteria with the help of the Comparator interface."
},
{
"code": null,
"e": 30598,
"s": 30587,
"text": "Example 5:"
},
{
"code": null,
"e": 30603,
"s": 30598,
"text": "Java"
},
{
"code": "// Java program to demonstrate Working of// Comparator interface // Importing required classesimport java.io.*;import java.lang.*;import java.util.*; // Class 1// A class to represent a student.class Student { int rollno; String name, address; // Constructor public Student(int rollno, String name, String address) { // This keyword refers to current object itself this.rollno = rollno; this.name = name; this.address = address; } // Used to print student details in main() public String toString() { return this.rollno + \" \" + this.name + \" \" + this.address; }} // Class 2// Helper class extending Comparator interfaceclass Sortbyroll implements Comparator<Student> { // Used for sorting in ascending order of // roll number public int compare(Student a, Student b) { return a.rollno - b.rollno; }} // Class 3// Main classclass GFG { // Main driver method public static void main(String[] args) { Student[] arr = { new Student(111, \"bbbb\", \"london\"), new Student(131, \"aaaa\", \"nyc\"), new Student(121, \"cccc\", \"jaipur\") }; System.out.println(\"Unsorted\"); for (int i = 0; i < arr.length; i++) System.out.println(arr[i]); // Sorting on basic as per class 1 created // (user-defined) Arrays.sort(arr, new Sortbyroll()); System.out.println(\"\\nSorted by rollno\"); for (int i = 0; i < arr.length; i++) System.out.println(arr[i]); }}",
"e": 32167,
"s": 30603,
"text": null
},
{
"code": null,
"e": 32177,
"s": 32167,
"text": " Output: "
},
{
"code": null,
"e": 32294,
"s": 32177,
"text": "Unsorted\n111 bbbb london\n131 aaaa nyc\n121 cccc jaipur\n\nSorted by rollno\n111 bbbb london\n121 cccc jaipur\n131 aaaa nyc"
},
{
"code": null,
"e": 32528,
"s": 32294,
"text": "Note: There is a slight difference between Arrays.sort() vs Collections.sort(). Arrays.sort works for arrays which can be of primitive data type also. Collections.sort() works for objects Collections like ArrayList, LinkedList, etc. "
},
{
"code": null,
"e": 32823,
"s": 32528,
"text": "This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 32836,
"s": 32823,
"text": "Anchit Gupta"
},
{
"code": null,
"e": 32849,
"s": 32836,
"text": "draco_malf0y"
},
{
"code": null,
"e": 32866,
"s": 32849,
"text": "metkar9699130773"
},
{
"code": null,
"e": 32874,
"s": 32866,
"text": "bigo(1)"
},
{
"code": null,
"e": 32888,
"s": 32874,
"text": "solankimayank"
},
{
"code": null,
"e": 32901,
"s": 32888,
"text": "simmytarika5"
},
{
"code": null,
"e": 32913,
"s": 32901,
"text": "Java-Arrays"
},
{
"code": null,
"e": 32928,
"s": 32913,
"text": "Java-Functions"
},
{
"code": null,
"e": 32933,
"s": 32928,
"text": "Java"
},
{
"code": null,
"e": 32938,
"s": 32933,
"text": "Java"
},
{
"code": null,
"e": 33036,
"s": 32938,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33051,
"s": 33036,
"text": "Stream In Java"
},
{
"code": null,
"e": 33070,
"s": 33051,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 33094,
"s": 33070,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 33106,
"s": 33094,
"text": "Set in Java"
},
{
"code": null,
"e": 33129,
"s": 33106,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 33149,
"s": 33129,
"text": "Collections in Java"
},
{
"code": null,
"e": 33173,
"s": 33149,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 33201,
"s": 33173,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 33220,
"s": 33201,
"text": "Overriding in Java"
}
] |
Program to Find the Incenter of a Triangle - GeeksforGeeks
|
10 Mar, 2022
Given the vertices of a triangle and length of its sides. A circle is inscribed in a triangle. The task is to find the incenter of a triangle.Examples:
Input: A(2, 2), B(1, 1), C(3, 1)
and AB = 2, BC = 1, AC = 1
Output: (2, 1.5)
Input: A(3, 3), B(1, 2), C(2, 2)
and AB = 3, BC = 2, AC = 2
Output: (2.5, 2.83)
Approach:
The center of the circle that touches the sides of a triangle is called its incenter.
Suppose the vertices of the triangle are A(x1, y1), B(x2, y2) and C(x3, y3).
Let the side AB = a, BC = b, AC = c then the coordinates of the in-center is given by the formula:
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the// incenter of a triangle#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ // coordinate of the vertices float x1 = 2, x2 = 1, x3 = 3; float y1 = 2, y2 = 1, y3 = 1; float a = 2, b = 1, c = 1; // Formula to calculate in-center float x = (a * x1 + b * x2 + c * x3) / (a + b + c); float y = (a * y1 + b * y2 + c * y3) / (a + b + c); // System.out.print(setprecision(3)); cout << "Incenter = " << "(" << x << ", " << y << ")"; return 0;} // This code is contributed by 29AjayKumar
// Java program to find the// incenter of a triangle import java.util.*;import java.lang.*; class GFG { // Driver code public static void main(String args[]) { // coordinate of the vertices float x1 = 2, x2 = 1, x3 = 3; float y1 = 2, y2 = 1, y3 = 1; float a = 2, b = 1, c = 1; // Formula to calculate in-center float x = (a * x1 + b * x2 + c * x3) / (a + b + c); float y = (a * y1 + b * y2 + c * y3) / (a + b + c); // System.out.print(setprecision(3)); System.out.println("Incenter= " + "(" + x + ", " + y + ")"); }}
# Python3 program to find the# incenter of a triangle # Driver code # coordinate of the verticesx1 = 2; x2 = 1; x3 = 3;y1 = 2; y2 = 1; y3 = 1;a = 2; b = 1; c = 1; # Formula to calculate in-centerx = (a * x1 + b * x2 + c * x3) / (a + b + c);y = (a * y1 + b * y2 + c * y3) / (a + b + c); # System.out.print(setprecision(3));print("Incenter = (", x, ",", y, ")"); # This code is contributed# by Akanksha Rai
// C# program to find the// incenter of a triangle using System; class GFG{ // Driver code public static void Main() { // coordinate of the vertices float x1 = 2, x2 = 1, x3 = 3; float y1 = 2, y2 = 1, y3 = 1; float a = 2, b = 1, c = 1; // Formula to calculate in-center float x = (a * x1 + b * x2 + c * x3) / (a + b + c); float y = (a * y1 + b * y2 + c * y3) / (a + b + c); // System.out.print(setprecision(3)); Console.WriteLine("Incenter= " + "(" + x + ", " + y + ")"); }} // This code is contributed by vt_m.
<script> // JavaScript program to find the // incenter of a triangle // Driver code // coordinate of the vertices var x1 = 2, x2 = 1, x3 = 3; var y1 = 2, y2 = 1, y3 = 1; var a = 2, b = 1, c = 1; // Formula to calculate in-center var x = (a * x1 + b * x2 + c * x3) / (a + b + c); var y = (a * y1 + b * y2 + c * y3) / (a + b + c); document.write( "Incenter = " + "(" + x.toFixed(1) + ", " + y.toFixed(1) + ")" ); </script>
Incenter= (2.0, 1.5)
vt_m
29AjayKumar
Akanksha_Rai
rdtank
ManasChhabra2
triangle
Geometric
Java
Mathematical
Mathematical
Java
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Convex Hull | Set 2 (Graham Scan)
Check whether a given point lies inside a triangle or not
Optimum location of point to minimize total distance
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples
|
[
{
"code": null,
"e": 26305,
"s": 26277,
"text": "\n10 Mar, 2022"
},
{
"code": null,
"e": 26459,
"s": 26305,
"text": "Given the vertices of a triangle and length of its sides. A circle is inscribed in a triangle. The task is to find the incenter of a triangle.Examples: "
},
{
"code": null,
"e": 26635,
"s": 26459,
"text": "Input: A(2, 2), B(1, 1), C(3, 1) \n and AB = 2, BC = 1, AC = 1\nOutput: (2, 1.5)\n\nInput: A(3, 3), B(1, 2), C(2, 2) \n and AB = 3, BC = 2, AC = 2\nOutput: (2.5, 2.83)"
},
{
"code": null,
"e": 26651,
"s": 26639,
"text": "Approach: "
},
{
"code": null,
"e": 26737,
"s": 26651,
"text": "The center of the circle that touches the sides of a triangle is called its incenter."
},
{
"code": null,
"e": 26814,
"s": 26737,
"text": "Suppose the vertices of the triangle are A(x1, y1), B(x2, y2) and C(x3, y3)."
},
{
"code": null,
"e": 26914,
"s": 26814,
"text": "Let the side AB = a, BC = b, AC = c then the coordinates of the in-center is given by the formula: "
},
{
"code": null,
"e": 26971,
"s": 26918,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26975,
"s": 26971,
"text": "C++"
},
{
"code": null,
"e": 26980,
"s": 26975,
"text": "Java"
},
{
"code": null,
"e": 26988,
"s": 26980,
"text": "Python3"
},
{
"code": null,
"e": 26991,
"s": 26988,
"text": "C#"
},
{
"code": null,
"e": 27002,
"s": 26991,
"text": "Javascript"
},
{
"code": "// C++ program to find the// incenter of a triangle#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ // coordinate of the vertices float x1 = 2, x2 = 1, x3 = 3; float y1 = 2, y2 = 1, y3 = 1; float a = 2, b = 1, c = 1; // Formula to calculate in-center float x = (a * x1 + b * x2 + c * x3) / (a + b + c); float y = (a * y1 + b * y2 + c * y3) / (a + b + c); // System.out.print(setprecision(3)); cout << \"Incenter = \" << \"(\" << x << \", \" << y << \")\"; return 0;} // This code is contributed by 29AjayKumar",
"e": 27602,
"s": 27002,
"text": null
},
{
"code": "// Java program to find the// incenter of a triangle import java.util.*;import java.lang.*; class GFG { // Driver code public static void main(String args[]) { // coordinate of the vertices float x1 = 2, x2 = 1, x3 = 3; float y1 = 2, y2 = 1, y3 = 1; float a = 2, b = 1, c = 1; // Formula to calculate in-center float x = (a * x1 + b * x2 + c * x3) / (a + b + c); float y = (a * y1 + b * y2 + c * y3) / (a + b + c); // System.out.print(setprecision(3)); System.out.println(\"Incenter= \" + \"(\" + x + \", \" + y + \")\"); }}",
"e": 28245,
"s": 27602,
"text": null
},
{
"code": "# Python3 program to find the# incenter of a triangle # Driver code # coordinate of the verticesx1 = 2; x2 = 1; x3 = 3;y1 = 2; y2 = 1; y3 = 1;a = 2; b = 1; c = 1; # Formula to calculate in-centerx = (a * x1 + b * x2 + c * x3) / (a + b + c);y = (a * y1 + b * y2 + c * y3) / (a + b + c); # System.out.print(setprecision(3));print(\"Incenter = (\", x, \",\", y, \")\"); # This code is contributed# by Akanksha Rai",
"e": 28650,
"s": 28245,
"text": null
},
{
"code": "// C# program to find the// incenter of a triangle using System; class GFG{ // Driver code public static void Main() { // coordinate of the vertices float x1 = 2, x2 = 1, x3 = 3; float y1 = 2, y2 = 1, y3 = 1; float a = 2, b = 1, c = 1; // Formula to calculate in-center float x = (a * x1 + b * x2 + c * x3) / (a + b + c); float y = (a * y1 + b * y2 + c * y3) / (a + b + c); // System.out.print(setprecision(3)); Console.WriteLine(\"Incenter= \" + \"(\" + x + \", \" + y + \")\"); }} // This code is contributed by vt_m.",
"e": 29285,
"s": 28650,
"text": null
},
{
"code": "<script> // JavaScript program to find the // incenter of a triangle // Driver code // coordinate of the vertices var x1 = 2, x2 = 1, x3 = 3; var y1 = 2, y2 = 1, y3 = 1; var a = 2, b = 1, c = 1; // Formula to calculate in-center var x = (a * x1 + b * x2 + c * x3) / (a + b + c); var y = (a * y1 + b * y2 + c * y3) / (a + b + c); document.write( \"Incenter = \" + \"(\" + x.toFixed(1) + \", \" + y.toFixed(1) + \")\" ); </script>",
"e": 29820,
"s": 29285,
"text": null
},
{
"code": null,
"e": 29841,
"s": 29820,
"text": "Incenter= (2.0, 1.5)"
},
{
"code": null,
"e": 29848,
"s": 29843,
"text": "vt_m"
},
{
"code": null,
"e": 29860,
"s": 29848,
"text": "29AjayKumar"
},
{
"code": null,
"e": 29873,
"s": 29860,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 29880,
"s": 29873,
"text": "rdtank"
},
{
"code": null,
"e": 29894,
"s": 29880,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 29903,
"s": 29894,
"text": "triangle"
},
{
"code": null,
"e": 29913,
"s": 29903,
"text": "Geometric"
},
{
"code": null,
"e": 29918,
"s": 29913,
"text": "Java"
},
{
"code": null,
"e": 29931,
"s": 29918,
"text": "Mathematical"
},
{
"code": null,
"e": 29944,
"s": 29931,
"text": "Mathematical"
},
{
"code": null,
"e": 29949,
"s": 29944,
"text": "Java"
},
{
"code": null,
"e": 29959,
"s": 29949,
"text": "Geometric"
},
{
"code": null,
"e": 30057,
"s": 29959,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30110,
"s": 30057,
"text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)"
},
{
"code": null,
"e": 30161,
"s": 30110,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 30195,
"s": 30161,
"text": "Convex Hull | Set 2 (Graham Scan)"
},
{
"code": null,
"e": 30253,
"s": 30195,
"text": "Check whether a given point lies inside a triangle or not"
},
{
"code": null,
"e": 30306,
"s": 30253,
"text": "Optimum location of point to minimize total distance"
},
{
"code": null,
"e": 30321,
"s": 30306,
"text": "Arrays in Java"
},
{
"code": null,
"e": 30365,
"s": 30321,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 30387,
"s": 30365,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 30438,
"s": 30387,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
C Program For Deleting A Node In A Linked List - GeeksforGeeks
|
26 Dec, 2021
We have discussed Linked List Introduction and Linked List Insertion in previous posts on a singly linked list.Let us formulate the problem statement to understand the deletion process. Given a ‘key’, delete the first occurrence of this key in the linked list.
Iterative Method:To delete a node from the linked list, we need to do the following steps. 1) Find the previous node of the node to be deleted. 2) Change the next of the previous node. 3) Free memory for the node to be deleted.
Since every node of the linked list is dynamically allocated using malloc() in C, we need to call free() for freeing memory allocated for the node to be deleted.
C
// A complete working C program// to demonstrate deletion in// singly linked list#include <stdio.h>#include <stdlib.h> // A linked list nodestruct Node { int data; struct Node* next;}; /* Given a reference (pointer to pointer) to the head of a list and an int, inserts a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} /* Given a reference (pointer to pointer) to the head of a list and a key, deletes the first occurrence of key in linked list */void deleteNode(struct Node** head_ref, int key){ // Store head node struct Node *temp = *head_ref, *prev; // If head node itself holds the key to be deleted if (temp != NULL && temp->data == key) { *head_ref = temp->next; // Changed head free(temp); // free old head return; } // Search for the key to be deleted, keep track of the // previous node as we need to change 'prev->next' while (temp != NULL && temp->data != key) { prev = temp; temp = temp->next; } // If key was not present in linked list if (temp == NULL) return; // Unlink the node from linked list prev->next = temp->next; free(temp); // Free memory} // This function prints contents of linked list starting// from the given nodevoid printList(struct Node* node){ while (node != NULL) { printf(" %d ", node->data); node = node->next; }} // Driver codeint main(){ /* Start with the empty list */ struct Node* head = NULL; push(&head, 7); push(&head, 1); push(&head, 3); push(&head, 2); puts("Created Linked List: "); printList(head); deleteNode(&head, 1); puts("Linked List after Deletion of 1: "); printList(head); return 0;}
Created Linked List:
2 3 1 7
Linked List after Deletion of 1:
2 3 7
Please refer complete article on Linked List | Set 3 (Deleting a node) for more details!
C-programming
Linked Lists
C Language
C Programs
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Strings in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
Header files in C/C++ and its uses
Basics of File Handling in C
|
[
{
"code": null,
"e": 25531,
"s": 25503,
"text": "\n26 Dec, 2021"
},
{
"code": null,
"e": 25793,
"s": 25531,
"text": "We have discussed Linked List Introduction and Linked List Insertion in previous posts on a singly linked list.Let us formulate the problem statement to understand the deletion process. Given a ‘key’, delete the first occurrence of this key in the linked list. "
},
{
"code": null,
"e": 26022,
"s": 25793,
"text": "Iterative Method:To delete a node from the linked list, we need to do the following steps. 1) Find the previous node of the node to be deleted. 2) Change the next of the previous node. 3) Free memory for the node to be deleted. "
},
{
"code": null,
"e": 26184,
"s": 26022,
"text": "Since every node of the linked list is dynamically allocated using malloc() in C, we need to call free() for freeing memory allocated for the node to be deleted."
},
{
"code": null,
"e": 26186,
"s": 26184,
"text": "C"
},
{
"code": "// A complete working C program// to demonstrate deletion in// singly linked list#include <stdio.h>#include <stdlib.h> // A linked list nodestruct Node { int data; struct Node* next;}; /* Given a reference (pointer to pointer) to the head of a list and an int, inserts a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} /* Given a reference (pointer to pointer) to the head of a list and a key, deletes the first occurrence of key in linked list */void deleteNode(struct Node** head_ref, int key){ // Store head node struct Node *temp = *head_ref, *prev; // If head node itself holds the key to be deleted if (temp != NULL && temp->data == key) { *head_ref = temp->next; // Changed head free(temp); // free old head return; } // Search for the key to be deleted, keep track of the // previous node as we need to change 'prev->next' while (temp != NULL && temp->data != key) { prev = temp; temp = temp->next; } // If key was not present in linked list if (temp == NULL) return; // Unlink the node from linked list prev->next = temp->next; free(temp); // Free memory} // This function prints contents of linked list starting// from the given nodevoid printList(struct Node* node){ while (node != NULL) { printf(\" %d \", node->data); node = node->next; }} // Driver codeint main(){ /* Start with the empty list */ struct Node* head = NULL; push(&head, 7); push(&head, 1); push(&head, 3); push(&head, 2); puts(\"Created Linked List: \"); printList(head); deleteNode(&head, 1); puts(\"Linked List after Deletion of 1: \"); printList(head); return 0;}",
"e": 28105,
"s": 26186,
"text": null
},
{
"code": null,
"e": 28183,
"s": 28105,
"text": "Created Linked List: \n 2 3 1 7 \nLinked List after Deletion of 1: \n 2 3 7"
},
{
"code": null,
"e": 28272,
"s": 28183,
"text": "Please refer complete article on Linked List | Set 3 (Deleting a node) for more details!"
},
{
"code": null,
"e": 28286,
"s": 28272,
"text": "C-programming"
},
{
"code": null,
"e": 28299,
"s": 28286,
"text": "Linked Lists"
},
{
"code": null,
"e": 28310,
"s": 28299,
"text": "C Language"
},
{
"code": null,
"e": 28321,
"s": 28310,
"text": "C Programs"
},
{
"code": null,
"e": 28333,
"s": 28321,
"text": "Linked List"
},
{
"code": null,
"e": 28345,
"s": 28333,
"text": "Linked List"
},
{
"code": null,
"e": 28443,
"s": 28345,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28481,
"s": 28443,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 28507,
"s": 28481,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 28527,
"s": 28507,
"text": "Multithreading in C"
},
{
"code": null,
"e": 28549,
"s": 28527,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 28590,
"s": 28549,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 28603,
"s": 28590,
"text": "Strings in C"
},
{
"code": null,
"e": 28644,
"s": 28603,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 28685,
"s": 28644,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 28720,
"s": 28685,
"text": "Header files in C/C++ and its uses"
}
] |
Flutter - Splitting App into Widgets - GeeksforGeeks
|
15 Jan, 2021
Splitting an app into widgets refers to the breaking up of large widgets into smaller, more manageable widgets which can be inferred as smaller chunks of codes. The principal thing here is to understand when to split a widget into smaller ones. We are going to discuss when to split a widget and methods of how to perform this.
Large Widget: Whenever we have a large widget with many nested widgets and other smaller widgets inside of it. It is advisable to split the large widgets into smaller widgets that can be managed easily.
Repeating Widgets: Sometimes we have a situation where we create some custom widget (e.g. custom Button) which we might use at many places, then also it is a good practice to split the piece of code into a separate widget. This helps us clean up extra lines of code and manage the changes to the widget in one place.
Complex Widget: There are situations when the widget might not be too large, but because of the implementation it becomes complex so to implement the complex parts separately for better understanding we might split the codes into different widgets.
1. Using Flutter Outline:
Use the Flutter Outline tool to split an app into widgets as shown below:
Flutter Outline is present on the right-hand side as a hidden tab. After opening the tab we can see the Widget Tree of the current dart file. Right-click on the widget we want to extract -> click on Extract Widget.
Flutter Outline and Widget Tree
Give a name for the widget->Click Refactor. The widget will be extracted. We can also place the widget in another file (we have to import it if we keep it in a new file).
Extract and refactor
This will extract the widgets from the app as shown below:
Extracted Widgets
2. By Right Clicking on Widget:
Follow the below shortcut to quickly refactor the widgets in the application.
By Right-Clicking on the Particular widget -> Refactor -> Extract Flutter Widget (we can also use shortcut Ctrl+Alt+W)
Click on Extract Flutter Widget..
Give it a name and then click on refactor.
Give a name and Click on Refactor
Example :
Here is an example of a Basic Calculator app that takes two numbers as input from the user and produces an output as the user clicks on any of the addition, subtraction, etc. buttons. There is only one dart file i.e. main.dart in this example.
Dart
import 'package:flutter/cupertino.dart';import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'GeeksforGeeks', theme: ThemeData( primarySwatch: Colors.green, ), home: Home(), ); }} class Home extends StatefulWidget { @override _HomeState createState() => _HomeState();} class _HomeState extends State<Home> { double n1, n2, op = 0; // 1st Number, 2nd Number and Output. @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), ), body: Container( padding: EdgeInsets.all(18), child: Column( children: [ Text( 'Simple Calculator', style: TextStyle(fontSize: 24), ), SizedBox( height: 15, ), Row( children: [ CustomTextField( hint: '1st Number', onChanged: (s) { n1 = double.parse(s); print(n1); }), SizedBox(width: 10), CustomTextField( hint: '2nd Number', onChanged: (s) { n2 = double.parse(s); print(n2); }) ], ), SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ CustomButton( symbol: '+', onTap: () { setState(() { op = (n1 + n2); }); }), CustomButton( symbol: '-', onTap: () { setState(() { op = (n1 - n2); }); }), CustomButton( symbol: '×', onTap: () { setState(() { op = (n1 * n2); }); }), CustomButton( symbol: '÷', onTap: () { setState(() { if (n2 == 0) op = -1; else op = (n1 / n2).toDouble(); }); }), ], ), SizedBox(height: 10), Text( 'Output', style: TextStyle(fontSize: 18), ), SizedBox(height: 5), Container( padding: EdgeInsets.all(10), width: double.infinity, height: 50, decoration: BoxDecoration( color: Colors.black12, borderRadius: BorderRadius.circular(18)), child: Center( child: Text( op.toStringAsFixed(2), style: TextStyle(fontSize: 24), ), ), ) ], ), ), ); }}
The above lines show the main screen of the app. It comprises several in-built widgets and several custom widgets (made from in-built widgets). These widgets are below the Home widget.
The First Custom Widget is the Custom TextField which is extracted using the above methods and some fields are added in the constructor for better usage and less code.
Dart
// This is a Custom TextField Widgetclass CustomTextField extends StatelessWidget { // In the Constructor onChanged and hint fields are added. const CustomTextField({Key key, this.onChanged, this.hint}) : super(key: key); // It requires the onChanged Function // and the hint to be Shown final Function onChanged; final String hint; @override Widget build(BuildContext context) { return Expanded( child: TextField( // onChanged Function is used here. onChanged: onChanged, style: TextStyle(fontSize: 18), decoration: InputDecoration( contentPadding: EdgeInsets.symmetric(horizontal: 20), filled: true, fillColor: Colors.black12, border: OutlineInputBorder( borderSide: BorderSide.none, borderRadius: BorderRadius.circular(18)), // hint String is used here. hintText: hint, helperText: 'Keep it Short'), ), ); }}
The Second Custom Widget Used here is Custom Button which is made using the Gesture Detector.
Dart
//This is a Custom Button Widget.class CustomButton extends StatelessWidget { // In the Constructor onTap and Symbol fields are added. const CustomButton({Key key, this.onTap, this.symbol}) : super(key: key); // It Requires 2 fields Symbol(to be displayed) // and onTap Function final String symbol; final Function onTap; @override Widget build(BuildContext context) { return GestureDetector( // The onTap Field is used here. onTap: onTap, child: Container( height: 60, width: 60, decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.blueGrey, ), child: Center( child: Text( // The Symbol is used here symbol, style: TextStyle( fontSize: 35, fontWeight: FontWeight.bold, color: Colors.white, ), ), ), ), ); }}
Output:
Results obtained by tapping different buttons.
android
Flutter
Flutter-widgets
Picked
Dart
Flutter
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 - Flexible Widget
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter Tutorial
Flutter - Checkbox Widget
Flutter - Flexible Widget
|
[
{
"code": null,
"e": 25489,
"s": 25461,
"text": "\n15 Jan, 2021"
},
{
"code": null,
"e": 25817,
"s": 25489,
"text": "Splitting an app into widgets refers to the breaking up of large widgets into smaller, more manageable widgets which can be inferred as smaller chunks of codes. The principal thing here is to understand when to split a widget into smaller ones. We are going to discuss when to split a widget and methods of how to perform this."
},
{
"code": null,
"e": 26020,
"s": 25817,
"text": "Large Widget: Whenever we have a large widget with many nested widgets and other smaller widgets inside of it. It is advisable to split the large widgets into smaller widgets that can be managed easily."
},
{
"code": null,
"e": 26337,
"s": 26020,
"text": "Repeating Widgets: Sometimes we have a situation where we create some custom widget (e.g. custom Button) which we might use at many places, then also it is a good practice to split the piece of code into a separate widget. This helps us clean up extra lines of code and manage the changes to the widget in one place."
},
{
"code": null,
"e": 26586,
"s": 26337,
"text": "Complex Widget: There are situations when the widget might not be too large, but because of the implementation it becomes complex so to implement the complex parts separately for better understanding we might split the codes into different widgets."
},
{
"code": null,
"e": 26612,
"s": 26586,
"text": "1. Using Flutter Outline:"
},
{
"code": null,
"e": 26686,
"s": 26612,
"text": "Use the Flutter Outline tool to split an app into widgets as shown below:"
},
{
"code": null,
"e": 26902,
"s": 26686,
"text": " Flutter Outline is present on the right-hand side as a hidden tab. After opening the tab we can see the Widget Tree of the current dart file. Right-click on the widget we want to extract -> click on Extract Widget."
},
{
"code": null,
"e": 26934,
"s": 26902,
"text": "Flutter Outline and Widget Tree"
},
{
"code": null,
"e": 27105,
"s": 26934,
"text": "Give a name for the widget->Click Refactor. The widget will be extracted. We can also place the widget in another file (we have to import it if we keep it in a new file)."
},
{
"code": null,
"e": 27126,
"s": 27105,
"text": "Extract and refactor"
},
{
"code": null,
"e": 27185,
"s": 27126,
"text": "This will extract the widgets from the app as shown below:"
},
{
"code": null,
"e": 27203,
"s": 27185,
"text": "Extracted Widgets"
},
{
"code": null,
"e": 27235,
"s": 27203,
"text": "2. By Right Clicking on Widget:"
},
{
"code": null,
"e": 27313,
"s": 27235,
"text": "Follow the below shortcut to quickly refactor the widgets in the application."
},
{
"code": null,
"e": 27433,
"s": 27313,
"text": " By Right-Clicking on the Particular widget -> Refactor -> Extract Flutter Widget (we can also use shortcut Ctrl+Alt+W)"
},
{
"code": null,
"e": 27467,
"s": 27433,
"text": "Click on Extract Flutter Widget.."
},
{
"code": null,
"e": 27511,
"s": 27467,
"text": " Give it a name and then click on refactor."
},
{
"code": null,
"e": 27545,
"s": 27511,
"text": "Give a name and Click on Refactor"
},
{
"code": null,
"e": 27556,
"s": 27545,
"text": "Example : "
},
{
"code": null,
"e": 27800,
"s": 27556,
"text": "Here is an example of a Basic Calculator app that takes two numbers as input from the user and produces an output as the user clicks on any of the addition, subtraction, etc. buttons. There is only one dart file i.e. main.dart in this example."
},
{
"code": null,
"e": 27805,
"s": 27800,
"text": "Dart"
},
{
"code": "import 'package:flutter/cupertino.dart';import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'GeeksforGeeks', theme: ThemeData( primarySwatch: Colors.green, ), home: Home(), ); }} class Home extends StatefulWidget { @override _HomeState createState() => _HomeState();} class _HomeState extends State<Home> { double n1, n2, op = 0; // 1st Number, 2nd Number and Output. @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), ), body: Container( padding: EdgeInsets.all(18), child: Column( children: [ Text( 'Simple Calculator', style: TextStyle(fontSize: 24), ), SizedBox( height: 15, ), Row( children: [ CustomTextField( hint: '1st Number', onChanged: (s) { n1 = double.parse(s); print(n1); }), SizedBox(width: 10), CustomTextField( hint: '2nd Number', onChanged: (s) { n2 = double.parse(s); print(n2); }) ], ), SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ CustomButton( symbol: '+', onTap: () { setState(() { op = (n1 + n2); }); }), CustomButton( symbol: '-', onTap: () { setState(() { op = (n1 - n2); }); }), CustomButton( symbol: '×', onTap: () { setState(() { op = (n1 * n2); }); }), CustomButton( symbol: '÷', onTap: () { setState(() { if (n2 == 0) op = -1; else op = (n1 / n2).toDouble(); }); }), ], ), SizedBox(height: 10), Text( 'Output', style: TextStyle(fontSize: 18), ), SizedBox(height: 5), Container( padding: EdgeInsets.all(10), width: double.infinity, height: 50, decoration: BoxDecoration( color: Colors.black12, borderRadius: BorderRadius.circular(18)), child: Center( child: Text( op.toStringAsFixed(2), style: TextStyle(fontSize: 24), ), ), ) ], ), ), ); }}",
"e": 31106,
"s": 27805,
"text": null
},
{
"code": null,
"e": 31291,
"s": 31106,
"text": "The above lines show the main screen of the app. It comprises several in-built widgets and several custom widgets (made from in-built widgets). These widgets are below the Home widget."
},
{
"code": null,
"e": 31460,
"s": 31291,
"text": "The First Custom Widget is the Custom TextField which is extracted using the above methods and some fields are added in the constructor for better usage and less code. "
},
{
"code": null,
"e": 31465,
"s": 31460,
"text": "Dart"
},
{
"code": "// This is a Custom TextField Widgetclass CustomTextField extends StatelessWidget { // In the Constructor onChanged and hint fields are added. const CustomTextField({Key key, this.onChanged, this.hint}) : super(key: key); // It requires the onChanged Function // and the hint to be Shown final Function onChanged; final String hint; @override Widget build(BuildContext context) { return Expanded( child: TextField( // onChanged Function is used here. onChanged: onChanged, style: TextStyle(fontSize: 18), decoration: InputDecoration( contentPadding: EdgeInsets.symmetric(horizontal: 20), filled: true, fillColor: Colors.black12, border: OutlineInputBorder( borderSide: BorderSide.none, borderRadius: BorderRadius.circular(18)), // hint String is used here. hintText: hint, helperText: 'Keep it Short'), ), ); }}",
"e": 32471,
"s": 31465,
"text": null
},
{
"code": null,
"e": 32565,
"s": 32471,
"text": "The Second Custom Widget Used here is Custom Button which is made using the Gesture Detector."
},
{
"code": null,
"e": 32570,
"s": 32565,
"text": "Dart"
},
{
"code": "//This is a Custom Button Widget.class CustomButton extends StatelessWidget { // In the Constructor onTap and Symbol fields are added. const CustomButton({Key key, this.onTap, this.symbol}) : super(key: key); // It Requires 2 fields Symbol(to be displayed) // and onTap Function final String symbol; final Function onTap; @override Widget build(BuildContext context) { return GestureDetector( // The onTap Field is used here. onTap: onTap, child: Container( height: 60, width: 60, decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.blueGrey, ), child: Center( child: Text( // The Symbol is used here symbol, style: TextStyle( fontSize: 35, fontWeight: FontWeight.bold, color: Colors.white, ), ), ), ), ); }}",
"e": 33522,
"s": 32570,
"text": null
},
{
"code": null,
"e": 33530,
"s": 33522,
"text": "Output:"
},
{
"code": null,
"e": 33577,
"s": 33530,
"text": "Results obtained by tapping different buttons."
},
{
"code": null,
"e": 33585,
"s": 33577,
"text": "android"
},
{
"code": null,
"e": 33593,
"s": 33585,
"text": "Flutter"
},
{
"code": null,
"e": 33609,
"s": 33593,
"text": "Flutter-widgets"
},
{
"code": null,
"e": 33616,
"s": 33609,
"text": "Picked"
},
{
"code": null,
"e": 33621,
"s": 33616,
"text": "Dart"
},
{
"code": null,
"e": 33629,
"s": 33621,
"text": "Flutter"
},
{
"code": null,
"e": 33727,
"s": 33629,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33759,
"s": 33727,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 33798,
"s": 33759,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 33824,
"s": 33798,
"text": "Flutter - Checkbox Widget"
},
{
"code": null,
"e": 33850,
"s": 33824,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 33876,
"s": 33850,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 33908,
"s": 33876,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 33947,
"s": 33908,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 33964,
"s": 33947,
"text": "Flutter Tutorial"
},
{
"code": null,
"e": 33990,
"s": 33964,
"text": "Flutter - Checkbox Widget"
}
] |
Arduino - String Object
|
The second type of string used in Arduino programming is the String Object.
An object is a construct that contains both data and functions. A String object can be created just like a variable and assigned a value or string. The String object contains functions (which are called "methods" in object oriented programming (OOP)) which operate on the string data contained in the String object.
The following sketch and explanation will make it clear what an object is and how the String object is used.
void setup() {
String my_str = "This is my string.";
Serial.begin(9600);
// (1) print the string
Serial.println(my_str);
// (2) change the string to upper-case
my_str.toUpperCase();
Serial.println(my_str);
// (3) overwrite the string
my_str = "My new string.";
Serial.println(my_str);
// (4) replace a word in the string
my_str.replace("string", "Arduino sketch");
Serial.println(my_str);
// (5) get the length of the string
Serial.print("String length is: ");
Serial.println(my_str.length());
}
void loop() {
}
This is my string.
THIS IS MY STRING.
My new string.
My new Arduino sketch.
String length is: 22
A string object is created and assigned a value (or string) at the top of the sketch.
String my_str = "This is my string." ;
This creates a String object with the name my_str and gives it a value of "This is my string.".
This can be compared to creating a variable and assigning a value to it such as an integer −
int my_var = 102;
The sketch works in the following way.
The string can be printed to the Serial Monitor window just like a character array string.
The string object my_str that was created, has a number of functions or methods that can be operated on it. These methods are invoked by using the objects name followed by the dot operator (.) and then the name of the function to use.
my_str.toUpperCase();
The toUpperCase() function operates on the string contained in the my_str object which is of type String and converts the string data (or text) that the object contains to upper-case characters. A list of the functions that the String class contains can be found in the Arduino String reference. Technically, String is called a class and is used to create String objects.
The assignment operator is used to assign a new string to the my_str object that replaces the old string
my_str = "My new string." ;
The assignment operator cannot be used on character array strings, but works on String objects only.
The replace() function is used to replace the first string passed to it by the second string passed to it. replace() is another function that is built into the String class and so is available to use on the String object my_str.
Getting the length of the string is easily done by using length(). In the example sketch, the result returned by length() is passed directly to Serial.println() without using an intermediate variable.
A String object is much easier to use than a string character array. The object has built-in functions that can perform a number of operations on strings.
The main disadvantage of using the String object is that it uses a lot of memory and can quickly use up the Arduinos RAM memory, which may cause Arduino to hang, crash or behave unexpectedly. If a sketch on an Arduino is small and limits the use of objects, then there should be no problems.
Character array strings are more difficult to use and you may need to write your own functions to operate on these types of strings. The advantage is that you have control on the size of the string arrays that you make, so you can keep the arrays small to save memory.
You need to make sure that you do not write beyond the end of the array bounds with string arrays. The String object does not have this problem and will take care of the string bounds for you, provided there is enough memory for it to operate on. The String object can try to write to memory that does not exist when it runs out of memory, but will never write over the end of the string that it is operating on.
In this chapter we studied about the strings, how they behave in memory and their operations.
The practical uses of strings will be covered in the next part of this course when we study how to get user input from the Serial Monitor window and save the input in a string.
65 Lectures
6.5 hours
Amit Rana
43 Lectures
3 hours
Amit Rana
20 Lectures
2 hours
Ashraf Said
19 Lectures
1.5 hours
Ashraf Said
11 Lectures
47 mins
Ashraf Said
9 Lectures
41 mins
Ashraf Said
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2946,
"s": 2870,
"text": "The second type of string used in Arduino programming is the String Object."
},
{
"code": null,
"e": 3262,
"s": 2946,
"text": "An object is a construct that contains both data and functions. A String object can be created just like a variable and assigned a value or string. The String object contains functions (which are called \"methods\" in object oriented programming (OOP)) which operate on the string data contained in the String object."
},
{
"code": null,
"e": 3371,
"s": 3262,
"text": "The following sketch and explanation will make it clear what an object is and how the String object is used."
},
{
"code": null,
"e": 3940,
"s": 3371,
"text": "void setup() { \n String my_str = \"This is my string.\";\n Serial.begin(9600);\n\n // (1) print the string\n Serial.println(my_str);\n\n // (2) change the string to upper-case\n my_str.toUpperCase();\n Serial.println(my_str);\n\n // (3) overwrite the string\n my_str = \"My new string.\";\n Serial.println(my_str);\n\n // (4) replace a word in the string\n my_str.replace(\"string\", \"Arduino sketch\");\n Serial.println(my_str);\n\n // (5) get the length of the string\n Serial.print(\"String length is: \");\n Serial.println(my_str.length());\n}\n\nvoid loop() { \n\n}"
},
{
"code": null,
"e": 4038,
"s": 3940,
"text": "This is my string.\nTHIS IS MY STRING.\nMy new string.\nMy new Arduino sketch.\nString length is: 22\n"
},
{
"code": null,
"e": 4124,
"s": 4038,
"text": "A string object is created and assigned a value (or string) at the top of the sketch."
},
{
"code": null,
"e": 4164,
"s": 4124,
"text": "String my_str = \"This is my string.\" ;\n"
},
{
"code": null,
"e": 4260,
"s": 4164,
"text": "This creates a String object with the name my_str and gives it a value of \"This is my string.\"."
},
{
"code": null,
"e": 4353,
"s": 4260,
"text": "This can be compared to creating a variable and assigning a value to it such as an integer −"
},
{
"code": null,
"e": 4372,
"s": 4353,
"text": "int my_var = 102;\n"
},
{
"code": null,
"e": 4411,
"s": 4372,
"text": "The sketch works in the following way."
},
{
"code": null,
"e": 4502,
"s": 4411,
"text": "The string can be printed to the Serial Monitor window just like a character array string."
},
{
"code": null,
"e": 4737,
"s": 4502,
"text": "The string object my_str that was created, has a number of functions or methods that can be operated on it. These methods are invoked by using the objects name followed by the dot operator (.) and then the name of the function to use."
},
{
"code": null,
"e": 4760,
"s": 4737,
"text": "my_str.toUpperCase();\n"
},
{
"code": null,
"e": 5132,
"s": 4760,
"text": "The toUpperCase() function operates on the string contained in the my_str object which is of type String and converts the string data (or text) that the object contains to upper-case characters. A list of the functions that the String class contains can be found in the Arduino String reference. Technically, String is called a class and is used to create String objects."
},
{
"code": null,
"e": 5237,
"s": 5132,
"text": "The assignment operator is used to assign a new string to the my_str object that replaces the old string"
},
{
"code": null,
"e": 5266,
"s": 5237,
"text": "my_str = \"My new string.\" ;\n"
},
{
"code": null,
"e": 5367,
"s": 5266,
"text": "The assignment operator cannot be used on character array strings, but works on String objects only."
},
{
"code": null,
"e": 5596,
"s": 5367,
"text": "The replace() function is used to replace the first string passed to it by the second string passed to it. replace() is another function that is built into the String class and so is available to use on the String object my_str."
},
{
"code": null,
"e": 5797,
"s": 5596,
"text": "Getting the length of the string is easily done by using length(). In the example sketch, the result returned by length() is passed directly to Serial.println() without using an intermediate variable."
},
{
"code": null,
"e": 5952,
"s": 5797,
"text": "A String object is much easier to use than a string character array. The object has built-in functions that can perform a number of operations on strings."
},
{
"code": null,
"e": 6244,
"s": 5952,
"text": "The main disadvantage of using the String object is that it uses a lot of memory and can quickly use up the Arduinos RAM memory, which may cause Arduino to hang, crash or behave unexpectedly. If a sketch on an Arduino is small and limits the use of objects, then there should be no problems."
},
{
"code": null,
"e": 6513,
"s": 6244,
"text": "Character array strings are more difficult to use and you may need to write your own functions to operate on these types of strings. The advantage is that you have control on the size of the string arrays that you make, so you can keep the arrays small to save memory."
},
{
"code": null,
"e": 6926,
"s": 6513,
"text": "You need to make sure that you do not write beyond the end of the array bounds with string arrays. The String object does not have this problem and will take care of the string bounds for you, provided there is enough memory for it to operate on. The String object can try to write to memory that does not exist when it runs out of memory, but will never write over the end of the string that it is operating on."
},
{
"code": null,
"e": 7020,
"s": 6926,
"text": "In this chapter we studied about the strings, how they behave in memory and their operations."
},
{
"code": null,
"e": 7197,
"s": 7020,
"text": "The practical uses of strings will be covered in the next part of this course when we study how to get user input from the Serial Monitor window and save the input in a string."
},
{
"code": null,
"e": 7232,
"s": 7197,
"text": "\n 65 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 7243,
"s": 7232,
"text": " Amit Rana"
},
{
"code": null,
"e": 7276,
"s": 7243,
"text": "\n 43 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 7287,
"s": 7276,
"text": " Amit Rana"
},
{
"code": null,
"e": 7320,
"s": 7287,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7333,
"s": 7320,
"text": " Ashraf Said"
},
{
"code": null,
"e": 7368,
"s": 7333,
"text": "\n 19 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7381,
"s": 7368,
"text": " Ashraf Said"
},
{
"code": null,
"e": 7413,
"s": 7381,
"text": "\n 11 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 7426,
"s": 7413,
"text": " Ashraf Said"
},
{
"code": null,
"e": 7457,
"s": 7426,
"text": "\n 9 Lectures \n 41 mins\n"
},
{
"code": null,
"e": 7470,
"s": 7457,
"text": " Ashraf Said"
},
{
"code": null,
"e": 7477,
"s": 7470,
"text": " Print"
},
{
"code": null,
"e": 7488,
"s": 7477,
"text": " Add Notes"
}
] |
C program to traverse an Array - GeeksforGeeks
|
30 Mar, 2021
Given an integer array of size N, the task is to traverse and print the elements in the array.Examples:
Input: arr[] = {2, -1, 5, 6, 0, -3} Output: 2 -1 5 6 0 -3
Input: arr[] = {4, 0, -2, -9, -7, 1} Output: 4 0 -2 -9 -7 1
Approach:-
1. Start a loop from 0 to N-1, where N is the size of array.
for(i = 0; i < N; i++)
2. Access every element of array with help of
arr[index]
3. Print the elements.
printf("%d ", arr[i])
Below is the implementation of the above approach:
C
// C program to traverse the array #include <stdio.h> // Function to traverse and print the arrayvoid printArray(int* arr, int n){ int i; printf("Array: "); for (i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n");} // Driver programint main(){ int arr[] = { 2, -1, 5, 6, 0, -3 }; int n = sizeof(arr) / sizeof(arr[0]); printArray(arr, n); return 0;}
Array: 2 -1 5 6 0 -3
Time Complexity: O(n)
Auxiliary Space: O(1)
souravmahato348
C-Arrays
Arrays
C Programs
School Programming
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Strings in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
Header files in C/C++ and its uses
Basics of File Handling in C
|
[
{
"code": null,
"e": 25721,
"s": 25693,
"text": "\n30 Mar, 2021"
},
{
"code": null,
"e": 25826,
"s": 25721,
"text": "Given an integer array of size N, the task is to traverse and print the elements in the array.Examples: "
},
{
"code": null,
"e": 25884,
"s": 25826,
"text": "Input: arr[] = {2, -1, 5, 6, 0, -3} Output: 2 -1 5 6 0 -3"
},
{
"code": null,
"e": 25946,
"s": 25884,
"text": "Input: arr[] = {4, 0, -2, -9, -7, 1} Output: 4 0 -2 -9 -7 1 "
},
{
"code": null,
"e": 25959,
"s": 25946,
"text": "Approach:- "
},
{
"code": null,
"e": 26021,
"s": 25959,
"text": "1. Start a loop from 0 to N-1, where N is the size of array. "
},
{
"code": null,
"e": 26044,
"s": 26021,
"text": "for(i = 0; i < N; i++)"
},
{
"code": null,
"e": 26091,
"s": 26044,
"text": "2. Access every element of array with help of "
},
{
"code": null,
"e": 26102,
"s": 26091,
"text": "arr[index]"
},
{
"code": null,
"e": 26126,
"s": 26102,
"text": "3. Print the elements. "
},
{
"code": null,
"e": 26148,
"s": 26126,
"text": "printf(\"%d \", arr[i])"
},
{
"code": null,
"e": 26201,
"s": 26148,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26203,
"s": 26201,
"text": "C"
},
{
"code": "// C program to traverse the array #include <stdio.h> // Function to traverse and print the arrayvoid printArray(int* arr, int n){ int i; printf(\"Array: \"); for (i = 0; i < n; i++) { printf(\"%d \", arr[i]); } printf(\"\\n\");} // Driver programint main(){ int arr[] = { 2, -1, 5, 6, 0, -3 }; int n = sizeof(arr) / sizeof(arr[0]); printArray(arr, n); return 0;}",
"e": 26597,
"s": 26203,
"text": null
},
{
"code": null,
"e": 26618,
"s": 26597,
"text": "Array: 2 -1 5 6 0 -3"
},
{
"code": null,
"e": 26642,
"s": 26620,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 26664,
"s": 26642,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 26680,
"s": 26664,
"text": "souravmahato348"
},
{
"code": null,
"e": 26689,
"s": 26680,
"text": "C-Arrays"
},
{
"code": null,
"e": 26696,
"s": 26689,
"text": "Arrays"
},
{
"code": null,
"e": 26707,
"s": 26696,
"text": "C Programs"
},
{
"code": null,
"e": 26726,
"s": 26707,
"text": "School Programming"
},
{
"code": null,
"e": 26733,
"s": 26726,
"text": "Arrays"
},
{
"code": null,
"e": 26831,
"s": 26733,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26899,
"s": 26831,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 26943,
"s": 26899,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 26991,
"s": 26943,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 27014,
"s": 26991,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 27046,
"s": 27014,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 27059,
"s": 27046,
"text": "Strings in C"
},
{
"code": null,
"e": 27100,
"s": 27059,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 27141,
"s": 27100,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 27176,
"s": 27141,
"text": "Header files in C/C++ and its uses"
}
] |
Python - Remove elements at Indices in List - GeeksforGeeks
|
01 Dec, 2021
Given List, remove all the elements present in indices list.
Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2, 4, 5] Output : [5, 6, 7, 2, 10] Explanation : 3, 6, and 1 has been removed.Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2] Output : [5, 6, 7, 8, 1, 2, 10] Explanation : 3 has been removed.
Method #1 : Using enumerate() + loop
In this, we iterate for all the elements, and if index is present in list, then that index element is omitted from result list.
Python3
# Python3 code to demonstrate working of# Remove elements at Indices in List# Using loop # initializing listtest_list = [5, 6, 3, 7, 8, 1, 2, 10] # printing original listprint("The original list is : " + str(test_list)) # initializing idx listidx_list = [2, 4, 5, 7] res = []for idx, ele in enumerate(test_list): # checking if element not present in index list if idx not in idx_list: res.append(ele) # printing resultsprint("Filtered List after removal : " + str(res))
The original list is : [5, 6, 3, 7, 8, 1, 2, 10]
Filtered List after removal : [5, 6, 7, 2]
Method #2 : Using enumerate() + list comprehension
In this, we perform task of iteration using list comprehension in compact way, rest all method similar to above.
Python3
# Python3 code to demonstrate working of# Remove elements at Indices in List# Using enumerate() + list comprehension # initializing listtest_list = [5, 6, 3, 7, 8, 1, 2, 10] # printing original listprint("The original list is : " + str(test_list)) # initializing idx listidx_list = [2, 4, 5, 7] # one-liner to test for element in index listres = [ele for idx, ele in enumerate(test_list) if idx not in idx_list] # printing resultsprint("Filtered List after removal : " + str(res))
The original list is : [5, 6, 3, 7, 8, 1, 2, 10]
Filtered List after removal : [5, 6, 7, 2]
rajeev0719singh
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n01 Dec, 2021"
},
{
"code": null,
"e": 25598,
"s": 25537,
"text": "Given List, remove all the elements present in indices list."
},
{
"code": null,
"e": 25865,
"s": 25598,
"text": "Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2, 4, 5] Output : [5, 6, 7, 2, 10] Explanation : 3, 6, and 1 has been removed.Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2] Output : [5, 6, 7, 8, 1, 2, 10] Explanation : 3 has been removed. "
},
{
"code": null,
"e": 25902,
"s": 25865,
"text": "Method #1 : Using enumerate() + loop"
},
{
"code": null,
"e": 26030,
"s": 25902,
"text": "In this, we iterate for all the elements, and if index is present in list, then that index element is omitted from result list."
},
{
"code": null,
"e": 26038,
"s": 26030,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Remove elements at Indices in List# Using loop # initializing listtest_list = [5, 6, 3, 7, 8, 1, 2, 10] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing idx listidx_list = [2, 4, 5, 7] res = []for idx, ele in enumerate(test_list): # checking if element not present in index list if idx not in idx_list: res.append(ele) # printing resultsprint(\"Filtered List after removal : \" + str(res))",
"e": 26526,
"s": 26038,
"text": null
},
{
"code": null,
"e": 26618,
"s": 26526,
"text": "The original list is : [5, 6, 3, 7, 8, 1, 2, 10]\nFiltered List after removal : [5, 6, 7, 2]"
},
{
"code": null,
"e": 26669,
"s": 26618,
"text": "Method #2 : Using enumerate() + list comprehension"
},
{
"code": null,
"e": 26782,
"s": 26669,
"text": "In this, we perform task of iteration using list comprehension in compact way, rest all method similar to above."
},
{
"code": null,
"e": 26790,
"s": 26782,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Remove elements at Indices in List# Using enumerate() + list comprehension # initializing listtest_list = [5, 6, 3, 7, 8, 1, 2, 10] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing idx listidx_list = [2, 4, 5, 7] # one-liner to test for element in index listres = [ele for idx, ele in enumerate(test_list) if idx not in idx_list] # printing resultsprint(\"Filtered List after removal : \" + str(res))",
"e": 27271,
"s": 26790,
"text": null
},
{
"code": null,
"e": 27363,
"s": 27271,
"text": "The original list is : [5, 6, 3, 7, 8, 1, 2, 10]\nFiltered List after removal : [5, 6, 7, 2]"
},
{
"code": null,
"e": 27379,
"s": 27363,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 27400,
"s": 27379,
"text": "Python list-programs"
},
{
"code": null,
"e": 27407,
"s": 27400,
"text": "Python"
},
{
"code": null,
"e": 27423,
"s": 27407,
"text": "Python Programs"
},
{
"code": null,
"e": 27521,
"s": 27423,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27553,
"s": 27521,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27595,
"s": 27553,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27637,
"s": 27595,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27664,
"s": 27637,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27720,
"s": 27664,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27742,
"s": 27720,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27781,
"s": 27742,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27827,
"s": 27781,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27865,
"s": 27827,
"text": "Python | Convert a list to dictionary"
}
] |
How to Check if LinkedHashMap Contains a value in Java? - GeeksforGeeks
|
15 Dec, 2020
LinkedHashMap is a predefined class in Java which is similar to HashMap, contains key and its respective value unlike HashMap, In LinkedHashMap insertion order is preserved. The task is to check if LinkedHashMap contains any value in java. to check we have to iterate through our LinkedHashMap and if we get any value we return true.
Example :
Input : Key- 2 : Value-6
Key- 4 : Value-1
Key- 5 : Value-10
value to check - 2
Output : False
Input : Key- 1 : Value-15
Key- 3 : Value-12
Key- 5 : Value-9
Key- 6 : Value-11
Value to check - 11
Output : True
Approach 1:(Using entrySet() Method)
Use a For-each loop to iterate through LinkedHashMap. create check() function to if there exist any value in LinkedHasMap or nor. Iterate through LinkedHashMap if we get any value return true else return false.
Pseudo Code:
for (Map.Entry<Integer, Integer> it : lhm.entrySet()) {
if (it.getValue() != null)
return true;
}
Syntax:
linked_hash_map.entrySet()
Parameters: The method does not take any parameter.
Return Value: The method returns a set having the same elements as the LinkedHashMap.
Example:
Java
// Java program to check if LinkedHashMap contains a// particular value import java.util.*;import java.io.*; class GFG { public static boolean check(LinkedHashMap<Integer, Integer> lhm, int value) { // iterate the map and find for (Map.Entry<Integer, Integer> it : lhm.entrySet()) { if (it.getValue() == value) return true; } return false; } public static void main(String[] args) { // create a linked Hashmap LinkedHashMap<Integer, Integer> LHM = new LinkedHashMap<>(); // add elements LHM.put(2, 6); LHM.put(4, 1); LHM.put(5, 10); int value = 2; // check if has a value 2 if (check(LHM, value)) System.out.println("True"); else System.out.println("False"); }}
False
Time complexity: O(n).
Approach 2: (Using containsValue() Method)
This approach is an optimal approach to our problem. In the above approach, we iterate through our LinkedHashMap. In this approach, we directly use our pre-defined function to check our value.
Algorithm
Use the function containValue() to find if our value is present or not in our LinkedHashMap.
Psuedo Code:
LHM.containsValue(val)
Here,
Val is value to check.
LHM is name of our LinkedHashMap.
Syntax:
Linked_Hash_Map.containsValue(Object Value)
Parameters: The method takes just one parameter Value of Object type and refers to the value whose mapping is supposed to be checked by any key inside the map.
Return Value: The method returns boolean true if the mapping of the value is detected else false.
Example:
Java
// Java program to check if LinkedHashMap contains a// particular value import java.util.*;import java.io.*; class GFG { public static void main(String[] args) { // create a linked hashmap LinkedHashMap<Integer, Integer> LHM = new LinkedHashMap<>(); // add mappings LHM.put(2, 6); LHM.put(4, 1); LHM.put(5, 10); int value = 2; // check if it has a value if (LHM.containsValue(value)) System.out.println("True"); else System.out.println("False"); }}
False
Time Complexity: O(1).
Java-LinkedHashMap
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
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
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": 25251,
"s": 25223,
"text": "\n15 Dec, 2020"
},
{
"code": null,
"e": 25586,
"s": 25251,
"text": "LinkedHashMap is a predefined class in Java which is similar to HashMap, contains key and its respective value unlike HashMap, In LinkedHashMap insertion order is preserved. The task is to check if LinkedHashMap contains any value in java. to check we have to iterate through our LinkedHashMap and if we get any value we return true."
},
{
"code": null,
"e": 25596,
"s": 25586,
"text": "Example :"
},
{
"code": null,
"e": 25834,
"s": 25596,
"text": "Input : Key- 2 : Value-6\n Key- 4 : Value-1\n Key- 5 : Value-10\n value to check - 2\n\nOutput : False\n\nInput : Key- 1 : Value-15\n Key- 3 : Value-12\n Key- 5 : Value-9\n Key- 6 : Value-11\n Value to check - 11\n\nOutput : True"
},
{
"code": null,
"e": 25871,
"s": 25834,
"text": "Approach 1:(Using entrySet() Method)"
},
{
"code": null,
"e": 26082,
"s": 25871,
"text": "Use a For-each loop to iterate through LinkedHashMap. create check() function to if there exist any value in LinkedHasMap or nor. Iterate through LinkedHashMap if we get any value return true else return false."
},
{
"code": null,
"e": 26095,
"s": 26082,
"text": "Pseudo Code:"
},
{
"code": null,
"e": 26216,
"s": 26095,
"text": "for (Map.Entry<Integer, Integer> it : lhm.entrySet()) {\n if (it.getValue() != null)\n return true;\n}"
},
{
"code": null,
"e": 26224,
"s": 26216,
"text": "Syntax:"
},
{
"code": null,
"e": 26251,
"s": 26224,
"text": "linked_hash_map.entrySet()"
},
{
"code": null,
"e": 26303,
"s": 26251,
"text": "Parameters: The method does not take any parameter."
},
{
"code": null,
"e": 26389,
"s": 26303,
"text": "Return Value: The method returns a set having the same elements as the LinkedHashMap."
},
{
"code": null,
"e": 26398,
"s": 26389,
"text": "Example:"
},
{
"code": null,
"e": 26403,
"s": 26398,
"text": "Java"
},
{
"code": "// Java program to check if LinkedHashMap contains a// particular value import java.util.*;import java.io.*; class GFG { public static boolean check(LinkedHashMap<Integer, Integer> lhm, int value) { // iterate the map and find for (Map.Entry<Integer, Integer> it : lhm.entrySet()) { if (it.getValue() == value) return true; } return false; } public static void main(String[] args) { // create a linked Hashmap LinkedHashMap<Integer, Integer> LHM = new LinkedHashMap<>(); // add elements LHM.put(2, 6); LHM.put(4, 1); LHM.put(5, 10); int value = 2; // check if has a value 2 if (check(LHM, value)) System.out.println(\"True\"); else System.out.println(\"False\"); }}",
"e": 27265,
"s": 26403,
"text": null
},
{
"code": null,
"e": 27271,
"s": 27265,
"text": "False"
},
{
"code": null,
"e": 27294,
"s": 27271,
"text": "Time complexity: O(n)."
},
{
"code": null,
"e": 27337,
"s": 27294,
"text": "Approach 2: (Using containsValue() Method)"
},
{
"code": null,
"e": 27530,
"s": 27337,
"text": "This approach is an optimal approach to our problem. In the above approach, we iterate through our LinkedHashMap. In this approach, we directly use our pre-defined function to check our value."
},
{
"code": null,
"e": 27540,
"s": 27530,
"text": "Algorithm"
},
{
"code": null,
"e": 27634,
"s": 27540,
"text": "Use the function containValue() to find if our value is present or not in our LinkedHashMap."
},
{
"code": null,
"e": 27647,
"s": 27634,
"text": "Psuedo Code:"
},
{
"code": null,
"e": 27670,
"s": 27647,
"text": "LHM.containsValue(val)"
},
{
"code": null,
"e": 27677,
"s": 27670,
"text": "Here, "
},
{
"code": null,
"e": 27700,
"s": 27677,
"text": "Val is value to check."
},
{
"code": null,
"e": 27734,
"s": 27700,
"text": "LHM is name of our LinkedHashMap."
},
{
"code": null,
"e": 27742,
"s": 27734,
"text": "Syntax:"
},
{
"code": null,
"e": 27786,
"s": 27742,
"text": "Linked_Hash_Map.containsValue(Object Value)"
},
{
"code": null,
"e": 27946,
"s": 27786,
"text": "Parameters: The method takes just one parameter Value of Object type and refers to the value whose mapping is supposed to be checked by any key inside the map."
},
{
"code": null,
"e": 28044,
"s": 27946,
"text": "Return Value: The method returns boolean true if the mapping of the value is detected else false."
},
{
"code": null,
"e": 28053,
"s": 28044,
"text": "Example:"
},
{
"code": null,
"e": 28058,
"s": 28053,
"text": "Java"
},
{
"code": "// Java program to check if LinkedHashMap contains a// particular value import java.util.*;import java.io.*; class GFG { public static void main(String[] args) { // create a linked hashmap LinkedHashMap<Integer, Integer> LHM = new LinkedHashMap<>(); // add mappings LHM.put(2, 6); LHM.put(4, 1); LHM.put(5, 10); int value = 2; // check if it has a value if (LHM.containsValue(value)) System.out.println(\"True\"); else System.out.println(\"False\"); }}",
"e": 28631,
"s": 28058,
"text": null
},
{
"code": null,
"e": 28637,
"s": 28631,
"text": "False"
},
{
"code": null,
"e": 28660,
"s": 28637,
"text": "Time Complexity: O(1)."
},
{
"code": null,
"e": 28679,
"s": 28660,
"text": "Java-LinkedHashMap"
},
{
"code": null,
"e": 28686,
"s": 28679,
"text": "Picked"
},
{
"code": null,
"e": 28710,
"s": 28686,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28715,
"s": 28710,
"text": "Java"
},
{
"code": null,
"e": 28729,
"s": 28715,
"text": "Java Programs"
},
{
"code": null,
"e": 28748,
"s": 28729,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28753,
"s": 28748,
"text": "Java"
},
{
"code": null,
"e": 28851,
"s": 28753,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28866,
"s": 28851,
"text": "Stream In Java"
},
{
"code": null,
"e": 28887,
"s": 28866,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28906,
"s": 28887,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28936,
"s": 28906,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28982,
"s": 28936,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29008,
"s": 28982,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 29042,
"s": 29008,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 29089,
"s": 29042,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 29121,
"s": 29089,
"text": "How to Iterate HashMap in Java?"
}
] |
MongoDB updateMany() Method - db.Collection.updateMany() - GeeksforGeeks
|
28 Jan, 2021
The updateMany() method updates all the documents in MongoDB collections that match the given query. When you update your document, the value of the _id field remains unchanged. This method can also add new fields in the document. Specify an empty document({}) in the selection criteria to update all collection documents.
This method can accept documents that only holds update operator expressions.
This method can also accept aggregation pipeline.
In this method, if the value of upsert is set to true for the shared collection, then you must include the full shared key in the filter/selection criteria.
The update operation will fail if this operation changes the size of the document.
You can also use this method inside multi-document transactions.
Syntax:
db.Collection_name.updateMany({Selection_Criteria},{$set:{Update_Data}},
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [<filterdocument1>, ... ],
hint: <document|string>
})
Parameters:
The first parameter is the Older value in the form of Documents. Documents are a structure created of file and value pairs, similar to JSON objects. Specify an empty document ({}) to update all documents in the collection.
The second parameter must contain a $set keyword to update the following specific document value.
The third parameter is optional.
Optional Parameters:
Upsert: The default value of this parameter is false. When it is true, it will make a new document in the collection when no document matches the given condition in the update method.
Multi: The default value of this parameter is false. When it is true, the update method updates all the documents that meet the query condition. Otherwise, it will update only one document.
writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document.
Collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison, like lettercase and accent marks. The type of this parameter is a document.
arrayFilters: It is an array of filter documents that indicates which array elements to modify for an update operation on an array field. The type of this parameter is an array.
Hint: It is a document or field that specifies the index to use to support the filter. It can take an index specification document or the index name string, and if you specify an index that does not exist, it will give an error.
Return:
This method returns a document that contains the following fields:
matchedCount: This field contains the number of matched documents.
modifiedCount: This field contains the number of modified documents.
upsertedId: This field contains the _id for the upserted document.
acknowledged: The value of this field is true if write concern was enabled or false if write concern was disabled.
Examples:
In the following examples, we are working with:
Database: gfg
Collection: student
Document: Three documents contains name and age of the students
db.student.updateMany({name: "aaksh"}, {$set:{age: 20}})
Here, we update the age of a student whose name is aaksh from 15 to 20 using updateMany() method.
db.student.updateMany({age:18},{$set:{eligible:"true"}})
Here, we update all the matched documents whose age is 18 to eligible: true
db.student.updateMany({age: 18}, {$set: {eligible: false}}, {upsert: true})
Here, we update all the documents that matched the given condition.
MongoDB-method
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - FindOne() Method
Create user and add role in MongoDB
MongoDB - sort() Method
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB insertMany() Method - db.Collection.insertMany()
MongoDB Cursor
MongoDB - Update() Method
How to Use Go With MongoDB?
|
[
{
"code": null,
"e": 25517,
"s": 25489,
"text": "\n28 Jan, 2021"
},
{
"code": null,
"e": 25840,
"s": 25517,
"text": "The updateMany() method updates all the documents in MongoDB collections that match the given query. When you update your document, the value of the _id field remains unchanged. This method can also add new fields in the document. Specify an empty document({}) in the selection criteria to update all collection documents."
},
{
"code": null,
"e": 25918,
"s": 25840,
"text": "This method can accept documents that only holds update operator expressions."
},
{
"code": null,
"e": 25968,
"s": 25918,
"text": "This method can also accept aggregation pipeline."
},
{
"code": null,
"e": 26125,
"s": 25968,
"text": "In this method, if the value of upsert is set to true for the shared collection, then you must include the full shared key in the filter/selection criteria."
},
{
"code": null,
"e": 26208,
"s": 26125,
"text": "The update operation will fail if this operation changes the size of the document."
},
{
"code": null,
"e": 26273,
"s": 26208,
"text": "You can also use this method inside multi-document transactions."
},
{
"code": null,
"e": 26281,
"s": 26273,
"text": "Syntax:"
},
{
"code": null,
"e": 26355,
"s": 26281,
"text": "db.Collection_name.updateMany({Selection_Criteria},{$set:{Update_Data}}, "
},
{
"code": null,
"e": 26357,
"s": 26355,
"text": "{"
},
{
"code": null,
"e": 26380,
"s": 26357,
"text": " upsert: <boolean>,"
},
{
"code": null,
"e": 26402,
"s": 26380,
"text": " multi: <boolean>,"
},
{
"code": null,
"e": 26432,
"s": 26402,
"text": " writeConcern: <document>,"
},
{
"code": null,
"e": 26459,
"s": 26432,
"text": " collation: <document>,"
},
{
"code": null,
"e": 26504,
"s": 26459,
"text": " arrayFilters: [<filterdocument1>, ... ],"
},
{
"code": null,
"e": 26540,
"s": 26504,
"text": " hint: <document|string> "
},
{
"code": null,
"e": 26543,
"s": 26540,
"text": "})"
},
{
"code": null,
"e": 26555,
"s": 26543,
"text": "Parameters:"
},
{
"code": null,
"e": 26778,
"s": 26555,
"text": "The first parameter is the Older value in the form of Documents. Documents are a structure created of file and value pairs, similar to JSON objects. Specify an empty document ({}) to update all documents in the collection."
},
{
"code": null,
"e": 26876,
"s": 26778,
"text": "The second parameter must contain a $set keyword to update the following specific document value."
},
{
"code": null,
"e": 26909,
"s": 26876,
"text": "The third parameter is optional."
},
{
"code": null,
"e": 26930,
"s": 26909,
"text": "Optional Parameters:"
},
{
"code": null,
"e": 27114,
"s": 26930,
"text": "Upsert: The default value of this parameter is false. When it is true, it will make a new document in the collection when no document matches the given condition in the update method."
},
{
"code": null,
"e": 27304,
"s": 27114,
"text": "Multi: The default value of this parameter is false. When it is true, the update method updates all the documents that meet the query condition. Otherwise, it will update only one document."
},
{
"code": null,
"e": 27431,
"s": 27304,
"text": "writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document."
},
{
"code": null,
"e": 27650,
"s": 27431,
"text": "Collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison, like lettercase and accent marks. The type of this parameter is a document."
},
{
"code": null,
"e": 27828,
"s": 27650,
"text": "arrayFilters: It is an array of filter documents that indicates which array elements to modify for an update operation on an array field. The type of this parameter is an array."
},
{
"code": null,
"e": 28057,
"s": 27828,
"text": "Hint: It is a document or field that specifies the index to use to support the filter. It can take an index specification document or the index name string, and if you specify an index that does not exist, it will give an error."
},
{
"code": null,
"e": 28065,
"s": 28057,
"text": "Return:"
},
{
"code": null,
"e": 28132,
"s": 28065,
"text": "This method returns a document that contains the following fields:"
},
{
"code": null,
"e": 28199,
"s": 28132,
"text": "matchedCount: This field contains the number of matched documents."
},
{
"code": null,
"e": 28268,
"s": 28199,
"text": "modifiedCount: This field contains the number of modified documents."
},
{
"code": null,
"e": 28335,
"s": 28268,
"text": "upsertedId: This field contains the _id for the upserted document."
},
{
"code": null,
"e": 28450,
"s": 28335,
"text": "acknowledged: The value of this field is true if write concern was enabled or false if write concern was disabled."
},
{
"code": null,
"e": 28460,
"s": 28450,
"text": "Examples:"
},
{
"code": null,
"e": 28508,
"s": 28460,
"text": "In the following examples, we are working with:"
},
{
"code": null,
"e": 28522,
"s": 28508,
"text": "Database: gfg"
},
{
"code": null,
"e": 28542,
"s": 28522,
"text": "Collection: student"
},
{
"code": null,
"e": 28606,
"s": 28542,
"text": "Document: Three documents contains name and age of the students"
},
{
"code": null,
"e": 28663,
"s": 28606,
"text": "db.student.updateMany({name: \"aaksh\"}, {$set:{age: 20}})"
},
{
"code": null,
"e": 28761,
"s": 28663,
"text": "Here, we update the age of a student whose name is aaksh from 15 to 20 using updateMany() method."
},
{
"code": null,
"e": 28818,
"s": 28761,
"text": "db.student.updateMany({age:18},{$set:{eligible:\"true\"}})"
},
{
"code": null,
"e": 28894,
"s": 28818,
"text": "Here, we update all the matched documents whose age is 18 to eligible: true"
},
{
"code": null,
"e": 28970,
"s": 28894,
"text": "db.student.updateMany({age: 18}, {$set: {eligible: false}}, {upsert: true})"
},
{
"code": null,
"e": 29038,
"s": 28970,
"text": "Here, we update all the documents that matched the given condition."
},
{
"code": null,
"e": 29053,
"s": 29038,
"text": "MongoDB-method"
},
{
"code": null,
"e": 29060,
"s": 29053,
"text": "Picked"
},
{
"code": null,
"e": 29068,
"s": 29060,
"text": "MongoDB"
},
{
"code": null,
"e": 29166,
"s": 29068,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29204,
"s": 29166,
"text": "How to connect MongoDB with ReactJS ?"
},
{
"code": null,
"e": 29229,
"s": 29204,
"text": "MongoDB - limit() Method"
},
{
"code": null,
"e": 29256,
"s": 29229,
"text": "MongoDB - FindOne() Method"
},
{
"code": null,
"e": 29292,
"s": 29256,
"text": "Create user and add role in MongoDB"
},
{
"code": null,
"e": 29316,
"s": 29292,
"text": "MongoDB - sort() Method"
},
{
"code": null,
"e": 29371,
"s": 29316,
"text": "MongoDB updateOne() Method - db.Collection.updateOne()"
},
{
"code": null,
"e": 29428,
"s": 29371,
"text": "MongoDB insertMany() Method - db.Collection.insertMany()"
},
{
"code": null,
"e": 29443,
"s": 29428,
"text": "MongoDB Cursor"
},
{
"code": null,
"e": 29469,
"s": 29443,
"text": "MongoDB - Update() Method"
}
] |
Eulerian Number - GeeksforGeeks
|
07 Aug, 2021
In combinatorics, the Eulerian Number A(n, m), is the number of permutations of the numbers 1 to n in which exactly m elements are greater than previous element.
For example, there are 4 permutations of the number 1 to 3 in which exactly 1 element is greater than the previous elements.
Examples :
Input : n = 3, m = 1
Output : 4
Please see above diagram (There
are 4 permutations where 1 no. is
greater.
Input : n = 4, m = 1
Output : 11
Eulerian Numbers are the coefficients of the Eulerian polynomials described below.
The Eulerian polynomials are defined by the exponential generating function
The Eulerian polynomials can be computed by the recurrence
An explicit formula for A(n, m) is
We can calculate A(n, m) by recurrence relation:
Example: Suppose, n = 3 and m = 1. Therefore, A(3, 1) = (3 – 1) * A(2, 0) + (1 + 1) * A(2, 1) = 2 * A(2, 0) + 2 * A(2, 1) = 2 * 1 + 2 * ( (2 – 1) * A(1, 0) + (1 + 1) * A(1, 1)) = 2 + 2 * (1 * 1 + 2 * ((1 – 1) * A(0, 0) + (1 + 1) * A(0, 1)) = 2 + 2 * (1 + 2 * (0 * 1 + 2 * 0) = 2 + 2 * (1 + 2 * 0) = 2 + 2 * 1 = 2 + 2 = 4 We can verify this with example shown above.
Below is the implementation of finding A(n, m):
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to find Eulerian number A(n, m)#include <bits/stdc++.h>using namespace std; // Return euleriannumber A(n, m)int eulerian(int n, int m){ if (m >= n || n == 0) return 0; if (m == 0) return 1; return (n - m) * eulerian(n - 1, m - 1) + (m + 1) * eulerian(n - 1, m);} // Driven Programint main(){ int n = 3, m = 1; cout << eulerian(n, m) << endl; return 0;}
// Java program to find Eulerian number A(n, m)import java.util.*; class Eulerian{ // Return eulerian number A(n, m) public static int eulerian(int n, int m) { if (m >= n || n == 0) return 0; if (m == 0) return 1; return (n - m) * eulerian(n - 1, m - 1) + (m + 1) * eulerian(n - 1, m); } // driver code public static void main(String[] args) { int n = 3, m = 1; System.out.print( eulerian(n, m) ); }} // This code is contributed by rishabh_jain
# Python3 Program to find Eulerian number A(n, m) # Return euleriannumber A(n, m)def eulerian(n, m): if (m >= n or n == 0): return 0; if (m == 0): return 1; return ((n - m) * eulerian(n - 1, m - 1) + (m + 1) * eulerian(n - 1, m)) # Driver coden = 3m = 1print( eulerian(n, m) ) # This code is contributed by rishabh_jain
// C# program to find Eulerian number A(n, m)using System; class Eulerian { // Return eulerian number A(n, m) public static int eulerian(int n, int m) { if (m >= n || n == 0) return 0; if (m == 0) return 1; return (n - m) * eulerian(n - 1, m - 1) + (m + 1) * eulerian(n - 1, m); } // driver code public static void Main() { int n = 3, m = 1; Console.WriteLine(eulerian(n, m)); }} // This code is contributed by vt_m
<?php// PHP Program to find// Eulerian number A(n, m) // Return euleriannumber A(n, m)function eulerian($n, $m){ if ($m >= $n || $n == 0) return 0; if ($m == 0) return 1; return ($n - $m) * eulerian($n - 1, $m - 1) + ($m + 1) * eulerian($n - 1, $m);} // Driven Code$n = 3; $m = 1;echo eulerian($n, $m); // This code is contributed by anuj_67.?>
<script> // JavaScript Program to find Eulerian number A(n, m) // Return eulerian number A(n, m) function eulerian(n, m) { if (m >= n || n == 0) return 0; if (m == 0) return 1; return (n - m) * eulerian(n - 1, m - 1) + (m + 1) * eulerian(n - 1, m); } // Driver code let n = 3, m = 1; document.write( eulerian(n, m) ); </script>
Output :
4
Below is the implementation of finding A(n, m) using Dynamic Programming:
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to find Eulerian number A(n, m)#include <bits/stdc++.h>using namespace std; // Return euleriannumber A(n, m)int eulerian(int n, int m){ int dp[n + 1][m + 1]; memset(dp, 0, sizeof(dp)); // For each row from 1 to n for (int i = 1; i <= n; i++) { // For each column from 0 to m for (int j = 0; j <= m; j++) { // If i is greater than j if (i > j) { // If j is 0, then make that // state as 1. if (j == 0) dp[i][j] = 1; // basic recurrence relation. else dp[i][j] = ((i - j) * dp[i - 1][j - 1]) + ((j + 1) * dp[i - 1][j]); } } } return dp[n][m];} // Driven Programint main(){ int n = 3, m = 1; cout << eulerian(n, m) << endl; return 0;}
// Java program to find Eulerian number A(n, m)import java.util.*; class Eulerian{ // Return euleriannumber A(n, m) public static int eulerian(int n, int m) { int[][] dp = new int[n+1][m+1]; // For each row from 1 to n for (int i = 1; i <= n; i++) { // For each column from 0 to m for (int j = 0; j <= m; j++) { // If i is greater than j if (i > j) { // If j is 0, then make // that state as 1. if (j == 0) dp[i][j] = 1; // basic recurrence relation. else dp[i][j] = ((i - j) * dp[i - 1][j - 1]) + ((j + 1) * dp[i - 1][j]); } } } return dp[n][m]; } // driver code public static void main(String[] args) { int n = 3, m = 1; System.out.print( eulerian(n, m) ); }} // This code is contributed by rishabh_jain
# Python3 Program to find Eulerian# number A(n, m) # Return euleriannumber A(n, m)def eulerian(n, m): dp = [[0 for x in range(m+1)] for y in range(n+1)] # For each row from 1 to n for i in range(1, n+1): # For each column from 0 to m for j in range(0, m+1): # If i is greater than j if (i > j): # If j is 0, then make that # state as 1. if (j == 0): dp[i][j] = 1 # basic recurrence relation. else : dp[i][j] = (((i - j) * dp[i - 1][j - 1]) + ((j + 1) * dp[i - 1][j])) return dp[n][m] # Driven Programn = 3m = 1print(eulerian(n, m)) # This code is contributed by Prasad Kshirsagar
// C# program to find Eulerian number A(n, m)using System; class Eulerian { // Return euleriannumber A(n, m) public static int eulerian(int n, int m) { int[, ] dp = new int[n + 1, m + 1]; // For each row from 1 to n for (int i = 1; i <= n; i++) { // For each column from 0 to m for (int j = 0; j <= m; j++) { // If i is greater than j if (i > j) { // If j is 0, then make // that state as 1. if (j == 0) dp[i, j] = 1; // basic recurrence relation. else dp[i, j] = ((i - j) * dp[i - 1, j - 1]) + ((j + 1) * dp[i - 1, j]); } } } return dp[n, m]; } // driver code public static void Main() { int n = 3, m = 1; Console.WriteLine(eulerian(n, m)); }} // This code is contributed by vt_m
<?php// PHP Program to find Eulerian// number A(n, m) // Return euleriannumber A(n, m)function eulerian($n, $m){ $dp = array(array()); for ($i = 0; $i < $n + 1; $i++) for($j = 0; $j < $m + 1; $j++) $dp[$i][$j] = 0 ; // For each row from 1 to n for ($i = 1; $i <= $n; $i++) { // For each column from 0 to m for ($j = 0; $j <= $m; $j++) { // If i is greater than j if ($i > $j) { // If j is 0, then make that // state as 1. if ($j == 0) $dp[$i][$j] = 1; // basic recurrence relation. else $dp[$i][$j] = (($i - $j) * $dp[$i - 1][$j - 1]) + (($j + 1) * $dp[$i - 1][$j]); } } } return $dp[$n][$m];} // Driver Code$n = 3 ;$m = 1;echo eulerian($n, $m) ; // This code is contributed by Ryuga?>
<script> // Javascript Program to find// Eulerian number A(n, m) // Return euleriannumber A(n, m)function eulerian(n, m){ var dp = Array.from(Array(n+1), ()=> Array(m+1).fill(0)); // For each row from 1 to n for (var i = 1; i <= n; i++) { // For each column from 0 to m for (var j = 0; j <= m; j++) { // If i is greater than j if (i > j) { // If j is 0, then make that // state as 1. if (j == 0) dp[i][j] = 1; // basic recurrence relation. else dp[i][j] = ((i - j) * dp[i - 1][j - 1]) + ((j + 1) * dp[i - 1][j]); } } } return dp[n][m];} // Driven Programvar n = 3, m = 1;document.write( eulerian(n, m) ); </script>
Output :
4
vt_m
Prasad_Kshirsagar
ankthon
sanjoy_62
noob2000
simranarora5sos
number-theory
Combinatorial
Dynamic Programming
number-theory
Dynamic Programming
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Combinational Sum
Count ways to reach the nth stair using step 1, 2 or 3
Print all possible strings of length k that can be formed from a set of n characters
Count of subsets with sum equal to X
Python program to get all subsets of given size of a set
0-1 Knapsack Problem | DP-10
Largest Sum Contiguous Subarray
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
|
[
{
"code": null,
"e": 26079,
"s": 26051,
"text": "\n07 Aug, 2021"
},
{
"code": null,
"e": 26241,
"s": 26079,
"text": "In combinatorics, the Eulerian Number A(n, m), is the number of permutations of the numbers 1 to n in which exactly m elements are greater than previous element."
},
{
"code": null,
"e": 26367,
"s": 26241,
"text": "For example, there are 4 permutations of the number 1 to 3 in which exactly 1 element is greater than the previous elements. "
},
{
"code": null,
"e": 26380,
"s": 26367,
"text": "Examples : "
},
{
"code": null,
"e": 26521,
"s": 26380,
"text": "Input : n = 3, m = 1\nOutput : 4\nPlease see above diagram (There\nare 4 permutations where 1 no. is\ngreater.\n\nInput : n = 4, m = 1\nOutput : 11"
},
{
"code": null,
"e": 26605,
"s": 26521,
"text": "Eulerian Numbers are the coefficients of the Eulerian polynomials described below. "
},
{
"code": null,
"e": 26682,
"s": 26605,
"text": "The Eulerian polynomials are defined by the exponential generating function "
},
{
"code": null,
"e": 26742,
"s": 26682,
"text": "The Eulerian polynomials can be computed by the recurrence "
},
{
"code": null,
"e": 26780,
"s": 26744,
"text": "An explicit formula for A(n, m) is "
},
{
"code": null,
"e": 26830,
"s": 26780,
"text": "We can calculate A(n, m) by recurrence relation: "
},
{
"code": null,
"e": 27196,
"s": 26830,
"text": "Example: Suppose, n = 3 and m = 1. Therefore, A(3, 1) = (3 – 1) * A(2, 0) + (1 + 1) * A(2, 1) = 2 * A(2, 0) + 2 * A(2, 1) = 2 * 1 + 2 * ( (2 – 1) * A(1, 0) + (1 + 1) * A(1, 1)) = 2 + 2 * (1 * 1 + 2 * ((1 – 1) * A(0, 0) + (1 + 1) * A(0, 1)) = 2 + 2 * (1 + 2 * (0 * 1 + 2 * 0) = 2 + 2 * (1 + 2 * 0) = 2 + 2 * 1 = 2 + 2 = 4 We can verify this with example shown above."
},
{
"code": null,
"e": 27246,
"s": 27196,
"text": "Below is the implementation of finding A(n, m): "
},
{
"code": null,
"e": 27250,
"s": 27246,
"text": "C++"
},
{
"code": null,
"e": 27255,
"s": 27250,
"text": "Java"
},
{
"code": null,
"e": 27263,
"s": 27255,
"text": "Python3"
},
{
"code": null,
"e": 27266,
"s": 27263,
"text": "C#"
},
{
"code": null,
"e": 27270,
"s": 27266,
"text": "PHP"
},
{
"code": null,
"e": 27281,
"s": 27270,
"text": "Javascript"
},
{
"code": "// CPP Program to find Eulerian number A(n, m)#include <bits/stdc++.h>using namespace std; // Return euleriannumber A(n, m)int eulerian(int n, int m){ if (m >= n || n == 0) return 0; if (m == 0) return 1; return (n - m) * eulerian(n - 1, m - 1) + (m + 1) * eulerian(n - 1, m);} // Driven Programint main(){ int n = 3, m = 1; cout << eulerian(n, m) << endl; return 0;}",
"e": 27693,
"s": 27281,
"text": null
},
{
"code": "// Java program to find Eulerian number A(n, m)import java.util.*; class Eulerian{ // Return eulerian number A(n, m) public static int eulerian(int n, int m) { if (m >= n || n == 0) return 0; if (m == 0) return 1; return (n - m) * eulerian(n - 1, m - 1) + (m + 1) * eulerian(n - 1, m); } // driver code public static void main(String[] args) { int n = 3, m = 1; System.out.print( eulerian(n, m) ); }} // This code is contributed by rishabh_jain",
"e": 28240,
"s": 27693,
"text": null
},
{
"code": "# Python3 Program to find Eulerian number A(n, m) # Return euleriannumber A(n, m)def eulerian(n, m): if (m >= n or n == 0): return 0; if (m == 0): return 1; return ((n - m) * eulerian(n - 1, m - 1) + (m + 1) * eulerian(n - 1, m)) # Driver coden = 3m = 1print( eulerian(n, m) ) # This code is contributed by rishabh_jain",
"e": 28596,
"s": 28240,
"text": null
},
{
"code": "// C# program to find Eulerian number A(n, m)using System; class Eulerian { // Return eulerian number A(n, m) public static int eulerian(int n, int m) { if (m >= n || n == 0) return 0; if (m == 0) return 1; return (n - m) * eulerian(n - 1, m - 1) + (m + 1) * eulerian(n - 1, m); } // driver code public static void Main() { int n = 3, m = 1; Console.WriteLine(eulerian(n, m)); }} // This code is contributed by vt_m",
"e": 29120,
"s": 28596,
"text": null
},
{
"code": "<?php// PHP Program to find// Eulerian number A(n, m) // Return euleriannumber A(n, m)function eulerian($n, $m){ if ($m >= $n || $n == 0) return 0; if ($m == 0) return 1; return ($n - $m) * eulerian($n - 1, $m - 1) + ($m + 1) * eulerian($n - 1, $m);} // Driven Code$n = 3; $m = 1;echo eulerian($n, $m); // This code is contributed by anuj_67.?>",
"e": 29506,
"s": 29120,
"text": null
},
{
"code": "<script> // JavaScript Program to find Eulerian number A(n, m) // Return eulerian number A(n, m) function eulerian(n, m) { if (m >= n || n == 0) return 0; if (m == 0) return 1; return (n - m) * eulerian(n - 1, m - 1) + (m + 1) * eulerian(n - 1, m); } // Driver code let n = 3, m = 1; document.write( eulerian(n, m) ); </script>",
"e": 29948,
"s": 29506,
"text": null
},
{
"code": null,
"e": 29958,
"s": 29948,
"text": "Output : "
},
{
"code": null,
"e": 29960,
"s": 29958,
"text": "4"
},
{
"code": null,
"e": 30035,
"s": 29960,
"text": "Below is the implementation of finding A(n, m) using Dynamic Programming: "
},
{
"code": null,
"e": 30039,
"s": 30035,
"text": "C++"
},
{
"code": null,
"e": 30044,
"s": 30039,
"text": "Java"
},
{
"code": null,
"e": 30052,
"s": 30044,
"text": "Python3"
},
{
"code": null,
"e": 30055,
"s": 30052,
"text": "C#"
},
{
"code": null,
"e": 30059,
"s": 30055,
"text": "PHP"
},
{
"code": null,
"e": 30070,
"s": 30059,
"text": "Javascript"
},
{
"code": "// CPP Program to find Eulerian number A(n, m)#include <bits/stdc++.h>using namespace std; // Return euleriannumber A(n, m)int eulerian(int n, int m){ int dp[n + 1][m + 1]; memset(dp, 0, sizeof(dp)); // For each row from 1 to n for (int i = 1; i <= n; i++) { // For each column from 0 to m for (int j = 0; j <= m; j++) { // If i is greater than j if (i > j) { // If j is 0, then make that // state as 1. if (j == 0) dp[i][j] = 1; // basic recurrence relation. else dp[i][j] = ((i - j) * dp[i - 1][j - 1]) + ((j + 1) * dp[i - 1][j]); } } } return dp[n][m];} // Driven Programint main(){ int n = 3, m = 1; cout << eulerian(n, m) << endl; return 0;}",
"e": 30957,
"s": 30070,
"text": null
},
{
"code": "// Java program to find Eulerian number A(n, m)import java.util.*; class Eulerian{ // Return euleriannumber A(n, m) public static int eulerian(int n, int m) { int[][] dp = new int[n+1][m+1]; // For each row from 1 to n for (int i = 1; i <= n; i++) { // For each column from 0 to m for (int j = 0; j <= m; j++) { // If i is greater than j if (i > j) { // If j is 0, then make // that state as 1. if (j == 0) dp[i][j] = 1; // basic recurrence relation. else dp[i][j] = ((i - j) * dp[i - 1][j - 1]) + ((j + 1) * dp[i - 1][j]); } } } return dp[n][m]; } // driver code public static void main(String[] args) { int n = 3, m = 1; System.out.print( eulerian(n, m) ); }} // This code is contributed by rishabh_jain",
"e": 32020,
"s": 30957,
"text": null
},
{
"code": "# Python3 Program to find Eulerian# number A(n, m) # Return euleriannumber A(n, m)def eulerian(n, m): dp = [[0 for x in range(m+1)] for y in range(n+1)] # For each row from 1 to n for i in range(1, n+1): # For each column from 0 to m for j in range(0, m+1): # If i is greater than j if (i > j): # If j is 0, then make that # state as 1. if (j == 0): dp[i][j] = 1 # basic recurrence relation. else : dp[i][j] = (((i - j) * dp[i - 1][j - 1]) + ((j + 1) * dp[i - 1][j])) return dp[n][m] # Driven Programn = 3m = 1print(eulerian(n, m)) # This code is contributed by Prasad Kshirsagar",
"e": 32843,
"s": 32020,
"text": null
},
{
"code": "// C# program to find Eulerian number A(n, m)using System; class Eulerian { // Return euleriannumber A(n, m) public static int eulerian(int n, int m) { int[, ] dp = new int[n + 1, m + 1]; // For each row from 1 to n for (int i = 1; i <= n; i++) { // For each column from 0 to m for (int j = 0; j <= m; j++) { // If i is greater than j if (i > j) { // If j is 0, then make // that state as 1. if (j == 0) dp[i, j] = 1; // basic recurrence relation. else dp[i, j] = ((i - j) * dp[i - 1, j - 1]) + ((j + 1) * dp[i - 1, j]); } } } return dp[n, m]; } // driver code public static void Main() { int n = 3, m = 1; Console.WriteLine(eulerian(n, m)); }} // This code is contributed by vt_m",
"e": 33867,
"s": 32843,
"text": null
},
{
"code": "<?php// PHP Program to find Eulerian// number A(n, m) // Return euleriannumber A(n, m)function eulerian($n, $m){ $dp = array(array()); for ($i = 0; $i < $n + 1; $i++) for($j = 0; $j < $m + 1; $j++) $dp[$i][$j] = 0 ; // For each row from 1 to n for ($i = 1; $i <= $n; $i++) { // For each column from 0 to m for ($j = 0; $j <= $m; $j++) { // If i is greater than j if ($i > $j) { // If j is 0, then make that // state as 1. if ($j == 0) $dp[$i][$j] = 1; // basic recurrence relation. else $dp[$i][$j] = (($i - $j) * $dp[$i - 1][$j - 1]) + (($j + 1) * $dp[$i - 1][$j]); } } } return $dp[$n][$m];} // Driver Code$n = 3 ;$m = 1;echo eulerian($n, $m) ; // This code is contributed by Ryuga?>",
"e": 34856,
"s": 33867,
"text": null
},
{
"code": "<script> // Javascript Program to find// Eulerian number A(n, m) // Return euleriannumber A(n, m)function eulerian(n, m){ var dp = Array.from(Array(n+1), ()=> Array(m+1).fill(0)); // For each row from 1 to n for (var i = 1; i <= n; i++) { // For each column from 0 to m for (var j = 0; j <= m; j++) { // If i is greater than j if (i > j) { // If j is 0, then make that // state as 1. if (j == 0) dp[i][j] = 1; // basic recurrence relation. else dp[i][j] = ((i - j) * dp[i - 1][j - 1]) + ((j + 1) * dp[i - 1][j]); } } } return dp[n][m];} // Driven Programvar n = 3, m = 1;document.write( eulerian(n, m) ); </script>",
"e": 35701,
"s": 34856,
"text": null
},
{
"code": null,
"e": 35712,
"s": 35701,
"text": "Output : "
},
{
"code": null,
"e": 35714,
"s": 35712,
"text": "4"
},
{
"code": null,
"e": 35721,
"s": 35716,
"text": "vt_m"
},
{
"code": null,
"e": 35739,
"s": 35721,
"text": "Prasad_Kshirsagar"
},
{
"code": null,
"e": 35747,
"s": 35739,
"text": "ankthon"
},
{
"code": null,
"e": 35757,
"s": 35747,
"text": "sanjoy_62"
},
{
"code": null,
"e": 35766,
"s": 35757,
"text": "noob2000"
},
{
"code": null,
"e": 35782,
"s": 35766,
"text": "simranarora5sos"
},
{
"code": null,
"e": 35796,
"s": 35782,
"text": "number-theory"
},
{
"code": null,
"e": 35810,
"s": 35796,
"text": "Combinatorial"
},
{
"code": null,
"e": 35830,
"s": 35810,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 35844,
"s": 35830,
"text": "number-theory"
},
{
"code": null,
"e": 35864,
"s": 35844,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 35878,
"s": 35864,
"text": "Combinatorial"
},
{
"code": null,
"e": 35976,
"s": 35878,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35994,
"s": 35976,
"text": "Combinational Sum"
},
{
"code": null,
"e": 36049,
"s": 35994,
"text": "Count ways to reach the nth stair using step 1, 2 or 3"
},
{
"code": null,
"e": 36134,
"s": 36049,
"text": "Print all possible strings of length k that can be formed from a set of n characters"
},
{
"code": null,
"e": 36171,
"s": 36134,
"text": "Count of subsets with sum equal to X"
},
{
"code": null,
"e": 36228,
"s": 36171,
"text": "Python program to get all subsets of given size of a set"
},
{
"code": null,
"e": 36257,
"s": 36228,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 36289,
"s": 36257,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 36323,
"s": 36289,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 36354,
"s": 36323,
"text": "Bellman–Ford Algorithm | DP-23"
}
] |
Python | Merging two list of dictionaries - GeeksforGeeks
|
12 Oct, 2021
Given two list of dictionaries, the task is to merge these two lists of dictionaries based on some value.
Method #1: Using defaultdict and extend to merge two list of dictionaries based on school_id.
# Python code to merge two list of dictionaries # based on some value. from collections import defaultdict # List initializationInput1 = [{'roll_no': ['123445', '1212'], 'school_id': 1}, {'roll_no': ['HA-4848231'], 'school_id': 2}] Input2 = [{'roll_no': ['473427'], 'school_id': 2}, {'roll_no': ['092112'], 'school_id': 5}] # Using defaultdicttemp = defaultdict(list) # Using extendfor elem in Input1: temp[elem['school_id']].extend(elem['roll_no']) for elem in Input2: temp[elem['school_id']].extend(elem['roll_no']) Output = [{"roll_no":y, "school_id":x} for x, y in temp.items()] # printingprint(Output)
[{‘school_id’: 1, ‘roll_no’: [‘123445’, ‘1212’]}, {‘school_id’: 2, ‘roll_no’: [‘HA-4848231’, ‘473427’]}, {‘school_id’: 5, ‘roll_no’: [‘092112’]}]
Method #2: Using extend() only.
# Python code to merge two list of dictionaries # based on some value. # List initializationInput1 = [{'roll_no': ['123445', '1212'], 'school_id': 1}, {'roll_no': ['HA-4848231'], 'school_id': 2}]Input2 = [{'roll_no': ['473427'], 'school_id': 2}, {'roll_no': ['092112'], 'school_id': 5}] # Iterating and using extend to convertfor elm2 in Input2: for elm1 in Input1: if elm2['school_id'] == elm1['school_id']: elm1['roll_no'].extend(elm2['roll_no']) break else: Input1.append(elm2) # printing print(Input1)
[{‘school_id’: 1, ‘roll_no’: [‘123445’, ‘1212’]}, {‘school_id’: 2, ‘roll_no’: [‘HA-4848231’, ‘473427’]}, {‘school_id’: 5, ‘roll_no’: [‘092112’]}]
Akanksha_Rai
gabaa406
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 26173,
"s": 26145,
"text": "\n12 Oct, 2021"
},
{
"code": null,
"e": 26279,
"s": 26173,
"text": "Given two list of dictionaries, the task is to merge these two lists of dictionaries based on some value."
},
{
"code": null,
"e": 26373,
"s": 26279,
"text": "Method #1: Using defaultdict and extend to merge two list of dictionaries based on school_id."
},
{
"code": "# Python code to merge two list of dictionaries # based on some value. from collections import defaultdict # List initializationInput1 = [{'roll_no': ['123445', '1212'], 'school_id': 1}, {'roll_no': ['HA-4848231'], 'school_id': 2}] Input2 = [{'roll_no': ['473427'], 'school_id': 2}, {'roll_no': ['092112'], 'school_id': 5}] # Using defaultdicttemp = defaultdict(list) # Using extendfor elem in Input1: temp[elem['school_id']].extend(elem['roll_no']) for elem in Input2: temp[elem['school_id']].extend(elem['roll_no']) Output = [{\"roll_no\":y, \"school_id\":x} for x, y in temp.items()] # printingprint(Output)",
"e": 27016,
"s": 26373,
"text": null
},
{
"code": null,
"e": 27162,
"s": 27016,
"text": "[{‘school_id’: 1, ‘roll_no’: [‘123445’, ‘1212’]}, {‘school_id’: 2, ‘roll_no’: [‘HA-4848231’, ‘473427’]}, {‘school_id’: 5, ‘roll_no’: [‘092112’]}]"
},
{
"code": null,
"e": 27195,
"s": 27162,
"text": " Method #2: Using extend() only."
},
{
"code": "# Python code to merge two list of dictionaries # based on some value. # List initializationInput1 = [{'roll_no': ['123445', '1212'], 'school_id': 1}, {'roll_no': ['HA-4848231'], 'school_id': 2}]Input2 = [{'roll_no': ['473427'], 'school_id': 2}, {'roll_no': ['092112'], 'school_id': 5}] # Iterating and using extend to convertfor elm2 in Input2: for elm1 in Input1: if elm2['school_id'] == elm1['school_id']: elm1['roll_no'].extend(elm2['roll_no']) break else: Input1.append(elm2) # printing print(Input1)",
"e": 27767,
"s": 27195,
"text": null
},
{
"code": null,
"e": 27913,
"s": 27767,
"text": "[{‘school_id’: 1, ‘roll_no’: [‘123445’, ‘1212’]}, {‘school_id’: 2, ‘roll_no’: [‘HA-4848231’, ‘473427’]}, {‘school_id’: 5, ‘roll_no’: [‘092112’]}]"
},
{
"code": null,
"e": 27926,
"s": 27913,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 27935,
"s": 27926,
"text": "gabaa406"
},
{
"code": null,
"e": 27962,
"s": 27935,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 27969,
"s": 27962,
"text": "Python"
},
{
"code": null,
"e": 27985,
"s": 27969,
"text": "Python Programs"
},
{
"code": null,
"e": 28083,
"s": 27985,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28101,
"s": 28083,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28136,
"s": 28101,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28168,
"s": 28136,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28190,
"s": 28168,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28232,
"s": 28190,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28275,
"s": 28232,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28297,
"s": 28275,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28336,
"s": 28297,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28382,
"s": 28336,
"text": "Python | Split string into list of characters"
}
] |
Difference between Storage Area Network (SAN) and Network Attached Storage (NAS) - GeeksforGeeks
|
22 Apr, 2022
Storage Area Network (SAN): Storage Area Network (SAN) is used for transferring the data between the servers and the storage devices fiber channel and switches. In SAN (Storage Area Network), Data is identified by disk block. Protocols that are used in SAN are: SCSI, SATA etc. Components of Storage Area Network (SAN):
1. Node ports
2. Cables
3. Interconnect device such as: Hubs, switches, directors
4. Storage arrays
5. SAN management Software
Network Attached Storage (NAS): In Network Attached Storage (NAS), data is identified by file name as well as byte offset. In Network Attached Storage, File system is managed by Head unit such as CPU and Memory. In this for backup and recovery, files are used instead of block by block copying technique. Components of Network Attached Storage (NAS):
1. Head unit: CPU, Memory
2. Network Interface Card (NIC)
3. Optimized operating system
4. Protocols
5. Storage protocols: ATA, SCSI,FC
Difference between Storage Area Network (SAN) and Network Attached Storage (NAS):
ashushrma378
manmeetjuneja5
Computer Networks
Difference Between
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
RSA Algorithm in Cryptography
TCP Server-Client implementation in C
Differences between TCP and UDP
Data encryption standard (DES) | Set 1
Types of Network Topology
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Differences between Black Box Testing vs White Box Testing
|
[
{
"code": null,
"e": 24436,
"s": 24408,
"text": "\n22 Apr, 2022"
},
{
"code": null,
"e": 24756,
"s": 24436,
"text": "Storage Area Network (SAN): Storage Area Network (SAN) is used for transferring the data between the servers and the storage devices fiber channel and switches. In SAN (Storage Area Network), Data is identified by disk block. Protocols that are used in SAN are: SCSI, SATA etc. Components of Storage Area Network (SAN):"
},
{
"code": null,
"e": 24884,
"s": 24756,
"text": "1. Node ports\n2. Cables\n3. Interconnect device such as: Hubs, switches, directors\n4. Storage arrays\n5. SAN management Software "
},
{
"code": null,
"e": 25235,
"s": 24884,
"text": "Network Attached Storage (NAS): In Network Attached Storage (NAS), data is identified by file name as well as byte offset. In Network Attached Storage, File system is managed by Head unit such as CPU and Memory. In this for backup and recovery, files are used instead of block by block copying technique. Components of Network Attached Storage (NAS):"
},
{
"code": null,
"e": 25372,
"s": 25235,
"text": "1. Head unit: CPU, Memory\n2. Network Interface Card (NIC)\n3. Optimized operating system\n4. Protocols\n5. Storage protocols: ATA, SCSI,FC "
},
{
"code": null,
"e": 25454,
"s": 25372,
"text": "Difference between Storage Area Network (SAN) and Network Attached Storage (NAS):"
},
{
"code": null,
"e": 25467,
"s": 25454,
"text": "ashushrma378"
},
{
"code": null,
"e": 25482,
"s": 25467,
"text": "manmeetjuneja5"
},
{
"code": null,
"e": 25500,
"s": 25482,
"text": "Computer Networks"
},
{
"code": null,
"e": 25519,
"s": 25500,
"text": "Difference Between"
},
{
"code": null,
"e": 25537,
"s": 25519,
"text": "Computer Networks"
},
{
"code": null,
"e": 25635,
"s": 25537,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25644,
"s": 25635,
"text": "Comments"
},
{
"code": null,
"e": 25657,
"s": 25644,
"text": "Old Comments"
},
{
"code": null,
"e": 25687,
"s": 25657,
"text": "RSA Algorithm in Cryptography"
},
{
"code": null,
"e": 25725,
"s": 25687,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 25757,
"s": 25725,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 25796,
"s": 25757,
"text": "Data encryption standard (DES) | Set 1"
},
{
"code": null,
"e": 25822,
"s": 25796,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 25853,
"s": 25822,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 25893,
"s": 25853,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 25925,
"s": 25893,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 25986,
"s": 25925,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
How to check privileges in MySQL?
|
To check privileges, use SHOW command with GRANTS. Following is the syntax −
SHOW GRANTS;
The above syntax will show privileges for root. If you want to check privileges for a specific user,
then use the below syntax −
SHOW GRANTS FOR 'yourUserName'@'yourHostName';
The above syntax will check privileges for a specific user.
Let us implement both the syntaxes one by one. Following is the query −
mysql> SHOW GRANTS;
The following is the output that displays root privileges −
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Grants for root@%
|
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, SHUTDOWN, PROCESS, FILE, REFERENCES, INDEX, ALTER, SHOW DATABASES, SUPER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, EVENT, TRIGGER, CREATE TABLESPACE, CREATE ROLE, DROP ROLE ON *.* TO `root`@`%` WITH GRANT OPTION |
| GRANT BACKUP_ADMIN,BINLOG_ADMIN,CONNECTION_ADMIN,ENCRYPTION_KEY_ADMIN,GROUP_REPLICATION_ADMIN,PERSIST_RO_VARIABLES_ADMIN,REPLICATION_SLAVE_ADMIN,RESOURCE_GROUP_ADMIN,RESOURCE_GROUP_USER,ROLE_ADMIN,SET_USER_ID,SYSTEM_VARIABLES_ADMIN,XA_RECOVER_ADMIN ON *.* TO `root`@`%`|
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.08 sec)
If you want to check the privileges for a specific user, then use FOR. Let’s say we have a username ‘Bob’ and host is ‘%’. Following is the query to get the privileges for user “BOB” −
mysql> SHOW GRANTS FOR 'Bob'@'%';
This will produce the following output −
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Grants for Bob@%
|
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, SHUTDOWN, PROCESS, FILE, REFERENCES, INDEX, ALTER, SHOW DATABASES, SUPER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, EVENT, TRIGGER, CREATE TABLESPACE, CREATE ROLE, DROP ROLE ON *.* TO `Bob`@`%` WITH GRANT OPTION |
| GRANT BACKUP_ADMIN,BINLOG_ADMIN,CONNECTION_ADMIN,ENCRYPTION_KEY_ADMIN,GR OUP_REPLICATION_ADMIN,PERSIST_RO_VARIABLES_ADMIN,REPLICATION_SLAVE_A DMIN,RESOURCE_GROUP_ADMIN,RESOURCE_GROUP_USER,ROLE_ADMIN,SET_USE R_ID,SYSTEM_VARIABLES_ADMIN,XA_RECOVER_ADMIN ON *.* TO `Bob`@`%` WITH GRANT OPTION |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1139,
"s": 1062,
"text": "To check privileges, use SHOW command with GRANTS. Following is the syntax −"
},
{
"code": null,
"e": 1152,
"s": 1139,
"text": "SHOW GRANTS;"
},
{
"code": null,
"e": 1281,
"s": 1152,
"text": "The above syntax will show privileges for root. If you want to check privileges for a specific user,\nthen use the below syntax −"
},
{
"code": null,
"e": 1328,
"s": 1281,
"text": "SHOW GRANTS FOR 'yourUserName'@'yourHostName';"
},
{
"code": null,
"e": 1388,
"s": 1328,
"text": "The above syntax will check privileges for a specific user."
},
{
"code": null,
"e": 1460,
"s": 1388,
"text": "Let us implement both the syntaxes one by one. Following is the query −"
},
{
"code": null,
"e": 1480,
"s": 1460,
"text": "mysql> SHOW GRANTS;"
},
{
"code": null,
"e": 1540,
"s": 1480,
"text": "The following is the output that displays root privileges −"
},
{
"code": null,
"e": 3416,
"s": 1540,
"text": "+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| Grants for root@%\n|\n+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, SHUTDOWN, PROCESS, FILE, REFERENCES, INDEX, ALTER, SHOW DATABASES, SUPER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, EVENT, TRIGGER, CREATE TABLESPACE, CREATE ROLE, DROP ROLE ON *.* TO `root`@`%` WITH GRANT OPTION |\n| GRANT BACKUP_ADMIN,BINLOG_ADMIN,CONNECTION_ADMIN,ENCRYPTION_KEY_ADMIN,GROUP_REPLICATION_ADMIN,PERSIST_RO_VARIABLES_ADMIN,REPLICATION_SLAVE_ADMIN,RESOURCE_GROUP_ADMIN,RESOURCE_GROUP_USER,ROLE_ADMIN,SET_USER_ID,SYSTEM_VARIABLES_ADMIN,XA_RECOVER_ADMIN ON *.* TO `root`@`%`|\n+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n2 rows in set (0.08 sec)"
},
{
"code": null,
"e": 3601,
"s": 3416,
"text": "If you want to check the privileges for a specific user, then use FOR. Let’s say we have a username ‘Bob’ and host is ‘%’. Following is the query to get the privileges for user “BOB” −"
},
{
"code": null,
"e": 3635,
"s": 3601,
"text": "mysql> SHOW GRANTS FOR 'Bob'@'%';"
},
{
"code": null,
"e": 3676,
"s": 3635,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 5567,
"s": 3676,
"text": "+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| Grants for Bob@%\n|\n+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, SHUTDOWN, PROCESS, FILE, REFERENCES, INDEX, ALTER, SHOW DATABASES, SUPER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, EVENT, TRIGGER, CREATE TABLESPACE, CREATE ROLE, DROP ROLE ON *.* TO `Bob`@`%` WITH GRANT OPTION |\n| GRANT BACKUP_ADMIN,BINLOG_ADMIN,CONNECTION_ADMIN,ENCRYPTION_KEY_ADMIN,GR OUP_REPLICATION_ADMIN,PERSIST_RO_VARIABLES_ADMIN,REPLICATION_SLAVE_A DMIN,RESOURCE_GROUP_ADMIN,RESOURCE_GROUP_USER,ROLE_ADMIN,SET_USE R_ID,SYSTEM_VARIABLES_ADMIN,XA_RECOVER_ADMIN ON *.* TO `Bob`@`%` WITH GRANT OPTION |\n+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n2 rows in set (0.00 sec)"
}
] |
Preprocessing text in Python. A step towards building a sentiment... | by Zolzaya Luvsandorj | Towards Data Science
|
This post is the second of three sequential posts on steps to build a sentiment classifier. Following our exploratory text analysis in the first post, it’s time to preprocess our text data. Simply put, preprocessing text data is to do a series of operations to convert the text into a tabular numeric data. In this post, we will look at 3 ways with varying complexity to preprocess text to tf-idf matrix as preparation for a model. If you are unsure what tf-idf is, this post explains with a simple example.
Before we dive in, let’s take a step back and look at the bigger picture real quickly. CRISP-DM methodology outlines the process flow for a successful data science project. Preprocessing data is one of the key tasks in the data preparation stage.
This post assumes that the reader (👀 yes, you!) has access to and is familiar with Python including installing packages, defining functions and other basic tasks. If you are new to Python, this is a good place to get started.
I have tested the scripts in Python 3.7.1 in Jupyter Notebook.
Let’s make sure you have the following libraries installed before we start:◼️ Data manipulation/analysis: numpy, pandas◼️ Data partitioning: sklearn◼️ Text preprocessing/analysis: nltk◼️ Spelling checker: spellchecker (pyspellchecker when installing)
Once you have nltk installed, please make sure you have downloaded ‘stopwords’ and ‘wordnet’ corpora from nltk with the script below:
import nltknltk.download('stopwords') nltk.download('wordnet')
If you have already downloaded, running this will notify you so.
Now, we are ready to import all the packages:
# Setting random seedseed = 123# Measuring run timefrom time import time# Data manipulation/analysisimport numpy as npimport pandas as pd# Data partitioningfrom sklearn.model_selection import train_test_split# Text preprocessing/analysisimport re, randomfrom nltk import word_tokenize, sent_tokenize, pos_tagfrom nltk.util import ngramsfrom nltk.corpus import stopwordsfrom nltk.stem import WordNetLemmatizerfrom nltk.tokenize import RegexpTokenizerfrom sklearn.feature_extraction.text import TfidfVectorizerfrom spellchecker import SpellChecker
We will use IMDB movie reviews dataset. You can download the dataset here and save it in your working directory. Once saved, let’s import it to Python:
sample = pd.read_csv('IMDB Dataset.csv')print(f"{sample.shape[0]} rows and {sample.shape[1]} columns")sample.head()
Let’s look at the split between sentiments:
sample['sentiment'].value_counts()
Sentiment is evenly split in the sample data. Let’s first partition the data into two sets: train and test. We will set aside 5000 cases for testing:
# Split data into train & testX_train, X_test, y_train, y_test = train_test_split(sample['review'], sample['sentiment'], test_size=5000, random_state=seed, stratify=sample['sentiment'])# Append sentiment back using indicestrain = pd.concat([X_train, y_train], axis=1)test = pd.concat([X_test, y_test], axis=1)# Check dimensionsprint(f"Train: {train.shape[0]} rows and {train.shape[1]} columns")print(f"{train['sentiment'].value_counts()}\n")print(f"Test: {test.shape[0]} rows and {test.shape[1]} columns")print(test['sentiment'].value_counts())
We will be using train for the preprocessing experiments in this post. We will preprocess the test only when we need to assess the final model. Let’s inspect the head of the training dataset:
train.head()
Alright, let’s start preprocessing! ✨
Depending on how we process, we could arrive at different tf-idf matrices. When building a model, it’s good to try out different ways of preprocessing. We will look at the following 3 approaches:
Simpler approachSimple approachLess simple approach
Simpler approach
Simple approach
Less simple approach
Although we are only looking at preprocessing text to tf-idf matrix in this post, you may also want to explore other alternatives.
For each approach, we will be sure to measure run time performance since it is an important consideration especially if the model is going to be productionised. We will test which approach works better with the model in the next post. Before we dive in, to make things easier, let’s define a function that help us inspect the different approaches:
def inspect(vectoriser, X): # Fit and transform start = time() print(f"There are {vectoriser.fit_transform(X).shape[1]} columns.\n") end = time() print(f"Took {round((end-start),2)} seconds.\n") # Inspect tokens tokens = list(vectoriser.vocabulary_.keys()) tokens.sort() print(f"Example tokens: {tokens[:50]}\n") # Inspect ignored tokens ignored = vectoriser.stop_words_ if len(ignored)==0: print("No token is ignored.") elif len(ignored)>50: print(f"Example ignored tokens: {random.sample(ignored, 50)}") else: print(f"Example ignored tokens: {ignored}")
Let’s start with the simplest of the three. In this approach, we will let sklearn’s TfidfVectorizer do all the preprocessing without using any additional custom functions. Let’s use the default parameters to get a feel of how many columns we will get:
vectoriser = TfidfVectorizer()inspect(vectoriser, X_train)
It was pretty quick. The output has over 97 thousand columns and the first 50 tokens are mostly numbers. Now, let’s tweak a few of the parameters to clean up the tokens further and better control the preprocessing:
# Simpler approachvectoriser = TfidfVectorizer(token_pattern=r'[a-z]+', stop_words='english', min_df=30, max_df=.7)inspect(vectoriser, X_train)
While the two versions above take about the same time, the number of columns are 7–8 times lower in the latter. Here, we have asked TfidfVectorizer to do a few things:◼ token_pattern=r'[a-z]+': tokenise into alphabetic tokens - this means we discard numbers and punctuation. If you are not familiar with regular expression, [a-z]+ means a token must consist of only letters. ◼ stop_words='english’: remove stop words.◼ min_df=30: remove rare tokens. We are considering a token as rare when it’s in less than 30 reviews. This will shrink the number of tokens significantly. Try running the script without this parameter and see the number of tokens.◼ max_df=.7: remove tokens that are in more than 70% of the documents. This means if a token is contained in more than 31.5K reviews, then we are ignoring them. There aren’t actually many words excluded because of this. So, we could even keep this feature to its default.
max_df and min_df help with token selection. In other words, with the help of these two, we can drop tokens that are either too frequent that may not be useful in classifying sentiments or too rare that may contribute to overfitting.
📍 Here’s a tip: If we define the parameters like this:
TfidfVectorizer(token_pattern=r'[a-z]+', max_df=.5)
you can find out what tokens were excluded because of max_df=.5 condition by running vectoriser.stop_words_ after fitting the vectoriser. When we call inspect function, the ‘example ignored tokens’ part of the output shows a snippet of those excluded words. Now, I encourage you to run the script above and check vectoriser.stop_words_. What do you see? Do you see mostly stop words? Try changing the values to .5, .6, .8 or .9 and rerun to observe how the excluded words change. It helps to understand how tweaking certain parameters impacts the preprocessing. Now, if you are keen, add stop_words='english’ or min_df=30 (don’t add both at the same time, add one at a time to understand individual parameters) and check out what tokens were excluded this time. We will tune these parameters further when building a model in the next post.
🔗 If you are keen to learn more about parameters , the documentation is here.
This approach was a 🍰, wasn’t it? I like this approach especially because it does a few basic things really well and quick. In my opinion, it’s always good to start simple and add complexity only if it improves performance.
There is always room for improvement. For instance, the word ‘play’, ‘plays’, ‘playing’ and ‘played’ are considered as 4 different tokens in previous approach. Wouldn’t it be great if we remove these inflectional endings so that these tokens are normalised into 1 unique token, ‘play’? That is what we are going to do in the this section!
To normalise inflectional endings, we will use a technique called lemmatisation. Another alternative is stemming. If you want to learn the difference between these two, I have briefly explained the difference here.
Lemmatisation helps convert words to their dictionary form. Taking our previous example, let’s lemmatise them and see how the output looks like:
lemmatiser = WordNetLemmatizer()for word in ['play', 'plays', 'playing', 'played']: print(lemmatiser.lemmatize(word, 'v'))
Cool, all words are now converted to ‘play’. Notice how we passed ‘v’ as the second argument in lemmatize method? The ‘v’ is a part-of-speech tag. Accurate lemmatisation, in fact, depends on the part-of-speech (POS) tag we provide to the lemmatiser along with the word. To demonstrate this, let’s rerun the previous script with one small change where ‘v’ becomes ‘n’:
lemmatiser = WordNetLemmatizer()for word in ['plays', 'playing', 'played']: print(lemmatiser.lemmatize(word, 'n'))
This time, not all words have been converted to play. This brief example shows how a part-of-speech tag can impact the effectiveness of the lemmatisation. So what exactly is a part-of-speech tag? Simply put, it refers to a grammatical category of the the word. The word ‘movie’ is a noun and ‘watch’ can be either a verb or a noun depending on the context. Nouns and verbs are examples of part-of-speech. In the first run, we told the lemmatiser that the words provided are verbs (hence ‘v’) and in the second run, nouns (hence ‘n’). Using nltk’s part-of-speech tagger: pos_tag(), we can tag each word with its part-of-speech.
We will shortly create a custom function that does part-of-speech tagging and lemmatisation based on the tags. We will pass this function to the analyzer parameter of TdidfVectoriser(). When we do this, some of the parameters used previously such as token_pattern, stop_words would no longer be supported. Thus, we have to also include a tokenising step in our custom function:
def preprocess_text(text): # 1. Tokenise to alphabetic tokens tokeniser = RegexpTokenizer(r'[A-Za-z]+') tokens = tokeniser.tokenize(text) # 2. POS tagging pos_map = {'J': 'a', 'N': 'n', 'R': 'r', 'V': 'v'} pos_tags = pos_tag(tokens) # 3. Lowercase and lemmatise lemmatiser = WordNetLemmatizer() tokens = [lemmatiser.lemmatize(t.lower(), pos=pos_map.get(p[0], 'v')) for t, p in pos_tags]return tokens
One thing to note here is that pos_tag() and lemmatiser.lemmatize() use different naming conventions for part-of-speech tags, so we had to map the part-of-speech produced by the nltk tagger to the names that the lemmatiser can understand. That’s why we have pos_map. Now, let’s preprocess the data and assess:
vectoriser = TfidfVectorizer(analyzer=preprocess_text, min_df=30, max_df=.7)inspect(vectoriser, X_train)
It reduced the number of columns to 10,754. That’s about 16% reduction in the number of columns compared to 12,805 columns in simpler approach. It took about 11 minutes on my computer which is ~85 times slower. If we think about it, lemmatisation is not going to alter every word in a review. Let’s take ‘The movie was awesome.’ sentence as an example. The only word would benefit from a lemmatisation is ‘was’. So keeping this in mind, sometimes it’s fine to use a default part-of-speech for all words if you need to do lemmatisation quicker. In that case, our custom function simplifies to:
# Simple approachdef preprocess_text(text): # 1. Tokenise to alphabetic tokens tokeniser = RegexpTokenizer(r'[A-Za-z]+') tokens = tokeniser.tokenize(text) # 2. Lowercase and lemmatise lemmatiser = WordNetLemmatizer() tokens = [lemmatiser.lemmatize(t.lower(), pos='v') for t in tokens]return tokensvectoriser = TfidfVectorizer(analyzer=preprocess_text, min_df=30, max_df=.7)inspect(vectoriser, X_train)
The number of columns is very close to the version we used part-of-speech tagger but it only took about a minute. So between these two versions, I prefer using the default part-of-speech tag over the other for this text dataset. Of note, if we don’t provide a value to the pos argument, the lemmatiser defaults to ’n’. Generally speaking, I usually like to use ‘v’ as a default because I find that it normalises more words in general. However, the more suitable default pos will depend on the data.
In this approach, we will further clean up the data. Based on the learnings from the exploratory data analysis and general preprocessing ideas, here’s what we’ll do:
◼ Correct typos: ‘chracter’ to ‘character’◼ Convert British spelling to American spelling: ‘realise’ to ‘realize’◼ Remove stop words
def convert_to_american(token): # Copied from here token = re.sub(r"(...)our$", r"\1or", token) token = re.sub(r"([bt])re$", r"\1er", token) token = re.sub(r"([iy])s(e$|ing|ation)", r"\1z\2", token) token = re.sub(r"ogue$", "og", token) return tokendef correct_typo(tokens): spell = SpellChecker() return [spell.correction(t) if len(spell.unknown([t]))>0 else t for t in tokens] def preprocess_text(text): # 1. Tokenise to alphabetic tokens tokeniser = RegexpTokenizer(r'[A-Za-z]+') tokens = tokeniser.tokenize(text) # 2. Lowercase and lemmatise lemmatiser = WordNetLemmatizer() tokens = [lemmatiser.lemmatize(t.lower(), pos='v') for t in tokens]# 3. Correct spelling (this won't convert 100% ) tokens = correct_typo(tokens) # 4. Convert British spelling to American spelling (this won't convert 100%) tokens = [convert_to_american(t) for t in tokens]# 5. Remove stopwords stop_words = stopwords.words('english') stop_words.extend(['cannot', 'could', 'done', 'let', 'may' 'mayn', 'might', 'must', 'need', 'ought', 'oughtn', 'shall', 'would', 'br']) tokens = [t for t in tokens if t not in stop_words] return tokens
In addition to these, we could keep adding other layers to correct and clean up. However, each additional step will add complexity and increase run time without a guaranteed improvement in model performance. Here are some ideas you could try in general when preprocessing text which is not particularly useful in our case but could be useful in other cases:
◼ Clean up junks such as html tags, email addresses, URLs ◼ Convert numbers to words instead of dropping them◼ Convert emojis or emoticons to words
Alright, let’s preprocess and inspect the output:
vectoriser = TfidfVectorizer(analyzer=preprocess_text, min_df=30, max_df=.7)inspect(vectoriser, X_train)
A few hours after I started running this code, it was still running. As I deemed it was taking too long, I had to interrupt the kernel to stop the query. To see how much slower this approach takes relative to the previous two, I reduced the size of the dataset to 1/9th of its size with the script below:
train = train.sample(5000, random_state=seed)
And I have ran all three approaches on this smaller subset of data. Here’s the comparison of the three approaches:
The less simple approach standardised the tokens more than the other two but at a really high cost. It takes at least 1000 times longer to preprocess compared to the others. There is a chance that this ratio could look worse when the dataset grows. Hence, it’s not practical to pursue less simple approach further unless it’s optimised to run faster.
👂 If you have a better computer than mine, this run time concern may not necessarily be a constraint for you in which case feel free to pursue further.
Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me.
Thank you for reading my post. Hopefully, you have learned a few different practical ways to preprocess text that you could apply to your next NLP project. In the next post, we will build a sentiment classifier. Here are links to the other two posts of the series:◼️ Exploratory text analysis in Python◼️ Sentiment classification in Python
Here are links to the my other NLP-related posts:◼️ Simple wordcloud in Python(Below lists a series of posts on Introduction to NLP)◼️ Part 1: Preprocessing text in Python◼️ Part 2: Difference between lemmatisation and stemming◼️ Part 3: TF-IDF explained◼️ Part 4: Supervised text classification model in Python◼️ Part 5A: Unsupervised topic model in Python (sklearn)◼️ Part 5B: Unsupervised topic model in Python (gensim)
Bye for now 🏃💨
|
[
{
"code": null,
"e": 679,
"s": 171,
"text": "This post is the second of three sequential posts on steps to build a sentiment classifier. Following our exploratory text analysis in the first post, it’s time to preprocess our text data. Simply put, preprocessing text data is to do a series of operations to convert the text into a tabular numeric data. In this post, we will look at 3 ways with varying complexity to preprocess text to tf-idf matrix as preparation for a model. If you are unsure what tf-idf is, this post explains with a simple example."
},
{
"code": null,
"e": 926,
"s": 679,
"text": "Before we dive in, let’s take a step back and look at the bigger picture real quickly. CRISP-DM methodology outlines the process flow for a successful data science project. Preprocessing data is one of the key tasks in the data preparation stage."
},
{
"code": null,
"e": 1152,
"s": 926,
"text": "This post assumes that the reader (👀 yes, you!) has access to and is familiar with Python including installing packages, defining functions and other basic tasks. If you are new to Python, this is a good place to get started."
},
{
"code": null,
"e": 1215,
"s": 1152,
"text": "I have tested the scripts in Python 3.7.1 in Jupyter Notebook."
},
{
"code": null,
"e": 1466,
"s": 1215,
"text": "Let’s make sure you have the following libraries installed before we start:◼️ Data manipulation/analysis: numpy, pandas◼️ Data partitioning: sklearn◼️ Text preprocessing/analysis: nltk◼️ Spelling checker: spellchecker (pyspellchecker when installing)"
},
{
"code": null,
"e": 1600,
"s": 1466,
"text": "Once you have nltk installed, please make sure you have downloaded ‘stopwords’ and ‘wordnet’ corpora from nltk with the script below:"
},
{
"code": null,
"e": 1663,
"s": 1600,
"text": "import nltknltk.download('stopwords') nltk.download('wordnet')"
},
{
"code": null,
"e": 1728,
"s": 1663,
"text": "If you have already downloaded, running this will notify you so."
},
{
"code": null,
"e": 1774,
"s": 1728,
"text": "Now, we are ready to import all the packages:"
},
{
"code": null,
"e": 2320,
"s": 1774,
"text": "# Setting random seedseed = 123# Measuring run timefrom time import time# Data manipulation/analysisimport numpy as npimport pandas as pd# Data partitioningfrom sklearn.model_selection import train_test_split# Text preprocessing/analysisimport re, randomfrom nltk import word_tokenize, sent_tokenize, pos_tagfrom nltk.util import ngramsfrom nltk.corpus import stopwordsfrom nltk.stem import WordNetLemmatizerfrom nltk.tokenize import RegexpTokenizerfrom sklearn.feature_extraction.text import TfidfVectorizerfrom spellchecker import SpellChecker"
},
{
"code": null,
"e": 2472,
"s": 2320,
"text": "We will use IMDB movie reviews dataset. You can download the dataset here and save it in your working directory. Once saved, let’s import it to Python:"
},
{
"code": null,
"e": 2588,
"s": 2472,
"text": "sample = pd.read_csv('IMDB Dataset.csv')print(f\"{sample.shape[0]} rows and {sample.shape[1]} columns\")sample.head()"
},
{
"code": null,
"e": 2632,
"s": 2588,
"text": "Let’s look at the split between sentiments:"
},
{
"code": null,
"e": 2667,
"s": 2632,
"text": "sample['sentiment'].value_counts()"
},
{
"code": null,
"e": 2817,
"s": 2667,
"text": "Sentiment is evenly split in the sample data. Let’s first partition the data into two sets: train and test. We will set aside 5000 cases for testing:"
},
{
"code": null,
"e": 3414,
"s": 2817,
"text": "# Split data into train & testX_train, X_test, y_train, y_test = train_test_split(sample['review'], sample['sentiment'], test_size=5000, random_state=seed, stratify=sample['sentiment'])# Append sentiment back using indicestrain = pd.concat([X_train, y_train], axis=1)test = pd.concat([X_test, y_test], axis=1)# Check dimensionsprint(f\"Train: {train.shape[0]} rows and {train.shape[1]} columns\")print(f\"{train['sentiment'].value_counts()}\\n\")print(f\"Test: {test.shape[0]} rows and {test.shape[1]} columns\")print(test['sentiment'].value_counts())"
},
{
"code": null,
"e": 3606,
"s": 3414,
"text": "We will be using train for the preprocessing experiments in this post. We will preprocess the test only when we need to assess the final model. Let’s inspect the head of the training dataset:"
},
{
"code": null,
"e": 3619,
"s": 3606,
"text": "train.head()"
},
{
"code": null,
"e": 3657,
"s": 3619,
"text": "Alright, let’s start preprocessing! ✨"
},
{
"code": null,
"e": 3853,
"s": 3657,
"text": "Depending on how we process, we could arrive at different tf-idf matrices. When building a model, it’s good to try out different ways of preprocessing. We will look at the following 3 approaches:"
},
{
"code": null,
"e": 3905,
"s": 3853,
"text": "Simpler approachSimple approachLess simple approach"
},
{
"code": null,
"e": 3922,
"s": 3905,
"text": "Simpler approach"
},
{
"code": null,
"e": 3938,
"s": 3922,
"text": "Simple approach"
},
{
"code": null,
"e": 3959,
"s": 3938,
"text": "Less simple approach"
},
{
"code": null,
"e": 4090,
"s": 3959,
"text": "Although we are only looking at preprocessing text to tf-idf matrix in this post, you may also want to explore other alternatives."
},
{
"code": null,
"e": 4438,
"s": 4090,
"text": "For each approach, we will be sure to measure run time performance since it is an important consideration especially if the model is going to be productionised. We will test which approach works better with the model in the next post. Before we dive in, to make things easier, let’s define a function that help us inspect the different approaches:"
},
{
"code": null,
"e": 5065,
"s": 4438,
"text": "def inspect(vectoriser, X): # Fit and transform start = time() print(f\"There are {vectoriser.fit_transform(X).shape[1]} columns.\\n\") end = time() print(f\"Took {round((end-start),2)} seconds.\\n\") # Inspect tokens tokens = list(vectoriser.vocabulary_.keys()) tokens.sort() print(f\"Example tokens: {tokens[:50]}\\n\") # Inspect ignored tokens ignored = vectoriser.stop_words_ if len(ignored)==0: print(\"No token is ignored.\") elif len(ignored)>50: print(f\"Example ignored tokens: {random.sample(ignored, 50)}\") else: print(f\"Example ignored tokens: {ignored}\")"
},
{
"code": null,
"e": 5317,
"s": 5065,
"text": "Let’s start with the simplest of the three. In this approach, we will let sklearn’s TfidfVectorizer do all the preprocessing without using any additional custom functions. Let’s use the default parameters to get a feel of how many columns we will get:"
},
{
"code": null,
"e": 5376,
"s": 5317,
"text": "vectoriser = TfidfVectorizer()inspect(vectoriser, X_train)"
},
{
"code": null,
"e": 5591,
"s": 5376,
"text": "It was pretty quick. The output has over 97 thousand columns and the first 50 tokens are mostly numbers. Now, let’s tweak a few of the parameters to clean up the tokens further and better control the preprocessing:"
},
{
"code": null,
"e": 5735,
"s": 5591,
"text": "# Simpler approachvectoriser = TfidfVectorizer(token_pattern=r'[a-z]+', stop_words='english', min_df=30, max_df=.7)inspect(vectoriser, X_train)"
},
{
"code": null,
"e": 6655,
"s": 5735,
"text": "While the two versions above take about the same time, the number of columns are 7–8 times lower in the latter. Here, we have asked TfidfVectorizer to do a few things:◼ token_pattern=r'[a-z]+': tokenise into alphabetic tokens - this means we discard numbers and punctuation. If you are not familiar with regular expression, [a-z]+ means a token must consist of only letters. ◼ stop_words='english’: remove stop words.◼ min_df=30: remove rare tokens. We are considering a token as rare when it’s in less than 30 reviews. This will shrink the number of tokens significantly. Try running the script without this parameter and see the number of tokens.◼ max_df=.7: remove tokens that are in more than 70% of the documents. This means if a token is contained in more than 31.5K reviews, then we are ignoring them. There aren’t actually many words excluded because of this. So, we could even keep this feature to its default."
},
{
"code": null,
"e": 6889,
"s": 6655,
"text": "max_df and min_df help with token selection. In other words, with the help of these two, we can drop tokens that are either too frequent that may not be useful in classifying sentiments or too rare that may contribute to overfitting."
},
{
"code": null,
"e": 6944,
"s": 6889,
"text": "📍 Here’s a tip: If we define the parameters like this:"
},
{
"code": null,
"e": 6996,
"s": 6944,
"text": "TfidfVectorizer(token_pattern=r'[a-z]+', max_df=.5)"
},
{
"code": null,
"e": 7836,
"s": 6996,
"text": "you can find out what tokens were excluded because of max_df=.5 condition by running vectoriser.stop_words_ after fitting the vectoriser. When we call inspect function, the ‘example ignored tokens’ part of the output shows a snippet of those excluded words. Now, I encourage you to run the script above and check vectoriser.stop_words_. What do you see? Do you see mostly stop words? Try changing the values to .5, .6, .8 or .9 and rerun to observe how the excluded words change. It helps to understand how tweaking certain parameters impacts the preprocessing. Now, if you are keen, add stop_words='english’ or min_df=30 (don’t add both at the same time, add one at a time to understand individual parameters) and check out what tokens were excluded this time. We will tune these parameters further when building a model in the next post."
},
{
"code": null,
"e": 7914,
"s": 7836,
"text": "🔗 If you are keen to learn more about parameters , the documentation is here."
},
{
"code": null,
"e": 8138,
"s": 7914,
"text": "This approach was a 🍰, wasn’t it? I like this approach especially because it does a few basic things really well and quick. In my opinion, it’s always good to start simple and add complexity only if it improves performance."
},
{
"code": null,
"e": 8477,
"s": 8138,
"text": "There is always room for improvement. For instance, the word ‘play’, ‘plays’, ‘playing’ and ‘played’ are considered as 4 different tokens in previous approach. Wouldn’t it be great if we remove these inflectional endings so that these tokens are normalised into 1 unique token, ‘play’? That is what we are going to do in the this section!"
},
{
"code": null,
"e": 8692,
"s": 8477,
"text": "To normalise inflectional endings, we will use a technique called lemmatisation. Another alternative is stemming. If you want to learn the difference between these two, I have briefly explained the difference here."
},
{
"code": null,
"e": 8837,
"s": 8692,
"text": "Lemmatisation helps convert words to their dictionary form. Taking our previous example, let’s lemmatise them and see how the output looks like:"
},
{
"code": null,
"e": 8963,
"s": 8837,
"text": "lemmatiser = WordNetLemmatizer()for word in ['play', 'plays', 'playing', 'played']: print(lemmatiser.lemmatize(word, 'v'))"
},
{
"code": null,
"e": 9331,
"s": 8963,
"text": "Cool, all words are now converted to ‘play’. Notice how we passed ‘v’ as the second argument in lemmatize method? The ‘v’ is a part-of-speech tag. Accurate lemmatisation, in fact, depends on the part-of-speech (POS) tag we provide to the lemmatiser along with the word. To demonstrate this, let’s rerun the previous script with one small change where ‘v’ becomes ‘n’:"
},
{
"code": null,
"e": 9449,
"s": 9331,
"text": "lemmatiser = WordNetLemmatizer()for word in ['plays', 'playing', 'played']: print(lemmatiser.lemmatize(word, 'n'))"
},
{
"code": null,
"e": 10076,
"s": 9449,
"text": "This time, not all words have been converted to play. This brief example shows how a part-of-speech tag can impact the effectiveness of the lemmatisation. So what exactly is a part-of-speech tag? Simply put, it refers to a grammatical category of the the word. The word ‘movie’ is a noun and ‘watch’ can be either a verb or a noun depending on the context. Nouns and verbs are examples of part-of-speech. In the first run, we told the lemmatiser that the words provided are verbs (hence ‘v’) and in the second run, nouns (hence ‘n’). Using nltk’s part-of-speech tagger: pos_tag(), we can tag each word with its part-of-speech."
},
{
"code": null,
"e": 10454,
"s": 10076,
"text": "We will shortly create a custom function that does part-of-speech tagging and lemmatisation based on the tags. We will pass this function to the analyzer parameter of TdidfVectoriser(). When we do this, some of the parameters used previously such as token_pattern, stop_words would no longer be supported. Thus, we have to also include a tokenising step in our custom function:"
},
{
"code": null,
"e": 10890,
"s": 10454,
"text": "def preprocess_text(text): # 1. Tokenise to alphabetic tokens tokeniser = RegexpTokenizer(r'[A-Za-z]+') tokens = tokeniser.tokenize(text) # 2. POS tagging pos_map = {'J': 'a', 'N': 'n', 'R': 'r', 'V': 'v'} pos_tags = pos_tag(tokens) # 3. Lowercase and lemmatise lemmatiser = WordNetLemmatizer() tokens = [lemmatiser.lemmatize(t.lower(), pos=pos_map.get(p[0], 'v')) for t, p in pos_tags]return tokens"
},
{
"code": null,
"e": 11200,
"s": 10890,
"text": "One thing to note here is that pos_tag() and lemmatiser.lemmatize() use different naming conventions for part-of-speech tags, so we had to map the part-of-speech produced by the nltk tagger to the names that the lemmatiser can understand. That’s why we have pos_map. Now, let’s preprocess the data and assess:"
},
{
"code": null,
"e": 11305,
"s": 11200,
"text": "vectoriser = TfidfVectorizer(analyzer=preprocess_text, min_df=30, max_df=.7)inspect(vectoriser, X_train)"
},
{
"code": null,
"e": 11898,
"s": 11305,
"text": "It reduced the number of columns to 10,754. That’s about 16% reduction in the number of columns compared to 12,805 columns in simpler approach. It took about 11 minutes on my computer which is ~85 times slower. If we think about it, lemmatisation is not going to alter every word in a review. Let’s take ‘The movie was awesome.’ sentence as an example. The only word would benefit from a lemmatisation is ‘was’. So keeping this in mind, sometimes it’s fine to use a default part-of-speech for all words if you need to do lemmatisation quicker. In that case, our custom function simplifies to:"
},
{
"code": null,
"e": 12323,
"s": 11898,
"text": "# Simple approachdef preprocess_text(text): # 1. Tokenise to alphabetic tokens tokeniser = RegexpTokenizer(r'[A-Za-z]+') tokens = tokeniser.tokenize(text) # 2. Lowercase and lemmatise lemmatiser = WordNetLemmatizer() tokens = [lemmatiser.lemmatize(t.lower(), pos='v') for t in tokens]return tokensvectoriser = TfidfVectorizer(analyzer=preprocess_text, min_df=30, max_df=.7)inspect(vectoriser, X_train)"
},
{
"code": null,
"e": 12822,
"s": 12323,
"text": "The number of columns is very close to the version we used part-of-speech tagger but it only took about a minute. So between these two versions, I prefer using the default part-of-speech tag over the other for this text dataset. Of note, if we don’t provide a value to the pos argument, the lemmatiser defaults to ’n’. Generally speaking, I usually like to use ‘v’ as a default because I find that it normalises more words in general. However, the more suitable default pos will depend on the data."
},
{
"code": null,
"e": 12988,
"s": 12822,
"text": "In this approach, we will further clean up the data. Based on the learnings from the exploratory data analysis and general preprocessing ideas, here’s what we’ll do:"
},
{
"code": null,
"e": 13121,
"s": 12988,
"text": "◼ Correct typos: ‘chracter’ to ‘character’◼ Convert British spelling to American spelling: ‘realise’ to ‘realize’◼ Remove stop words"
},
{
"code": null,
"e": 14343,
"s": 13121,
"text": "def convert_to_american(token): # Copied from here token = re.sub(r\"(...)our$\", r\"\\1or\", token) token = re.sub(r\"([bt])re$\", r\"\\1er\", token) token = re.sub(r\"([iy])s(e$|ing|ation)\", r\"\\1z\\2\", token) token = re.sub(r\"ogue$\", \"og\", token) return tokendef correct_typo(tokens): spell = SpellChecker() return [spell.correction(t) if len(spell.unknown([t]))>0 else t for t in tokens] def preprocess_text(text): # 1. Tokenise to alphabetic tokens tokeniser = RegexpTokenizer(r'[A-Za-z]+') tokens = tokeniser.tokenize(text) # 2. Lowercase and lemmatise lemmatiser = WordNetLemmatizer() tokens = [lemmatiser.lemmatize(t.lower(), pos='v') for t in tokens]# 3. Correct spelling (this won't convert 100% ) tokens = correct_typo(tokens) # 4. Convert British spelling to American spelling (this won't convert 100%) tokens = [convert_to_american(t) for t in tokens]# 5. Remove stopwords stop_words = stopwords.words('english') stop_words.extend(['cannot', 'could', 'done', 'let', 'may' 'mayn', 'might', 'must', 'need', 'ought', 'oughtn', 'shall', 'would', 'br']) tokens = [t for t in tokens if t not in stop_words] return tokens"
},
{
"code": null,
"e": 14701,
"s": 14343,
"text": "In addition to these, we could keep adding other layers to correct and clean up. However, each additional step will add complexity and increase run time without a guaranteed improvement in model performance. Here are some ideas you could try in general when preprocessing text which is not particularly useful in our case but could be useful in other cases:"
},
{
"code": null,
"e": 14849,
"s": 14701,
"text": "◼ Clean up junks such as html tags, email addresses, URLs ◼ Convert numbers to words instead of dropping them◼ Convert emojis or emoticons to words"
},
{
"code": null,
"e": 14899,
"s": 14849,
"text": "Alright, let’s preprocess and inspect the output:"
},
{
"code": null,
"e": 15004,
"s": 14899,
"text": "vectoriser = TfidfVectorizer(analyzer=preprocess_text, min_df=30, max_df=.7)inspect(vectoriser, X_train)"
},
{
"code": null,
"e": 15309,
"s": 15004,
"text": "A few hours after I started running this code, it was still running. As I deemed it was taking too long, I had to interrupt the kernel to stop the query. To see how much slower this approach takes relative to the previous two, I reduced the size of the dataset to 1/9th of its size with the script below:"
},
{
"code": null,
"e": 15355,
"s": 15309,
"text": "train = train.sample(5000, random_state=seed)"
},
{
"code": null,
"e": 15470,
"s": 15355,
"text": "And I have ran all three approaches on this smaller subset of data. Here’s the comparison of the three approaches:"
},
{
"code": null,
"e": 15821,
"s": 15470,
"text": "The less simple approach standardised the tokens more than the other two but at a really high cost. It takes at least 1000 times longer to preprocess compared to the others. There is a chance that this ratio could look worse when the dataset grows. Hence, it’s not practical to pursue less simple approach further unless it’s optimised to run faster."
},
{
"code": null,
"e": 15973,
"s": 15821,
"text": "👂 If you have a better computer than mine, this run time concern may not necessarily be a constraint for you in which case feel free to pursue further."
},
{
"code": null,
"e": 16197,
"s": 15973,
"text": "Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me."
},
{
"code": null,
"e": 16537,
"s": 16197,
"text": "Thank you for reading my post. Hopefully, you have learned a few different practical ways to preprocess text that you could apply to your next NLP project. In the next post, we will build a sentiment classifier. Here are links to the other two posts of the series:◼️ Exploratory text analysis in Python◼️ Sentiment classification in Python"
},
{
"code": null,
"e": 16960,
"s": 16537,
"text": "Here are links to the my other NLP-related posts:◼️ Simple wordcloud in Python(Below lists a series of posts on Introduction to NLP)◼️ Part 1: Preprocessing text in Python◼️ Part 2: Difference between lemmatisation and stemming◼️ Part 3: TF-IDF explained◼️ Part 4: Supervised text classification model in Python◼️ Part 5A: Unsupervised topic model in Python (sklearn)◼️ Part 5B: Unsupervised topic model in Python (gensim)"
}
] |
C++ Ostream Library - write
|
It is used to inserts the first n characters of the array pointed by s into the stream. This function simply copies a block of data, without checking its contents: The array may contain null characters, which are also copied without stopping the copying process.
Following is the declaration for std::ostream::write.
ostream& write (const char* s, streamsize n);
s − Pointer to an array of at least n characters.
s − Pointer to an array of at least n characters.
n − Number of characters to insert.
n − Number of characters to insert.
It returns the ostream object (*this).
Basic guarantee − if an exception is thrown, the object is in a valid state.
Modifies the stream objectAccess up to n characters pointed by s./p>
In below example explains about std::ostream::write.
#include <fstream>
int main () {
std::ifstream infile ("test.txt",std::ifstream::binary);
std::ofstream outfile ("new.txt",std::ofstream::binary);
infile.seekg (0,infile.end);
long size = infile.tellg();
infile.seekg (0);
char* buffer = new char[size];
infile.read (buffer,size);
outfile.write (buffer,size);
delete[] buffer;
outfile.close();
infile.close();
return 0;
}
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2866,
"s": 2603,
"text": "It is used to inserts the first n characters of the array pointed by s into the stream. This function simply copies a block of data, without checking its contents: The array may contain null characters, which are also copied without stopping the copying process."
},
{
"code": null,
"e": 2920,
"s": 2866,
"text": "Following is the declaration for std::ostream::write."
},
{
"code": null,
"e": 2966,
"s": 2920,
"text": "ostream& write (const char* s, streamsize n);"
},
{
"code": null,
"e": 3016,
"s": 2966,
"text": "s − Pointer to an array of at least n characters."
},
{
"code": null,
"e": 3066,
"s": 3016,
"text": "s − Pointer to an array of at least n characters."
},
{
"code": null,
"e": 3102,
"s": 3066,
"text": "n − Number of characters to insert."
},
{
"code": null,
"e": 3138,
"s": 3102,
"text": "n − Number of characters to insert."
},
{
"code": null,
"e": 3177,
"s": 3138,
"text": "It returns the ostream object (*this)."
},
{
"code": null,
"e": 3254,
"s": 3177,
"text": "Basic guarantee − if an exception is thrown, the object is in a valid state."
},
{
"code": null,
"e": 3324,
"s": 3254,
"text": "Modifies the stream objectAccess up to n characters pointed by s./p>\n"
},
{
"code": null,
"e": 3377,
"s": 3324,
"text": "In below example explains about std::ostream::write."
},
{
"code": null,
"e": 3792,
"s": 3377,
"text": "#include <fstream>\n\nint main () {\n std::ifstream infile (\"test.txt\",std::ifstream::binary);\n std::ofstream outfile (\"new.txt\",std::ofstream::binary);\n\n infile.seekg (0,infile.end);\n long size = infile.tellg();\n infile.seekg (0);\n\n char* buffer = new char[size];\n\n infile.read (buffer,size);\n\n outfile.write (buffer,size);\n \n delete[] buffer;\n\n outfile.close();\n infile.close();\n return 0;\n}"
},
{
"code": null,
"e": 3799,
"s": 3792,
"text": " Print"
},
{
"code": null,
"e": 3810,
"s": 3799,
"text": " Add Notes"
}
] |
Select DataFrame rows between two index values in Python Pandas
|
We can slice a Pandas DataFrame to select rows between two index values. Let's take an example and see how it's done.
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
Print the input DataFrame, df.
Initialize a variable for lower limit of the index.
Initialize another variable for upper limit of the index.
Use df[index_lower_limit: index_upper_limit] to print the DataFrame in range index.
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 7, 0],
"y": [4, 7, 5, 1],
"z": [9, 3, 5, 1]
}
)
print "Input DataFrame is:\n", df
index_lower_limit = 1
index_upper_limit = 3
print("DataFrame between two index values:\n",
df[index_lower_limit: index_upper_limit])
Input DataFrame is:
x y z
0 5 4 9
1 2 7 3
2 7 5 5
3 0 1 1
DataFrame between two index values:
x y z
1 2 7 3
2 7 5 5
|
[
{
"code": null,
"e": 1180,
"s": 1062,
"text": "We can slice a Pandas DataFrame to select rows between two index values. Let's take an example and see how it's done."
},
{
"code": null,
"e": 1264,
"s": 1180,
"text": "Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df."
},
{
"code": null,
"e": 1295,
"s": 1264,
"text": "Print the input DataFrame, df."
},
{
"code": null,
"e": 1347,
"s": 1295,
"text": "Initialize a variable for lower limit of the index."
},
{
"code": null,
"e": 1405,
"s": 1347,
"text": "Initialize another variable for upper limit of the index."
},
{
"code": null,
"e": 1489,
"s": 1405,
"text": "Use df[index_lower_limit: index_upper_limit] to print the DataFrame in range index."
},
{
"code": null,
"e": 1784,
"s": 1489,
"text": "import pandas as pd\n\ndf = pd.DataFrame(\n {\n \"x\": [5, 2, 7, 0],\n \"y\": [4, 7, 5, 1],\n \"z\": [9, 3, 5, 1]\n }\n)\nprint \"Input DataFrame is:\\n\", df\n\nindex_lower_limit = 1\nindex_upper_limit = 3\n\nprint(\"DataFrame between two index values:\\n\",\ndf[index_lower_limit: index_upper_limit])"
},
{
"code": null,
"e": 1905,
"s": 1784,
"text": "Input DataFrame is:\n x y z\n0 5 4 9\n1 2 7 3\n2 7 5 5\n3 0 1 1\n\nDataFrame between two index values:\n x y z\n1 2 7 3\n2 7 5 5"
}
] |
How To Create Unique Pokémon Using GANs | by Tyler Folkman | Towards Data Science
|
My son is really into Pokemon. I don’t get it, but I guess that’s besides the point. I did start to wonder, though, if I could create new Pokemon cards for him automatically using deep learning.
I ended up having a bit of success generating Pokemon-like images using Generative Adversarial Networks (GANs) and I thought others might enjoy seeing the process.
I don’t want to spend a lot of time discussing what GANs are, but the above image is a very simple explanation of the process.
You train two networks — a discriminator and a generator. The generator learns how to take in random noise and generate images which look like images from the training data. It does this by feeding its generated images to a discriminator network which is trained to discern between real and generated images.
The generator is optimized to get better and better at fooling the discriminator and the discriminator is optimized to get better and better at detecting the generated images. Thus, they both improve together.
If you would like to learn more, there are many amazing articles, books, and YouTube videos you can find via Google.
So — my hypothesis is that I could train a GAN with real Pokemon images as my training set. The result would be a generator that would then be able to create novel Pokemon! Excellent!
My first challenge was finding Pokemon images. Fortunately, Kaggle datasets came to the rescue!
Someone had already thought of a similar idea, though it sounds like he didn’t have much success generating new Pokemon images, but since he spent the time gathering the 800+ images he decided to upload them to a Kaggle dataset.
This saved me a ton of time.
I also learned that there really are only about 800 Pokemon so it wouldn't be possible to expand this data set with additional Pokemon.
Here is an example of one of the images (256 x 256):
Now that I had data, I had to pick which type of GAN I wanted to use. There are probably hundreds of variations of GANs that exist, but I have seen good results in the past using DCGAN.
DCGAN eliminates any fully connected layers from the neural networks, uses transposed convolutions for up-sampling, and replaces max pooling with convolution strides (among other things).
I like DCGANs because compared to other GANs I have tried they seem to be more robust and thus easier to train without significant tuning of hyper-parameters.
In fact, DCGAN is so popular, that PyTorch has a pretty good implementation as one of its examples. The great part, as well, is that their example can read input directly from a folder. Thus, with the following command, I was able to start training my GAN:
python main.py --dataset folder --dataroot ~/Downloads/pokemon/ --cuda --niter 10000 --workers 8
This command reads the images from the ~/Downloads/pokemon folder, runs on my GPU with 8 workers for loading the data, and runs for 10,000 iterations.
It turns out 10,000 iterations is a lot for this problem, but I wanted to see how far I could push it. Let’s take a look!
The very first step starts with a network which knows nothing, so all that is generated is noise:
Each box is a 64 x 64 pixel image and is an attempt to generate a Pokemon from our generator. Since our grid is 8 x 8, we have 64 different Pokemon trying to be generated. I scaled the images down to 64 x 64 because this algorithm becomes unstable when trying to generate larger images (or at least it did for me).
After 50 epochs, we start to see some life:
After 150, things become a bit clearer:
After 3,700, you have some half-way decent 64 x 64 attempts at Pokemon. After this, it started to diverge to worse results:
Now — I know what you’re thinking, those don’t look like Pokemon at all!
I would ask you to zoom your browser out to about 25% and look again. At a distance, they look surprisingly similar to real Pokemon.
The issue is since we are training on 64 x 64 images it is too easy for the discriminator to be fooled by images which are Pokemon-like in their shape and color and thus the generator doesn’t need to improve.
The obvious next step, in my mind, is to train a higher resolution GAN. In fact, I already made some attempts at just this.
My first attempt was to re-write the PyTorch code to scale to 256 x 256 images. The code worked, but the DCGAN broke down and I couldn’t stabilize the training. I believe the main reason for this is because I only have about 800 images. And while I do some data augmentation, it isn’t enough to train a higher resolution DCGAN.
I then tried using a Relativistic GAN which has seen success training on higher resolution data with small data sets, but wasn’t able to get that to work either.
I’m going to continue to try some other ideas to generate higher resolution Pokemon and if I get something to work, I will post the technique I used.
If nothing else, maybe we can call these generated Pokemon Smoke type Pokemon?
You can find this story here as well.
Interested in learning more about Python data analysis and visualization? Check out my course.
|
[
{
"code": null,
"e": 367,
"s": 172,
"text": "My son is really into Pokemon. I don’t get it, but I guess that’s besides the point. I did start to wonder, though, if I could create new Pokemon cards for him automatically using deep learning."
},
{
"code": null,
"e": 531,
"s": 367,
"text": "I ended up having a bit of success generating Pokemon-like images using Generative Adversarial Networks (GANs) and I thought others might enjoy seeing the process."
},
{
"code": null,
"e": 658,
"s": 531,
"text": "I don’t want to spend a lot of time discussing what GANs are, but the above image is a very simple explanation of the process."
},
{
"code": null,
"e": 967,
"s": 658,
"text": "You train two networks — a discriminator and a generator. The generator learns how to take in random noise and generate images which look like images from the training data. It does this by feeding its generated images to a discriminator network which is trained to discern between real and generated images."
},
{
"code": null,
"e": 1177,
"s": 967,
"text": "The generator is optimized to get better and better at fooling the discriminator and the discriminator is optimized to get better and better at detecting the generated images. Thus, they both improve together."
},
{
"code": null,
"e": 1294,
"s": 1177,
"text": "If you would like to learn more, there are many amazing articles, books, and YouTube videos you can find via Google."
},
{
"code": null,
"e": 1478,
"s": 1294,
"text": "So — my hypothesis is that I could train a GAN with real Pokemon images as my training set. The result would be a generator that would then be able to create novel Pokemon! Excellent!"
},
{
"code": null,
"e": 1574,
"s": 1478,
"text": "My first challenge was finding Pokemon images. Fortunately, Kaggle datasets came to the rescue!"
},
{
"code": null,
"e": 1803,
"s": 1574,
"text": "Someone had already thought of a similar idea, though it sounds like he didn’t have much success generating new Pokemon images, but since he spent the time gathering the 800+ images he decided to upload them to a Kaggle dataset."
},
{
"code": null,
"e": 1832,
"s": 1803,
"text": "This saved me a ton of time."
},
{
"code": null,
"e": 1968,
"s": 1832,
"text": "I also learned that there really are only about 800 Pokemon so it wouldn't be possible to expand this data set with additional Pokemon."
},
{
"code": null,
"e": 2021,
"s": 1968,
"text": "Here is an example of one of the images (256 x 256):"
},
{
"code": null,
"e": 2207,
"s": 2021,
"text": "Now that I had data, I had to pick which type of GAN I wanted to use. There are probably hundreds of variations of GANs that exist, but I have seen good results in the past using DCGAN."
},
{
"code": null,
"e": 2395,
"s": 2207,
"text": "DCGAN eliminates any fully connected layers from the neural networks, uses transposed convolutions for up-sampling, and replaces max pooling with convolution strides (among other things)."
},
{
"code": null,
"e": 2554,
"s": 2395,
"text": "I like DCGANs because compared to other GANs I have tried they seem to be more robust and thus easier to train without significant tuning of hyper-parameters."
},
{
"code": null,
"e": 2811,
"s": 2554,
"text": "In fact, DCGAN is so popular, that PyTorch has a pretty good implementation as one of its examples. The great part, as well, is that their example can read input directly from a folder. Thus, with the following command, I was able to start training my GAN:"
},
{
"code": null,
"e": 2909,
"s": 2811,
"text": "python main.py --dataset folder --dataroot ~/Downloads/pokemon/ --cuda --niter 10000 --workers 8"
},
{
"code": null,
"e": 3060,
"s": 2909,
"text": "This command reads the images from the ~/Downloads/pokemon folder, runs on my GPU with 8 workers for loading the data, and runs for 10,000 iterations."
},
{
"code": null,
"e": 3182,
"s": 3060,
"text": "It turns out 10,000 iterations is a lot for this problem, but I wanted to see how far I could push it. Let’s take a look!"
},
{
"code": null,
"e": 3280,
"s": 3182,
"text": "The very first step starts with a network which knows nothing, so all that is generated is noise:"
},
{
"code": null,
"e": 3595,
"s": 3280,
"text": "Each box is a 64 x 64 pixel image and is an attempt to generate a Pokemon from our generator. Since our grid is 8 x 8, we have 64 different Pokemon trying to be generated. I scaled the images down to 64 x 64 because this algorithm becomes unstable when trying to generate larger images (or at least it did for me)."
},
{
"code": null,
"e": 3639,
"s": 3595,
"text": "After 50 epochs, we start to see some life:"
},
{
"code": null,
"e": 3679,
"s": 3639,
"text": "After 150, things become a bit clearer:"
},
{
"code": null,
"e": 3803,
"s": 3679,
"text": "After 3,700, you have some half-way decent 64 x 64 attempts at Pokemon. After this, it started to diverge to worse results:"
},
{
"code": null,
"e": 3876,
"s": 3803,
"text": "Now — I know what you’re thinking, those don’t look like Pokemon at all!"
},
{
"code": null,
"e": 4009,
"s": 3876,
"text": "I would ask you to zoom your browser out to about 25% and look again. At a distance, they look surprisingly similar to real Pokemon."
},
{
"code": null,
"e": 4218,
"s": 4009,
"text": "The issue is since we are training on 64 x 64 images it is too easy for the discriminator to be fooled by images which are Pokemon-like in their shape and color and thus the generator doesn’t need to improve."
},
{
"code": null,
"e": 4342,
"s": 4218,
"text": "The obvious next step, in my mind, is to train a higher resolution GAN. In fact, I already made some attempts at just this."
},
{
"code": null,
"e": 4670,
"s": 4342,
"text": "My first attempt was to re-write the PyTorch code to scale to 256 x 256 images. The code worked, but the DCGAN broke down and I couldn’t stabilize the training. I believe the main reason for this is because I only have about 800 images. And while I do some data augmentation, it isn’t enough to train a higher resolution DCGAN."
},
{
"code": null,
"e": 4832,
"s": 4670,
"text": "I then tried using a Relativistic GAN which has seen success training on higher resolution data with small data sets, but wasn’t able to get that to work either."
},
{
"code": null,
"e": 4982,
"s": 4832,
"text": "I’m going to continue to try some other ideas to generate higher resolution Pokemon and if I get something to work, I will post the technique I used."
},
{
"code": null,
"e": 5061,
"s": 4982,
"text": "If nothing else, maybe we can call these generated Pokemon Smoke type Pokemon?"
},
{
"code": null,
"e": 5099,
"s": 5061,
"text": "You can find this story here as well."
}
] |
How to run two PHP versions for two projects on same apache server ? - GeeksforGeeks
|
15 Nov, 2021
In this article, we will learn about running two versions of PHP on the same Apache server. To manage many domains, the Apache webserver uses virtual hosts on a single instance.
Prerequisite: We will be using the XAMPP server to use the Apache server and some knowledge to use it.
First, download the older version of XAMPP that can be of any version. The old version is XAMPP 1.8.2 and then later we install the latest version of the XAMPP. Both versions of the XAMPP will have the same apache server.
Steps:
Download xampp-win32-1.8.2-6-VC9-Installer.exeInstall the software.Click on the next.Change the name (better to use the XAMPP_1_8_2) so that later you will be able to differentiate between the new and old versions.Click on “install” to complete the installation process.
Download xampp-win32-1.8.2-6-VC9-Installer.exe
Download xampp-win32-1.8.2-6-VC9-Installer.exe
Install the software.
Install the software.
Click on the next.
Click on the next.
Change the name (better to use the XAMPP_1_8_2) so that later you will be able to differentiate between the new and old versions.
Change the name (better to use the XAMPP_1_8_2) so that later you will be able to differentiate between the new and old versions.
Click on “install” to complete the installation process.
Click on “install” to complete the installation process.
Open the folder location where you kept your XAMPP1_8_2.
Click on the Apache at the XAMPP_1_8_2 –> apache
Configure the file httpd CONF file to change the port for the new XAMPP. As two different versions of XAMPP cannot run on the same port, we need to change to the port.
Steps to change the port for the XAMPP1_8_2:
Open the file HTTP CONF file > change the port from the 80 to 8080.
After changing the port click on save and exit.
Now go to the extra folder
Changes to be done in the ssl CONF file
Change the Listen 443 to 444
Save all and exit.
Now download the XAMPP new version
Follow the same steps {1, 2, 3, 4, 5, 6}
Don’t change anything like the port.
Open the XAMPP1_8_2 control
Open the XAMPP new version control.
Note: You may face some problem with the port of 3306.
Change the port 3306 to 3307
Steps to change port:
Change the config file for the MySQL in “my.ini” file.
Change the config file for the MySQL in “my.ini” file.
Change the port to 3307
Change the port to 3307
Run the code:PHPPHP<?php phpinfo();?>
Run the code:
PHP
<?php phpinfo();?>
Save the above code in “htdocs” folder of the XAMPP folder for the new and older version.
Save the above code in “htdocs” folder of the XAMPP folder for the new and older version.
Save in “htdocs” folder of the XAMPP folder.
Save in “htdocs” folder of the XAMPP folder.
Similarly with XAMPP_1_8_2Now, open the browser then type the command .localhost/phpinfo.phpOutput:This is the one version 7.4.2.Now for the second version type the command .localhost:8080/phpinfo.phpOutput:Finally we are able to execute the two PHP version (7.4.2 and 5.4.27) in the same Apache server.My Personal Notes
arrow_drop_upSave
Similarly with XAMPP_1_8_2
Now, open the browser then type the command .
localhost/phpinfo.php
Output:
This is the one version 7.4.2.
Now for the second version type the command .
localhost:8080/phpinfo.php
Output:
Finally we are able to execute the two PHP version (7.4.2 and 5.4.27) in the same Apache server.
simmytarika5
PHP-Misc
PHP
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 25246,
"s": 25218,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 25424,
"s": 25246,
"text": "In this article, we will learn about running two versions of PHP on the same Apache server. To manage many domains, the Apache webserver uses virtual hosts on a single instance."
},
{
"code": null,
"e": 25527,
"s": 25424,
"text": "Prerequisite: We will be using the XAMPP server to use the Apache server and some knowledge to use it."
},
{
"code": null,
"e": 25749,
"s": 25527,
"text": "First, download the older version of XAMPP that can be of any version. The old version is XAMPP 1.8.2 and then later we install the latest version of the XAMPP. Both versions of the XAMPP will have the same apache server."
},
{
"code": null,
"e": 25756,
"s": 25749,
"text": "Steps:"
},
{
"code": null,
"e": 26027,
"s": 25756,
"text": "Download xampp-win32-1.8.2-6-VC9-Installer.exeInstall the software.Click on the next.Change the name (better to use the XAMPP_1_8_2) so that later you will be able to differentiate between the new and old versions.Click on “install” to complete the installation process."
},
{
"code": null,
"e": 26074,
"s": 26027,
"text": "Download xampp-win32-1.8.2-6-VC9-Installer.exe"
},
{
"code": null,
"e": 26121,
"s": 26074,
"text": "Download xampp-win32-1.8.2-6-VC9-Installer.exe"
},
{
"code": null,
"e": 26143,
"s": 26121,
"text": "Install the software."
},
{
"code": null,
"e": 26165,
"s": 26143,
"text": "Install the software."
},
{
"code": null,
"e": 26184,
"s": 26165,
"text": "Click on the next."
},
{
"code": null,
"e": 26203,
"s": 26184,
"text": "Click on the next."
},
{
"code": null,
"e": 26333,
"s": 26203,
"text": "Change the name (better to use the XAMPP_1_8_2) so that later you will be able to differentiate between the new and old versions."
},
{
"code": null,
"e": 26463,
"s": 26333,
"text": "Change the name (better to use the XAMPP_1_8_2) so that later you will be able to differentiate between the new and old versions."
},
{
"code": null,
"e": 26520,
"s": 26463,
"text": "Click on “install” to complete the installation process."
},
{
"code": null,
"e": 26577,
"s": 26520,
"text": "Click on “install” to complete the installation process."
},
{
"code": null,
"e": 26634,
"s": 26577,
"text": "Open the folder location where you kept your XAMPP1_8_2."
},
{
"code": null,
"e": 26683,
"s": 26634,
"text": "Click on the Apache at the XAMPP_1_8_2 –> apache"
},
{
"code": null,
"e": 26851,
"s": 26683,
"text": "Configure the file httpd CONF file to change the port for the new XAMPP. As two different versions of XAMPP cannot run on the same port, we need to change to the port."
},
{
"code": null,
"e": 26896,
"s": 26851,
"text": "Steps to change the port for the XAMPP1_8_2:"
},
{
"code": null,
"e": 26964,
"s": 26896,
"text": "Open the file HTTP CONF file > change the port from the 80 to 8080."
},
{
"code": null,
"e": 27012,
"s": 26964,
"text": "After changing the port click on save and exit."
},
{
"code": null,
"e": 27039,
"s": 27012,
"text": "Now go to the extra folder"
},
{
"code": null,
"e": 27079,
"s": 27039,
"text": "Changes to be done in the ssl CONF file"
},
{
"code": null,
"e": 27108,
"s": 27079,
"text": "Change the Listen 443 to 444"
},
{
"code": null,
"e": 27127,
"s": 27108,
"text": "Save all and exit."
},
{
"code": null,
"e": 27162,
"s": 27127,
"text": "Now download the XAMPP new version"
},
{
"code": null,
"e": 27203,
"s": 27162,
"text": "Follow the same steps {1, 2, 3, 4, 5, 6}"
},
{
"code": null,
"e": 27240,
"s": 27203,
"text": "Don’t change anything like the port."
},
{
"code": null,
"e": 27268,
"s": 27240,
"text": "Open the XAMPP1_8_2 control"
},
{
"code": null,
"e": 27304,
"s": 27268,
"text": "Open the XAMPP new version control."
},
{
"code": null,
"e": 27359,
"s": 27304,
"text": "Note: You may face some problem with the port of 3306."
},
{
"code": null,
"e": 27388,
"s": 27359,
"text": "Change the port 3306 to 3307"
},
{
"code": null,
"e": 27410,
"s": 27388,
"text": "Steps to change port:"
},
{
"code": null,
"e": 27465,
"s": 27410,
"text": "Change the config file for the MySQL in “my.ini” file."
},
{
"code": null,
"e": 27520,
"s": 27465,
"text": "Change the config file for the MySQL in “my.ini” file."
},
{
"code": null,
"e": 27544,
"s": 27520,
"text": "Change the port to 3307"
},
{
"code": null,
"e": 27568,
"s": 27544,
"text": "Change the port to 3307"
},
{
"code": null,
"e": 27609,
"s": 27568,
"text": "Run the code:PHPPHP<?php phpinfo();?>"
},
{
"code": null,
"e": 27623,
"s": 27609,
"text": "Run the code:"
},
{
"code": null,
"e": 27627,
"s": 27623,
"text": "PHP"
},
{
"code": "<?php phpinfo();?>",
"e": 27649,
"s": 27627,
"text": null
},
{
"code": null,
"e": 27739,
"s": 27649,
"text": "Save the above code in “htdocs” folder of the XAMPP folder for the new and older version."
},
{
"code": null,
"e": 27829,
"s": 27739,
"text": "Save the above code in “htdocs” folder of the XAMPP folder for the new and older version."
},
{
"code": null,
"e": 27874,
"s": 27829,
"text": "Save in “htdocs” folder of the XAMPP folder."
},
{
"code": null,
"e": 27919,
"s": 27874,
"text": "Save in “htdocs” folder of the XAMPP folder."
},
{
"code": null,
"e": 28260,
"s": 27919,
"text": "Similarly with XAMPP_1_8_2Now, open the browser then type the command .localhost/phpinfo.phpOutput:This is the one version 7.4.2.Now for the second version type the command .localhost:8080/phpinfo.phpOutput:Finally we are able to execute the two PHP version (7.4.2 and 5.4.27) in the same Apache server.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 28287,
"s": 28260,
"text": "Similarly with XAMPP_1_8_2"
},
{
"code": null,
"e": 28333,
"s": 28287,
"text": "Now, open the browser then type the command ."
},
{
"code": null,
"e": 28355,
"s": 28333,
"text": "localhost/phpinfo.php"
},
{
"code": null,
"e": 28363,
"s": 28355,
"text": "Output:"
},
{
"code": null,
"e": 28394,
"s": 28363,
"text": "This is the one version 7.4.2."
},
{
"code": null,
"e": 28440,
"s": 28394,
"text": "Now for the second version type the command ."
},
{
"code": null,
"e": 28467,
"s": 28440,
"text": "localhost:8080/phpinfo.php"
},
{
"code": null,
"e": 28475,
"s": 28467,
"text": "Output:"
},
{
"code": null,
"e": 28574,
"s": 28475,
"text": "Finally we are able to execute the two PHP version (7.4.2 and 5.4.27) in the same Apache server."
},
{
"code": null,
"e": 28587,
"s": 28574,
"text": "simmytarika5"
},
{
"code": null,
"e": 28596,
"s": 28587,
"text": "PHP-Misc"
},
{
"code": null,
"e": 28600,
"s": 28596,
"text": "PHP"
},
{
"code": null,
"e": 28617,
"s": 28600,
"text": "Web Technologies"
},
{
"code": null,
"e": 28644,
"s": 28617,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28648,
"s": 28644,
"text": "PHP"
},
{
"code": null,
"e": 28746,
"s": 28648,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28796,
"s": 28746,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 28836,
"s": 28796,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 28897,
"s": 28836,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 28947,
"s": 28897,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 28974,
"s": 28947,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 29016,
"s": 28974,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29049,
"s": 29016,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29092,
"s": 29049,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29142,
"s": 29092,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
C# | Type.GetMember() Method - GeeksforGeeks
|
05 Dec, 2019
Type.GetMember() Method is used to get the specified members of the current Type. There are 3 methods in the overload list of this method as follows:
GetMember(String) Method
GetMember(String, BindingFlags) Method
GetMember(String, MemberTypes, BindingFlags) Method
This method searches for the public members with the specified name.
Syntax: public System.Reflection.MemberInfo[] GetMember (string name);Here, it takes the string containing the name of the public members to get.
Return Value: This method returns an array of MemberInfo objects representing the public members with the specified name, if found otherwise, an empty array.
Exception: This method throws ArgumentNullException if name is null.
Below programs illustrate the use of the above-discussed method:
Example 1:
// C# program to demonstrate the// Type.GetMember(String) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Student); // try-catch block for handling Exception try { MemberInfo[] info = objType.GetMember("Name"); // Display the Result Console.WriteLine("Members of current type is as Follow: "); for (int i = 0; i < info.Length; i++) Console.WriteLine(" {0}", info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write("name is null."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} // Defining class Studentpublic class Student { public string Name = "Rahul"; public string Dept = "Electrical"; public int Roll = 10; public static int id = 02;}
Members of current type is as Follow:
System.String Name
Example 2: For ArgumentNullException
// C# program to demonstrate the// Type.GetMember(String) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Student); // try-catch block for handling Exception try { MemberInfo[] info = objType.GetMember(null); // Display the Result Console.WriteLine("Members of current type is as Follow: "); for (int i = 0; i < info.Length; i++) Console.WriteLine(" {0}", info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.WriteLine("name is null."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} // Defining class Studentpublic class Student { public string Name = "Rahul"; public string Dept = "Electrical"; public int Roll = 10; public static int id = 02;}
name is null.
Exception Thrown: System.ArgumentNullException
This method is used to search for the specified members, using the specified binding constraints.
Syntax: public virtual System.Reflection.MemberInfo[] GetMember (string name, System.Reflection.BindingFlags bindingAttr);
Parameters:name: It is the string containing the name of the members to get.bindingAttr: It is a bitmask comprised of one or more BindingFlags that specify how the search is conducted. or, Zero, to return an empty array.
Return Value: This method returns an array of MemberInfo objects representing the public members with the specified name if found otherwise, an empty array.
Exception: This method throws ArgumentNullException if name is null.
Below programs illustrate the use of the above-discussed method:
Example 1:
// C# program to demonstrate the// Type.GetMember(String, BindingFlags) // Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Student); // try-catch block for handling Exception try { MemberInfo[] info = objType.GetMember("Name", BindingFlags.Public | BindingFlags.Instance); // Display the Result Console.WriteLine("Members of current type is as Follow: "); for (int i = 0; i < info.Length; i++) Console.WriteLine(" {0}", info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.WriteLine("name is null."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} // Defining class Studentpublic class Student{ public string Name = "Rahul"; public string Dept = "Electrical"; public int Roll = 10; public static int id = 02;}
Members of current type is as Follow:
System.String Name
Example 2: For ArgumentNullException
// C# program to demonstrate the// Type.GetMember(String, BindingFlags) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Student); // try-catch block for handling Exception try { MemberInfo[] info = objType.GetMember(null, BindingFlags.Public | BindingFlags.Instance); // Display the Result Console.WriteLine("Members of current type is as Follow: "); for (int i = 0; i < info.Length; i++) Console.WriteLine(" {0}", info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.WriteLine("name is null."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} // Defining class Studentpublic class Student{ public string Name = "Rahul"; public string Dept = "Electrical"; public int Roll = 10; public static int id = 02;}
name is null.
Exception Thrown: System.ArgumentNullException
This method is used to search for the specified members of the specified member type, using the specified binding constraints.
Syntax: public virtual System.Reflection.MemberInfo[] GetMember (string name, System.Reflection.MemberTypes type, System.Reflection.BindingFlags bindingAttr);
Parameters:name: It is the string containing the name of the members to get.type: It is the value to search for.bindingAttr: It is a bitmask comprised of one or more BindingFlags that specify how the search is conducted or, Zero, to return an empty array.
Return Value: This method returns an array of MemberInfo objects representing the public members with the specified name if found otherwise, an empty array.
Exception: This method throw ArgumentNullException if the name is null.
Below programs illustrate the use of the above-discussed method:
Example 1:
// C# program to demonstrate the// Type.GetMember(String, MemberTypes,// BindingFlags) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Student); // try-catch block for handling Exception try { MemberInfo[] info = objType.GetMember("returnNull", MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance); // Display the Result Console.WriteLine("Members of current type is as Follow: "); for (int i = 0; i < info.Length; i++) Console.WriteLine(" {0}", info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.WriteLine("name is null."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} // Defining class Studentpublic class Student { public string Name = "Rahul"; public string Dept = "Electrical"; public int Roll = 10; public static int id = 02; public void returnNull() {}}
Members of current type is as Follow:
Void returnNull()
Example 2: For ArgumentNullException
// C# program to demonstrate the// Type.GetMember(String, MemberTypes,// BindingFlags) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Student); // try-catch block for handling Exception try { MemberInfo[] info = objType.GetMember(null, MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance); // Display the Result Console.WriteLine("Members of current type is as Follow: "); for (int i = 0; i < info.Length; i++) Console.WriteLine(" {0}", info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.WriteLine("name is null."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} // Defining class Studentpublic class Student{ public string Name = "Rahul"; public string Dept = "Electrical"; public int Roll = 10; public static int id = 02; public void returnNull() {}}
name is null.
Exception Thrown: System.ArgumentNullException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.type.getmember?view=netframework-4.8
CSharp-method
CSharp-Type-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# Dictionary with examples
C# | Method Overriding
C# | Constructors
C# | Class and Object
Introduction to .NET Framework
Extension Method in C#
Difference between Ref and Out keywords in C#
C# | String.IndexOf( ) Method | Set - 1
C# | Delegates
C# | Data Types
|
[
{
"code": null,
"e": 24904,
"s": 24876,
"text": "\n05 Dec, 2019"
},
{
"code": null,
"e": 25054,
"s": 24904,
"text": "Type.GetMember() Method is used to get the specified members of the current Type. There are 3 methods in the overload list of this method as follows:"
},
{
"code": null,
"e": 25079,
"s": 25054,
"text": "GetMember(String) Method"
},
{
"code": null,
"e": 25118,
"s": 25079,
"text": "GetMember(String, BindingFlags) Method"
},
{
"code": null,
"e": 25170,
"s": 25118,
"text": "GetMember(String, MemberTypes, BindingFlags) Method"
},
{
"code": null,
"e": 25239,
"s": 25170,
"text": "This method searches for the public members with the specified name."
},
{
"code": null,
"e": 25385,
"s": 25239,
"text": "Syntax: public System.Reflection.MemberInfo[] GetMember (string name);Here, it takes the string containing the name of the public members to get."
},
{
"code": null,
"e": 25543,
"s": 25385,
"text": "Return Value: This method returns an array of MemberInfo objects representing the public members with the specified name, if found otherwise, an empty array."
},
{
"code": null,
"e": 25612,
"s": 25543,
"text": "Exception: This method throws ArgumentNullException if name is null."
},
{
"code": null,
"e": 25677,
"s": 25612,
"text": "Below programs illustrate the use of the above-discussed method:"
},
{
"code": null,
"e": 25688,
"s": 25677,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// Type.GetMember(String) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Student); // try-catch block for handling Exception try { MemberInfo[] info = objType.GetMember(\"Name\"); // Display the Result Console.WriteLine(\"Members of current type is as Follow: \"); for (int i = 0; i < info.Length; i++) Console.WriteLine(\" {0}\", info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write(\"name is null.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }} // Defining class Studentpublic class Student { public string Name = \"Rahul\"; public string Dept = \"Electrical\"; public int Roll = 10; public static int id = 02;}",
"e": 26747,
"s": 25688,
"text": null
},
{
"code": null,
"e": 26807,
"s": 26747,
"text": "Members of current type is as Follow: \n System.String Name\n"
},
{
"code": null,
"e": 26844,
"s": 26807,
"text": "Example 2: For ArgumentNullException"
},
{
"code": "// C# program to demonstrate the// Type.GetMember(String) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Student); // try-catch block for handling Exception try { MemberInfo[] info = objType.GetMember(null); // Display the Result Console.WriteLine(\"Members of current type is as Follow: \"); for (int i = 0; i < info.Length; i++) Console.WriteLine(\" {0}\", info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.WriteLine(\"name is null.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }} // Defining class Studentpublic class Student { public string Name = \"Rahul\"; public string Dept = \"Electrical\"; public int Roll = 10; public static int id = 02;}",
"e": 27905,
"s": 26844,
"text": null
},
{
"code": null,
"e": 27967,
"s": 27905,
"text": "name is null.\nException Thrown: System.ArgumentNullException\n"
},
{
"code": null,
"e": 28065,
"s": 27967,
"text": "This method is used to search for the specified members, using the specified binding constraints."
},
{
"code": null,
"e": 28188,
"s": 28065,
"text": "Syntax: public virtual System.Reflection.MemberInfo[] GetMember (string name, System.Reflection.BindingFlags bindingAttr);"
},
{
"code": null,
"e": 28409,
"s": 28188,
"text": "Parameters:name: It is the string containing the name of the members to get.bindingAttr: It is a bitmask comprised of one or more BindingFlags that specify how the search is conducted. or, Zero, to return an empty array."
},
{
"code": null,
"e": 28566,
"s": 28409,
"text": "Return Value: This method returns an array of MemberInfo objects representing the public members with the specified name if found otherwise, an empty array."
},
{
"code": null,
"e": 28635,
"s": 28566,
"text": "Exception: This method throws ArgumentNullException if name is null."
},
{
"code": null,
"e": 28700,
"s": 28635,
"text": "Below programs illustrate the use of the above-discussed method:"
},
{
"code": null,
"e": 28711,
"s": 28700,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// Type.GetMember(String, BindingFlags) // Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Student); // try-catch block for handling Exception try { MemberInfo[] info = objType.GetMember(\"Name\", BindingFlags.Public | BindingFlags.Instance); // Display the Result Console.WriteLine(\"Members of current type is as Follow: \"); for (int i = 0; i < info.Length; i++) Console.WriteLine(\" {0}\", info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.WriteLine(\"name is null.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }} // Defining class Studentpublic class Student{ public string Name = \"Rahul\"; public string Dept = \"Electrical\"; public int Roll = 10; public static int id = 02;}",
"e": 29856,
"s": 28711,
"text": null
},
{
"code": null,
"e": 29916,
"s": 29856,
"text": "Members of current type is as Follow: \n System.String Name\n"
},
{
"code": null,
"e": 29953,
"s": 29916,
"text": "Example 2: For ArgumentNullException"
},
{
"code": "// C# program to demonstrate the// Type.GetMember(String, BindingFlags) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Student); // try-catch block for handling Exception try { MemberInfo[] info = objType.GetMember(null, BindingFlags.Public | BindingFlags.Instance); // Display the Result Console.WriteLine(\"Members of current type is as Follow: \"); for (int i = 0; i < info.Length; i++) Console.WriteLine(\" {0}\", info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.WriteLine(\"name is null.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }} // Defining class Studentpublic class Student{ public string Name = \"Rahul\"; public string Dept = \"Electrical\"; public int Roll = 10; public static int id = 02;}",
"e": 31092,
"s": 29953,
"text": null
},
{
"code": null,
"e": 31154,
"s": 31092,
"text": "name is null.\nException Thrown: System.ArgumentNullException\n"
},
{
"code": null,
"e": 31281,
"s": 31154,
"text": "This method is used to search for the specified members of the specified member type, using the specified binding constraints."
},
{
"code": null,
"e": 31440,
"s": 31281,
"text": "Syntax: public virtual System.Reflection.MemberInfo[] GetMember (string name, System.Reflection.MemberTypes type, System.Reflection.BindingFlags bindingAttr);"
},
{
"code": null,
"e": 31696,
"s": 31440,
"text": "Parameters:name: It is the string containing the name of the members to get.type: It is the value to search for.bindingAttr: It is a bitmask comprised of one or more BindingFlags that specify how the search is conducted or, Zero, to return an empty array."
},
{
"code": null,
"e": 31853,
"s": 31696,
"text": "Return Value: This method returns an array of MemberInfo objects representing the public members with the specified name if found otherwise, an empty array."
},
{
"code": null,
"e": 31925,
"s": 31853,
"text": "Exception: This method throw ArgumentNullException if the name is null."
},
{
"code": null,
"e": 31990,
"s": 31925,
"text": "Below programs illustrate the use of the above-discussed method:"
},
{
"code": null,
"e": 32001,
"s": 31990,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// Type.GetMember(String, MemberTypes,// BindingFlags) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Student); // try-catch block for handling Exception try { MemberInfo[] info = objType.GetMember(\"returnNull\", MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance); // Display the Result Console.WriteLine(\"Members of current type is as Follow: \"); for (int i = 0; i < info.Length; i++) Console.WriteLine(\" {0}\", info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.WriteLine(\"name is null.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }} // Defining class Studentpublic class Student { public string Name = \"Rahul\"; public string Dept = \"Electrical\"; public int Roll = 10; public static int id = 02; public void returnNull() {}}",
"e": 33234,
"s": 32001,
"text": null
},
{
"code": null,
"e": 33293,
"s": 33234,
"text": "Members of current type is as Follow: \n Void returnNull()\n"
},
{
"code": null,
"e": 33330,
"s": 33293,
"text": "Example 2: For ArgumentNullException"
},
{
"code": "// C# program to demonstrate the// Type.GetMember(String, MemberTypes,// BindingFlags) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Student); // try-catch block for handling Exception try { MemberInfo[] info = objType.GetMember(null, MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance); // Display the Result Console.WriteLine(\"Members of current type is as Follow: \"); for (int i = 0; i < info.Length; i++) Console.WriteLine(\" {0}\", info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.WriteLine(\"name is null.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }} // Defining class Studentpublic class Student{ public string Name = \"Rahul\"; public string Dept = \"Electrical\"; public int Roll = 10; public static int id = 02; public void returnNull() {}}",
"e": 34547,
"s": 33330,
"text": null
},
{
"code": null,
"e": 34609,
"s": 34547,
"text": "name is null.\nException Thrown: System.ArgumentNullException\n"
},
{
"code": null,
"e": 34620,
"s": 34609,
"text": "Reference:"
},
{
"code": null,
"e": 34708,
"s": 34620,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.type.getmember?view=netframework-4.8"
},
{
"code": null,
"e": 34722,
"s": 34708,
"text": "CSharp-method"
},
{
"code": null,
"e": 34740,
"s": 34722,
"text": "CSharp-Type-Class"
},
{
"code": null,
"e": 34743,
"s": 34740,
"text": "C#"
},
{
"code": null,
"e": 34841,
"s": 34743,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34850,
"s": 34841,
"text": "Comments"
},
{
"code": null,
"e": 34863,
"s": 34850,
"text": "Old Comments"
},
{
"code": null,
"e": 34891,
"s": 34863,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 34914,
"s": 34891,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 34932,
"s": 34914,
"text": "C# | Constructors"
},
{
"code": null,
"e": 34954,
"s": 34932,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 34985,
"s": 34954,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 35008,
"s": 34985,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 35054,
"s": 35008,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 35094,
"s": 35054,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 35109,
"s": 35094,
"text": "C# | Delegates"
}
] |
Rename Files Using R - GeeksforGeeks
|
14 Sep, 2021
In this article, we are going to see how to rename files using R Programming Language.
To rename a file in R we use file.rename(). This function renames all the files mentioned as parameters. It returns normally TRUE for success, FALSE for failure.
Note: File naming conventions depend on the platform.
Syntax: file.rename( to, from)
Parameters:
to: character vector that contains all the files to be renamed
from: character vector that contains new names for file
File for demonstration:
Directory
Below is the implementation:
Here we first list out the working directory and then use rename() function to rename the file name.
R
# Define working directoryworking_directory <- "working/dic/" # get list of current file# names as character vector current_filescurrent_files <- list.files(working_directory) # get file names after renaming# as character vector new_filesnew_files <- c("geeks1.txt","geeks2.txt") # Use file.rename() function to rename filesfile.rename(paste0(working_directory, current_files), paste0(working_directory, new_files))
Output:
TRUE TRUE
Final Directory
Picked
R-FileHandling
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
|
[
{
"code": null,
"e": 26597,
"s": 26569,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 26684,
"s": 26597,
"text": "In this article, we are going to see how to rename files using R Programming Language."
},
{
"code": null,
"e": 26847,
"s": 26684,
"text": "To rename a file in R we use file.rename(). This function renames all the files mentioned as parameters. It returns normally TRUE for success, FALSE for failure. "
},
{
"code": null,
"e": 26901,
"s": 26847,
"text": "Note: File naming conventions depend on the platform."
},
{
"code": null,
"e": 26932,
"s": 26901,
"text": "Syntax: file.rename( to, from)"
},
{
"code": null,
"e": 26944,
"s": 26932,
"text": "Parameters:"
},
{
"code": null,
"e": 27007,
"s": 26944,
"text": "to: character vector that contains all the files to be renamed"
},
{
"code": null,
"e": 27063,
"s": 27007,
"text": "from: character vector that contains new names for file"
},
{
"code": null,
"e": 27087,
"s": 27063,
"text": "File for demonstration:"
},
{
"code": null,
"e": 27097,
"s": 27087,
"text": "Directory"
},
{
"code": null,
"e": 27126,
"s": 27097,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 27227,
"s": 27126,
"text": "Here we first list out the working directory and then use rename() function to rename the file name."
},
{
"code": null,
"e": 27229,
"s": 27227,
"text": "R"
},
{
"code": "# Define working directoryworking_directory <- \"working/dic/\" # get list of current file# names as character vector current_filescurrent_files <- list.files(working_directory) # get file names after renaming# as character vector new_filesnew_files <- c(\"geeks1.txt\",\"geeks2.txt\") # Use file.rename() function to rename filesfile.rename(paste0(working_directory, current_files), paste0(working_directory, new_files))",
"e": 27659,
"s": 27229,
"text": null
},
{
"code": null,
"e": 27667,
"s": 27659,
"text": "Output:"
},
{
"code": null,
"e": 27677,
"s": 27667,
"text": "TRUE TRUE"
},
{
"code": null,
"e": 27693,
"s": 27677,
"text": "Final Directory"
},
{
"code": null,
"e": 27700,
"s": 27693,
"text": "Picked"
},
{
"code": null,
"e": 27715,
"s": 27700,
"text": "R-FileHandling"
},
{
"code": null,
"e": 27726,
"s": 27715,
"text": "R Language"
},
{
"code": null,
"e": 27824,
"s": 27726,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27876,
"s": 27824,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27911,
"s": 27876,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27969,
"s": 27911,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28007,
"s": 27969,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28050,
"s": 28007,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28100,
"s": 28050,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 28117,
"s": 28100,
"text": "R - if statement"
},
{
"code": null,
"e": 28166,
"s": 28117,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28203,
"s": 28166,
"text": "How to import an Excel File into R ?"
}
] |
Maximum number of segments of lengths a, b and c - GeeksforGeeks
|
07 Apr, 2021
Given a positive integer N, find the maximum number of segments of lengths a, b and c that can be formed from N . Examples :
Input : N = 7, a = 5, b, = 2, c = 5
Output : 2
N can be divided into 2 segments of lengths
2 and 5. For the second example,
Input : N = 17, a = 2, b = 1, c = 3
Output : 17
N can be divided into 17 segments of 1 or 8
segments of 2 and 1 segment of 1. But 17 segments
of 1 is greater than 9 segments of 2 and 1.
Approach : The approach used is Dynamic Programming. The base dp0 will be 0 as initially it has no segments. After that, iterate from 1 to n, and for each of the 3 states i.e, dpi+a, dpi+b and dpi+c, store the maximum value obtained by either using or not using the a, b or c segment. The 3 states to deal with are :
dpi+a=max(dpi+1, dpi+a); dpi+b=max(dpi+1, dpi+b); dpi+c=max(dpi+1, dpi+c);
Below is the implementation of above idea :
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to divide N into// maximum number of segments// of length a, b and c#include <bits/stdc++.h>using namespace std; // function to find the maximum// number of segmentsint maximumSegments(int n, int a, int b, int c){ // stores the maximum number of // segments each index can have int dp[n + 1]; // initialize with -1 memset(dp, -1, sizeof(dp)); // 0th index will have 0 segments // base case dp[0] = 0; // traverse for all possible // segments till n for (int i = 0; i < n; i++) { if (dp[i] != -1) { // conditions if(i + a <= n ) //avoid buffer overflow dp[i + a] = max(dp[i] + 1, dp[i + a]); if(i + b <= n ) //avoid buffer overflow dp[i + b] = max(dp[i] + 1, dp[i + b]); if(i + c <= n ) //avoid buffer overflow dp[i + c] = max(dp[i] + 1, dp[i + c]); } } return dp[n];} // Driver codeint main(){ int n = 7, a = 5, b = 2, c = 5; cout << maximumSegments(n, a, b, c); return 0;}
// Java implementation to divide N into// maximum number of segments// of length a, b and cimport java.util.*; class GFG{ // function to find the maximum // number of segments static int maximumSegments(int n, int a, int b, int c) { // stores the maximum number of // segments each index can have int dp[] = new int[n + 10]; // initialize with -1 Arrays.fill(dp, -1); // 0th index will have 0 segments // base case dp[0] = 0; // traverse for all possible // segments till n for (int i = 0; i < n; i++) { if (dp[i] != -1) { // conditions if(i + a <= n ) //avoid buffer overflow dp[i + a] = Math.max(dp[i] + 1, dp[i + a]); if(i + b <= n ) //avoid buffer overflow dp[i + b] = Math.max(dp[i] + 1, dp[i + b]); if(i + c <= n ) //avoid buffer overflow dp[i + c] = Math.max(dp[i] + 1, dp[i + c]); } } return dp[n]; } // Driver code public static void main(String arg[]) { int n = 7, a = 5, b = 2, c = 5; System.out.print(maximumSegments(n, a, b, c)); }} // This code is contributed by Anant Agarwal.
# Python implementation# to divide N into maximum# number of segments of# length a, b and c # function to find# the maximum number# of segmentsdef maximumSegments(n, a, b, c) : # stores the maximum # number of segments # each index can have dp = [-1] * (n + 10) # 0th index will have # 0 segments base case dp[0] = 0 # traverse for all possible # segments till n for i in range(0, n) : if (dp[i] != -1) : # conditions if(i + a <= n ): # avoid buffer overflow dp[i + a] = max(dp[i] + 1, dp[i + a]) if(i + b <= n ): # avoid buffer overflow dp[i + b] = max(dp[i] + 1, dp[i + b]) if(i + c <= n ): # avoid buffer overflow dp[i + c] = max(dp[i] + 1, dp[i + c]) return dp[n] # Driver coden = 7a = 5b = 2c = 5print (maximumSegments(n, a, b, c)) # This code is contributed by# Manish Shaw(manishshaw1)
// C# implementation to divide N into// maximum number of segments// of length a, b and cusing System; class GFG{ // function to find the maximum // number of segments static int maximumSegments(int n, int a, int b, int c) { // stores the maximum number of // segments each index can have int []dp = new int[n + 10]; // initialize with -1 for(int i = 0; i < n + 10; i++) dp[i]= -1; // 0th index will have 0 segments // base case dp[0] = 0; // traverse for all possible // segments till n for (int i = 0; i < n; i++) { if (dp[i] != -1) { // conditions if(i + a <= n ) // avoid buffer overflow dp[i + a] = Math.Max(dp[i] + 1, dp[i + a]); if(i + b <= n ) // avoid buffer overflow dp[i + b] = Math.Max(dp[i] + 1, dp[i + b]); if(i + c <= n ) // avoid buffer overflow dp[i + c] = Math.Max(dp[i] + 1, dp[i + c]); } } return dp[n]; } // Driver code public static void Main() { int n = 7, a = 5, b = 2, c = 5; Console.Write(maximumSegments(n, a, b, c)); }} // This code is contributed by nitin mittal
<?php// PHP implementation to divide// N into maximum number of// segments of length a, b and c // function to find the maximum// number of segmentsfunction maximumSegments($n, $a, $b, $c){ // stores the maximum // number of segments // each index can have $dp = array(); // initialize with -1 for($i = 0; $i < $n + 10; $i++) $dp[$i]= -1; // 0th index will have // 0 segments base case $dp[0] = 0; // traverse for all possible // segments till n for ($i = 0; $i < $n; $i++) { if ($dp[$i] != -1) { // conditions if($i + $a <= $n ) // avoid buffer overflow $dp[$i + $a] = max($dp[$i] + 1, $dp[$i + $a]); if($i + $b <= $n ) // avoid buffer overflow $dp[$i + $b] = max($dp[$i] + 1, $dp[$i + $b]); if($i + $c <= $n ) // avoid buffer overflow $dp[$i + $c] = max($dp[$i] + 1, $dp[$i + $c]); } } return $dp[$n];} // Driver code$n = 7; $a = 5;$b = 2; $c = 5;echo (maximumSegments($n, $a, $b, $c)); // This code is contributed by// Manish Shaw(manishshaw1)?>
<script>// JavaScript program implementation to divide N into// maximum number of segments// of length a, b and c // function to find the maximum // number of segments function maximumSegments(n, a, b, c) { // stores the maximum number of // segments each index can have let dp = []; // initialize with -1 for(let i = 0; i < n + 10; i++) dp[i]= -1; // 0th index will have 0 segments // base case dp[0] = 0; // traverse for all possible // segments till n for (let i = 0; i < n; i++) { if (dp[i] != -1) { // conditions if(i + a <= n ) //avoid buffer overflow dp[i + a] = Math.max(dp[i] + 1, dp[i + a]); if(i + b <= n ) //avoid buffer overflow dp[i + b] = Math.max(dp[i] + 1, dp[i + b]); if(i + c <= n ) //avoid buffer overflow dp[i + c] = Math.max(dp[i] + 1, dp[i + c]); } } return dp[n]; } // Driver Code let n = 7, a = 5, b = 2, c = 5; document.write(maximumSegments(n, a, b, c)); // This code is contributed by susmitakundugoaldanga.</script>
Output :
2
Time complexity : O(n)
nitin mittal
manishshaw1
rishikkumar
susmitakundugoaldanga
Dynamic Programming
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Optimal Substructure Property in Dynamic Programming | DP-2
Optimal Strategy for a Game | DP-31
Maximum sum such that no two elements are adjacent
Min Cost Path | DP-6
Maximum Subarray Sum using Divide and Conquer algorithm
Weighted Job Scheduling
Optimal Binary Search Tree | DP-24
3 Different ways to print Fibonacci series in Java
Binomial Coefficient | DP-9
Greedy approach vs Dynamic programming
|
[
{
"code": null,
"e": 24698,
"s": 24670,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 24825,
"s": 24698,
"text": "Given a positive integer N, find the maximum number of segments of lengths a, b and c that can be formed from N . Examples : "
},
{
"code": null,
"e": 25143,
"s": 24825,
"text": "Input : N = 7, a = 5, b, = 2, c = 5 \nOutput : 2 \nN can be divided into 2 segments of lengths\n2 and 5. For the second example,\n\nInput : N = 17, a = 2, b = 1, c = 3 \nOutput : 17 \nN can be divided into 17 segments of 1 or 8 \nsegments of 2 and 1 segment of 1. But 17 segments\nof 1 is greater than 9 segments of 2 and 1. "
},
{
"code": null,
"e": 25464,
"s": 25145,
"text": "Approach : The approach used is Dynamic Programming. The base dp0 will be 0 as initially it has no segments. After that, iterate from 1 to n, and for each of the 3 states i.e, dpi+a, dpi+b and dpi+c, store the maximum value obtained by either using or not using the a, b or c segment. The 3 states to deal with are : "
},
{
"code": null,
"e": 25539,
"s": 25464,
"text": "dpi+a=max(dpi+1, dpi+a); dpi+b=max(dpi+1, dpi+b); dpi+c=max(dpi+1, dpi+c);"
},
{
"code": null,
"e": 25585,
"s": 25539,
"text": "Below is the implementation of above idea : "
},
{
"code": null,
"e": 25589,
"s": 25585,
"text": "C++"
},
{
"code": null,
"e": 25594,
"s": 25589,
"text": "Java"
},
{
"code": null,
"e": 25602,
"s": 25594,
"text": "Python3"
},
{
"code": null,
"e": 25605,
"s": 25602,
"text": "C#"
},
{
"code": null,
"e": 25609,
"s": 25605,
"text": "PHP"
},
{
"code": null,
"e": 25620,
"s": 25609,
"text": "Javascript"
},
{
"code": "// C++ implementation to divide N into// maximum number of segments// of length a, b and c#include <bits/stdc++.h>using namespace std; // function to find the maximum// number of segmentsint maximumSegments(int n, int a, int b, int c){ // stores the maximum number of // segments each index can have int dp[n + 1]; // initialize with -1 memset(dp, -1, sizeof(dp)); // 0th index will have 0 segments // base case dp[0] = 0; // traverse for all possible // segments till n for (int i = 0; i < n; i++) { if (dp[i] != -1) { // conditions if(i + a <= n ) //avoid buffer overflow dp[i + a] = max(dp[i] + 1, dp[i + a]); if(i + b <= n ) //avoid buffer overflow dp[i + b] = max(dp[i] + 1, dp[i + b]); if(i + c <= n ) //avoid buffer overflow dp[i + c] = max(dp[i] + 1, dp[i + c]); } } return dp[n];} // Driver codeint main(){ int n = 7, a = 5, b = 2, c = 5; cout << maximumSegments(n, a, b, c); return 0;}",
"e": 26842,
"s": 25620,
"text": null
},
{
"code": "// Java implementation to divide N into// maximum number of segments// of length a, b and cimport java.util.*; class GFG{ // function to find the maximum // number of segments static int maximumSegments(int n, int a, int b, int c) { // stores the maximum number of // segments each index can have int dp[] = new int[n + 10]; // initialize with -1 Arrays.fill(dp, -1); // 0th index will have 0 segments // base case dp[0] = 0; // traverse for all possible // segments till n for (int i = 0; i < n; i++) { if (dp[i] != -1) { // conditions if(i + a <= n ) //avoid buffer overflow dp[i + a] = Math.max(dp[i] + 1, dp[i + a]); if(i + b <= n ) //avoid buffer overflow dp[i + b] = Math.max(dp[i] + 1, dp[i + b]); if(i + c <= n ) //avoid buffer overflow dp[i + c] = Math.max(dp[i] + 1, dp[i + c]); } } return dp[n]; } // Driver code public static void main(String arg[]) { int n = 7, a = 5, b = 2, c = 5; System.out.print(maximumSegments(n, a, b, c)); }} // This code is contributed by Anant Agarwal.",
"e": 28340,
"s": 26842,
"text": null
},
{
"code": "# Python implementation# to divide N into maximum# number of segments of# length a, b and c # function to find# the maximum number# of segmentsdef maximumSegments(n, a, b, c) : # stores the maximum # number of segments # each index can have dp = [-1] * (n + 10) # 0th index will have # 0 segments base case dp[0] = 0 # traverse for all possible # segments till n for i in range(0, n) : if (dp[i] != -1) : # conditions if(i + a <= n ): # avoid buffer overflow dp[i + a] = max(dp[i] + 1, dp[i + a]) if(i + b <= n ): # avoid buffer overflow dp[i + b] = max(dp[i] + 1, dp[i + b]) if(i + c <= n ): # avoid buffer overflow dp[i + c] = max(dp[i] + 1, dp[i + c]) return dp[n] # Driver coden = 7a = 5b = 2c = 5print (maximumSegments(n, a, b, c)) # This code is contributed by# Manish Shaw(manishshaw1)",
"e": 29447,
"s": 28340,
"text": null
},
{
"code": "// C# implementation to divide N into// maximum number of segments// of length a, b and cusing System; class GFG{ // function to find the maximum // number of segments static int maximumSegments(int n, int a, int b, int c) { // stores the maximum number of // segments each index can have int []dp = new int[n + 10]; // initialize with -1 for(int i = 0; i < n + 10; i++) dp[i]= -1; // 0th index will have 0 segments // base case dp[0] = 0; // traverse for all possible // segments till n for (int i = 0; i < n; i++) { if (dp[i] != -1) { // conditions if(i + a <= n ) // avoid buffer overflow dp[i + a] = Math.Max(dp[i] + 1, dp[i + a]); if(i + b <= n ) // avoid buffer overflow dp[i + b] = Math.Max(dp[i] + 1, dp[i + b]); if(i + c <= n ) // avoid buffer overflow dp[i + c] = Math.Max(dp[i] + 1, dp[i + c]); } } return dp[n]; } // Driver code public static void Main() { int n = 7, a = 5, b = 2, c = 5; Console.Write(maximumSegments(n, a, b, c)); }} // This code is contributed by nitin mittal",
"e": 30957,
"s": 29447,
"text": null
},
{
"code": "<?php// PHP implementation to divide// N into maximum number of// segments of length a, b and c // function to find the maximum// number of segmentsfunction maximumSegments($n, $a, $b, $c){ // stores the maximum // number of segments // each index can have $dp = array(); // initialize with -1 for($i = 0; $i < $n + 10; $i++) $dp[$i]= -1; // 0th index will have // 0 segments base case $dp[0] = 0; // traverse for all possible // segments till n for ($i = 0; $i < $n; $i++) { if ($dp[$i] != -1) { // conditions if($i + $a <= $n ) // avoid buffer overflow $dp[$i + $a] = max($dp[$i] + 1, $dp[$i + $a]); if($i + $b <= $n ) // avoid buffer overflow $dp[$i + $b] = max($dp[$i] + 1, $dp[$i + $b]); if($i + $c <= $n ) // avoid buffer overflow $dp[$i + $c] = max($dp[$i] + 1, $dp[$i + $c]); } } return $dp[$n];} // Driver code$n = 7; $a = 5;$b = 2; $c = 5;echo (maximumSegments($n, $a, $b, $c)); // This code is contributed by// Manish Shaw(manishshaw1)?>",
"e": 32254,
"s": 30957,
"text": null
},
{
"code": "<script>// JavaScript program implementation to divide N into// maximum number of segments// of length a, b and c // function to find the maximum // number of segments function maximumSegments(n, a, b, c) { // stores the maximum number of // segments each index can have let dp = []; // initialize with -1 for(let i = 0; i < n + 10; i++) dp[i]= -1; // 0th index will have 0 segments // base case dp[0] = 0; // traverse for all possible // segments till n for (let i = 0; i < n; i++) { if (dp[i] != -1) { // conditions if(i + a <= n ) //avoid buffer overflow dp[i + a] = Math.max(dp[i] + 1, dp[i + a]); if(i + b <= n ) //avoid buffer overflow dp[i + b] = Math.max(dp[i] + 1, dp[i + b]); if(i + c <= n ) //avoid buffer overflow dp[i + c] = Math.max(dp[i] + 1, dp[i + c]); } } return dp[n]; } // Driver Code let n = 7, a = 5, b = 2, c = 5; document.write(maximumSegments(n, a, b, c)); // This code is contributed by susmitakundugoaldanga.</script>",
"e": 33684,
"s": 32254,
"text": null
},
{
"code": null,
"e": 33695,
"s": 33684,
"text": "Output : "
},
{
"code": null,
"e": 33697,
"s": 33695,
"text": "2"
},
{
"code": null,
"e": 33721,
"s": 33697,
"text": "Time complexity : O(n) "
},
{
"code": null,
"e": 33734,
"s": 33721,
"text": "nitin mittal"
},
{
"code": null,
"e": 33746,
"s": 33734,
"text": "manishshaw1"
},
{
"code": null,
"e": 33758,
"s": 33746,
"text": "rishikkumar"
},
{
"code": null,
"e": 33780,
"s": 33758,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 33800,
"s": 33780,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 33820,
"s": 33800,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 33918,
"s": 33820,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33927,
"s": 33918,
"text": "Comments"
},
{
"code": null,
"e": 33940,
"s": 33927,
"text": "Old Comments"
},
{
"code": null,
"e": 34000,
"s": 33940,
"text": "Optimal Substructure Property in Dynamic Programming | DP-2"
},
{
"code": null,
"e": 34036,
"s": 34000,
"text": "Optimal Strategy for a Game | DP-31"
},
{
"code": null,
"e": 34087,
"s": 34036,
"text": "Maximum sum such that no two elements are adjacent"
},
{
"code": null,
"e": 34108,
"s": 34087,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 34164,
"s": 34108,
"text": "Maximum Subarray Sum using Divide and Conquer algorithm"
},
{
"code": null,
"e": 34188,
"s": 34164,
"text": "Weighted Job Scheduling"
},
{
"code": null,
"e": 34223,
"s": 34188,
"text": "Optimal Binary Search Tree | DP-24"
},
{
"code": null,
"e": 34274,
"s": 34223,
"text": "3 Different ways to print Fibonacci series in Java"
},
{
"code": null,
"e": 34302,
"s": 34274,
"text": "Binomial Coefficient | DP-9"
}
] |
Tryit Editor v3.7
|
Tryit: HTML table - colgroup
|
[] |
ReactJS UI Ant Design Layout Component - GeeksforGeeks
|
01 Jun, 2021
Ant Design Library has this component pre-built, and it is very easy to integrate as well. The Layout component is used for handling the overall layout of a page. We can use the following approach in ReactJS to use the Ant Design Layout Component.
Layout Props:
className: It is used to pass the container className.
hasSider: It is used to indicate whether contain Sider in children or not.
style: It is used to customize the styles.
Layout.Sider Props:
breakpoint: It is used to denote the Breakpoints of the responsive layout.
className: It is used to pass the container className.
collapsed: It is used to set the current status.
collapsedWidth: It is used to denote the width of the collapsed sidebar.
collapsible: It is used to indicate whether it can be collapsed or not.
defaultCollapsed: It is used to set the initial status.
reverseArrow: It is used to reverse the direction of the arrow, for a sider that expands from the right.
style: It is used to customize the styles.
theme: It is used to denote the Color theme of the sidebar.
trigger: It is used to specify the customized trigger.
width: It is used to denote the width of the sidebar.
zeroWidthTriggerStyle: When collapsedWidth is 0, it is used to customize the styles of the special trigger.
onBreakpoint: It is a callback function that is triggered when breakpoints changed.
onCollapse: It is a callback function that is triggered when clicking the trigger or activating the responsive layout.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install antd
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react'import "antd/dist/antd.css";import { Layout } from 'antd'; const { Header, Footer, Sider, Content } = Layout; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design Layout Component</h4> <> <Layout> <Sider style={{ backgroundColor: 'grey' }}> Sample Sider </Sider> <Layout style={{ backgroundColor: 'lightblue' }}> <Header style={{ backgroundColor: 'green' }}> Sample Header </Header> <Content style={{ backgroundColor: 'yellow' }}> Sample Content </Content> <Footer style={{ backgroundColor: 'green' }}> Sample Footer </Footer> </Layout> </Layout> </> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://ant.design/components/layout/
ReactJS-Ant Design
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
Create a Responsive Navbar using ReactJS
How to pass data from one component to other component in ReactJS ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 34238,
"s": 34210,
"text": "\n01 Jun, 2021"
},
{
"code": null,
"e": 34486,
"s": 34238,
"text": "Ant Design Library has this component pre-built, and it is very easy to integrate as well. The Layout component is used for handling the overall layout of a page. We can use the following approach in ReactJS to use the Ant Design Layout Component."
},
{
"code": null,
"e": 34500,
"s": 34486,
"text": "Layout Props:"
},
{
"code": null,
"e": 34555,
"s": 34500,
"text": "className: It is used to pass the container className."
},
{
"code": null,
"e": 34630,
"s": 34555,
"text": "hasSider: It is used to indicate whether contain Sider in children or not."
},
{
"code": null,
"e": 34673,
"s": 34630,
"text": "style: It is used to customize the styles."
},
{
"code": null,
"e": 34693,
"s": 34673,
"text": "Layout.Sider Props:"
},
{
"code": null,
"e": 34768,
"s": 34693,
"text": "breakpoint: It is used to denote the Breakpoints of the responsive layout."
},
{
"code": null,
"e": 34823,
"s": 34768,
"text": "className: It is used to pass the container className."
},
{
"code": null,
"e": 34872,
"s": 34823,
"text": "collapsed: It is used to set the current status."
},
{
"code": null,
"e": 34945,
"s": 34872,
"text": "collapsedWidth: It is used to denote the width of the collapsed sidebar."
},
{
"code": null,
"e": 35017,
"s": 34945,
"text": "collapsible: It is used to indicate whether it can be collapsed or not."
},
{
"code": null,
"e": 35073,
"s": 35017,
"text": "defaultCollapsed: It is used to set the initial status."
},
{
"code": null,
"e": 35178,
"s": 35073,
"text": "reverseArrow: It is used to reverse the direction of the arrow, for a sider that expands from the right."
},
{
"code": null,
"e": 35221,
"s": 35178,
"text": "style: It is used to customize the styles."
},
{
"code": null,
"e": 35281,
"s": 35221,
"text": "theme: It is used to denote the Color theme of the sidebar."
},
{
"code": null,
"e": 35336,
"s": 35281,
"text": "trigger: It is used to specify the customized trigger."
},
{
"code": null,
"e": 35390,
"s": 35336,
"text": "width: It is used to denote the width of the sidebar."
},
{
"code": null,
"e": 35498,
"s": 35390,
"text": "zeroWidthTriggerStyle: When collapsedWidth is 0, it is used to customize the styles of the special trigger."
},
{
"code": null,
"e": 35582,
"s": 35498,
"text": "onBreakpoint: It is a callback function that is triggered when breakpoints changed."
},
{
"code": null,
"e": 35701,
"s": 35582,
"text": "onCollapse: It is a callback function that is triggered when clicking the trigger or activating the responsive layout."
},
{
"code": null,
"e": 35751,
"s": 35701,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 35846,
"s": 35751,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 35910,
"s": 35846,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 35942,
"s": 35910,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 36055,
"s": 35942,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 36155,
"s": 36055,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 36169,
"s": 36155,
"text": "cd foldername"
},
{
"code": null,
"e": 36290,
"s": 36169,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd"
},
{
"code": null,
"e": 36395,
"s": 36290,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 36412,
"s": 36395,
"text": "npm install antd"
},
{
"code": null,
"e": 36464,
"s": 36412,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 36482,
"s": 36464,
"text": "Project Structure"
},
{
"code": null,
"e": 36612,
"s": 36482,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 36619,
"s": 36612,
"text": "App.js"
},
{
"code": "import React from 'react'import \"antd/dist/antd.css\";import { Layout } from 'antd'; const { Header, Footer, Sider, Content } = Layout; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design Layout Component</h4> <> <Layout> <Sider style={{ backgroundColor: 'grey' }}> Sample Sider </Sider> <Layout style={{ backgroundColor: 'lightblue' }}> <Header style={{ backgroundColor: 'green' }}> Sample Header </Header> <Content style={{ backgroundColor: 'yellow' }}> Sample Content </Content> <Footer style={{ backgroundColor: 'green' }}> Sample Footer </Footer> </Layout> </Layout> </> </div> );}",
"e": 37478,
"s": 36619,
"text": null
},
{
"code": null,
"e": 37591,
"s": 37478,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 37601,
"s": 37591,
"text": "npm start"
},
{
"code": null,
"e": 37700,
"s": 37601,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 37749,
"s": 37700,
"text": "Reference: https://ant.design/components/layout/"
},
{
"code": null,
"e": 37768,
"s": 37749,
"text": "ReactJS-Ant Design"
},
{
"code": null,
"e": 37776,
"s": 37768,
"text": "ReactJS"
},
{
"code": null,
"e": 37793,
"s": 37776,
"text": "Web Technologies"
},
{
"code": null,
"e": 37891,
"s": 37793,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37900,
"s": 37891,
"text": "Comments"
},
{
"code": null,
"e": 37913,
"s": 37900,
"text": "Old Comments"
},
{
"code": null,
"e": 37956,
"s": 37913,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 38001,
"s": 37956,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 38066,
"s": 38001,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 38107,
"s": 38066,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 38175,
"s": 38107,
"text": "How to pass data from one component to other component in ReactJS ?"
},
{
"code": null,
"e": 38217,
"s": 38175,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 38250,
"s": 38217,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 38300,
"s": 38250,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 38362,
"s": 38300,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Blob conversion function in Cassandra - GeeksforGeeks
|
03 Dec, 2019
In Cassandra, Blob data type represents constant hexadecimal data type and the number is defined as 0[xX](hex)+ where hex means hexadecimal. It is useful to store a short string or small images.
In this article we will discuss Blob conversion function which converts the native types into binary data (blob):
typeAsBlob(value)
blobAsType(value)
Let’s understand with an example.
To create table function_test1 used the following CQL query.
CREATE TABLE function_test1 (
Name varchar PRIMARY KEY,
type_value blob
);
To insert data into the table using the following CQL query.
INSERT INTO function_test1 (Name, type_value)
VALUES ('Ashish', bigintAsBlob(5));
INSERT INTO function_test1 (Name, type_value)
VALUES ('Rana', bigintAsBlob(9));
To read the data using the following CQL query.
SELECT *
FROM function_test1;
Output:
Now, to convert blobAsBigint then first update the table by using the following CQL query.
ALTER TABLE function_test1 ADD Id bigint;
Now, again insert data into the updated table. So, let’s have a look.
INSERT INTO function_test1 (Name, Id)
VALUES ('Ashish', blobAsBigint(0x0000000000000005));
INSERT INTO function_test1 (Name, Id)
VALUES ('Rana', blobAsBigint(0x0000000000000009));
To see the final output used the following CQL query.
SELECT *
FROM function_test1;
Output:
Apache
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL Trigger | Student Database
Introduction of ER Model
Introduction of B-Tree
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
SQL | Views
Difference between DDL and DML in DBMS
Third Normal Form (3NF)
Second Normal Form (2NF)
CTE in SQL
|
[
{
"code": null,
"e": 24038,
"s": 24010,
"text": "\n03 Dec, 2019"
},
{
"code": null,
"e": 24233,
"s": 24038,
"text": "In Cassandra, Blob data type represents constant hexadecimal data type and the number is defined as 0[xX](hex)+ where hex means hexadecimal. It is useful to store a short string or small images."
},
{
"code": null,
"e": 24347,
"s": 24233,
"text": "In this article we will discuss Blob conversion function which converts the native types into binary data (blob):"
},
{
"code": null,
"e": 24384,
"s": 24347,
"text": "typeAsBlob(value)\nblobAsType(value) "
},
{
"code": null,
"e": 24418,
"s": 24384,
"text": "Let’s understand with an example."
},
{
"code": null,
"e": 24479,
"s": 24418,
"text": "To create table function_test1 used the following CQL query."
},
{
"code": null,
"e": 24558,
"s": 24479,
"text": "CREATE TABLE function_test1 ( \nName varchar PRIMARY KEY, \ntype_value blob\n ); "
},
{
"code": null,
"e": 24619,
"s": 24558,
"text": "To insert data into the table using the following CQL query."
},
{
"code": null,
"e": 24799,
"s": 24619,
"text": "INSERT INTO function_test1 (Name, type_value) \n VALUES ('Ashish', bigintAsBlob(5));\nINSERT INTO function_test1 (Name, type_value) \n VALUES ('Rana', bigintAsBlob(9)); "
},
{
"code": null,
"e": 24847,
"s": 24799,
"text": "To read the data using the following CQL query."
},
{
"code": null,
"e": 24879,
"s": 24847,
"text": "SELECT * \nFROM function_test1; "
},
{
"code": null,
"e": 24887,
"s": 24879,
"text": "Output:"
},
{
"code": null,
"e": 24978,
"s": 24887,
"text": "Now, to convert blobAsBigint then first update the table by using the following CQL query."
},
{
"code": null,
"e": 25021,
"s": 24978,
"text": "ALTER TABLE function_test1 ADD Id bigint; "
},
{
"code": null,
"e": 25091,
"s": 25021,
"text": "Now, again insert data into the updated table. So, let’s have a look."
},
{
"code": null,
"e": 25288,
"s": 25091,
"text": "INSERT INTO function_test1 (Name, Id) \n VALUES ('Ashish', blobAsBigint(0x0000000000000005));\nINSERT INTO function_test1 (Name, Id) \n VALUES ('Rana', blobAsBigint(0x0000000000000009)); "
},
{
"code": null,
"e": 25342,
"s": 25288,
"text": "To see the final output used the following CQL query."
},
{
"code": null,
"e": 25374,
"s": 25342,
"text": "SELECT * \nFROM function_test1; "
},
{
"code": null,
"e": 25382,
"s": 25374,
"text": "Output:"
},
{
"code": null,
"e": 25389,
"s": 25382,
"text": "Apache"
},
{
"code": null,
"e": 25394,
"s": 25389,
"text": "DBMS"
},
{
"code": null,
"e": 25399,
"s": 25394,
"text": "DBMS"
},
{
"code": null,
"e": 25497,
"s": 25399,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25506,
"s": 25497,
"text": "Comments"
},
{
"code": null,
"e": 25519,
"s": 25506,
"text": "Old Comments"
},
{
"code": null,
"e": 25550,
"s": 25519,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 25575,
"s": 25550,
"text": "Introduction of ER Model"
},
{
"code": null,
"e": 25598,
"s": 25575,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 25651,
"s": 25598,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 25709,
"s": 25651,
"text": "Introduction of DBMS (Database Management System) | Set 1"
},
{
"code": null,
"e": 25721,
"s": 25709,
"text": "SQL | Views"
},
{
"code": null,
"e": 25760,
"s": 25721,
"text": "Difference between DDL and DML in DBMS"
},
{
"code": null,
"e": 25784,
"s": 25760,
"text": "Third Normal Form (3NF)"
},
{
"code": null,
"e": 25809,
"s": 25784,
"text": "Second Normal Form (2NF)"
}
] |
What's the best way to trim std::string in C++?
|
Here we will see how to trim the strings in C++. The trimming string means removing whitespaces from left and right part of the string.
To trim the C++ string, we will use the boost string library. In that library, there are two different methods called trim_left() and trim_right(). To trim string completely, we can use both of them.
#include<iostream>
#include<boost/algorithm/string.hpp>
using namespace std;
main(){
string myStr = " This is a string ";
cout << "The string is: (" << myStr << ")" << endl;
//trim the string
boost::trim_right(myStr);
cout << "The string is: (" << myStr << ")" << endl;
boost::trim_left(myStr);
cout << "The string is: (" << myStr << ")" << endl;
}
$ g++ test.cpp
$ ./a.out
The string is: ( This is a string )
The string is: ( This is a string)
The string is: (This is a string)
$
|
[
{
"code": null,
"e": 1198,
"s": 1062,
"text": "Here we will see how to trim the strings in C++. The trimming string means removing whitespaces from left and right part of the string."
},
{
"code": null,
"e": 1398,
"s": 1198,
"text": "To trim the C++ string, we will use the boost string library. In that library, there are two different methods called trim_left() and trim_right(). To trim string completely, we can use both of them."
},
{
"code": null,
"e": 1768,
"s": 1398,
"text": "#include<iostream>\n#include<boost/algorithm/string.hpp>\nusing namespace std;\nmain(){\n string myStr = \" This is a string \";\n cout << \"The string is: (\" << myStr << \")\" << endl;\n //trim the string\n boost::trim_right(myStr);\n cout << \"The string is: (\" << myStr << \")\" << endl;\n boost::trim_left(myStr);\n cout << \"The string is: (\" << myStr << \")\" << endl;\n}"
},
{
"code": null,
"e": 1920,
"s": 1768,
"text": "$ g++ test.cpp\n$ ./a.out\nThe string is: ( This is a string )\nThe string is: ( This is a string)\nThe string is: (This is a string)\n$"
}
] |
Batch statement in Cassandra - GeeksforGeeks
|
09 Dec, 2019
In this article, we will discuss the BATCH statement, good and misuse of BATCH statement and how we can use the BATCH statement in single and multiple partitions in Cassandra which is supported by Cassandra Query Language (CQL). let’s discuss one by one.
We can use the BATCH statement in single and multiple partitions which ensure atomicity for both the operations.
So, let’s take an example.First, we create a table namely as bank_emp_data which has Id, Name, emp_start_date, emp_end_date fields. Let’s have a look.
CREATE TABLE bank_emp_data(
E_id int,
Name text,
emp_start_date date,
emp_end_date date,
PRIMARY KEY (E_id, Name)
);
Now, here we are going to write data into bank_emp_data table without using BATCH statement. Let’s have a look.
INSERT INTO bank_emp_data(E_id, Name, emp_start_date, emp_end_date)
VALUES (1005, 'Ashish', '2019-12-05', '2025-12-05');
INSERT INTO bank_emp_data(E_id, Name, emp_start_date)
VALUES (1006, 'Rana', '2019-12-05');
INSERT INTO bank_emp_data(E_id, Name, emp_end_date)
VALUES (1007, 'shiv', '2020-12-05');
To see the output used the following CQL query.
Select *
From bank_emp_data;
Output:
Now, to update an existing row in bank_emp_data table used the following CQL query given below.
Update bank_emp_data set emp_start_date = '2019-12-05'
where E_id = 1007 and Name= 'shiv';
To see the updated row used the following CQL query.
Select *
from bank_emp_data;
Output:
Now, here we are using BATCH statement and it also shows how we can good use of BATCH statement. Let’s have a look.
BEGIN BATCH
INSERT INTO bank_emp_data(E_id, Name, emp_start_date, emp_end_date)
VALUES (1005, 'Ashish', '2019-12-05', '2025-12-05');
INSERT INTO bank_emp_data(E_id, Name, emp_start_date)
VALUES (1006, 'Rana', '2019-12-05');
INSERT INTO bank_emp_data(E_id, Name, emp_end_date)
VALUES (1007, 'shiv', '2020-12-05');
Update bank_emp_data set emp_start_date = '2019-12-05'
where E_id = 1007 and Name= 'shiv';
APPLY BATCH;
Now, let’s see the output of bank_emp_data using BATCH statement.
Select *
from bank_emp_data;
Multiple partition batch:We can write data into different tables by using the BATCH statement.
Let’s understand with an example.
Table: Emp_data
create table Emp_data(
E_id int primary key,
Name text,
city text
);
Table: Emp_data_copy
create table Emp_data_copy(
Name text primary key,
E_id int
);
Now, we are using BATCH to insert data into different tables.
BEGIN BATCH
INSERT INTO Emp_data (E_id, Name, city)
VALUES (101, 'Ashish', 'california');
INSERT INTO Emp_data_copy (Name, E_id)
VALUES ('Ashish', 101);
APPLY BATCH;
Now, let’s see the output of Emp_data table.
SELECT *
FROM Emp_data;
Output:
Now, let’s see the output of the Emp_data_copy table.
SELECT *
FROM Emp_data_copy;
Output:
Apache
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction of B-Tree
Difference between Clustered and Non-clustered index
CTE in SQL
Introduction of ER Model
SQL | Views
SQL Interview Questions
Third Normal Form (3NF)
SQL | GROUP BY
Difference between Primary Key and Foreign Key
Types of Functional dependencies in DBMS
|
[
{
"code": null,
"e": 24418,
"s": 24390,
"text": "\n09 Dec, 2019"
},
{
"code": null,
"e": 24673,
"s": 24418,
"text": "In this article, we will discuss the BATCH statement, good and misuse of BATCH statement and how we can use the BATCH statement in single and multiple partitions in Cassandra which is supported by Cassandra Query Language (CQL). let’s discuss one by one."
},
{
"code": null,
"e": 24786,
"s": 24673,
"text": "We can use the BATCH statement in single and multiple partitions which ensure atomicity for both the operations."
},
{
"code": null,
"e": 24937,
"s": 24786,
"text": "So, let’s take an example.First, we create a table namely as bank_emp_data which has Id, Name, emp_start_date, emp_end_date fields. Let’s have a look."
},
{
"code": null,
"e": 25056,
"s": 24937,
"text": "CREATE TABLE bank_emp_data(\nE_id int,\nName text,\nemp_start_date date, \nemp_end_date date,\nPRIMARY KEY (E_id, Name)\n); "
},
{
"code": null,
"e": 25168,
"s": 25056,
"text": "Now, here we are going to write data into bank_emp_data table without using BATCH statement. Let’s have a look."
},
{
"code": null,
"e": 25475,
"s": 25168,
"text": "INSERT INTO bank_emp_data(E_id, Name, emp_start_date, emp_end_date) \nVALUES (1005, 'Ashish', '2019-12-05', '2025-12-05');\n\nINSERT INTO bank_emp_data(E_id, Name, emp_start_date) \nVALUES (1006, 'Rana', '2019-12-05');\n\nINSERT INTO bank_emp_data(E_id, Name, emp_end_date) \nVALUES (1007, 'shiv', '2020-12-05'); "
},
{
"code": null,
"e": 25523,
"s": 25475,
"text": "To see the output used the following CQL query."
},
{
"code": null,
"e": 25554,
"s": 25523,
"text": "Select * \nFrom bank_emp_data; "
},
{
"code": null,
"e": 25562,
"s": 25554,
"text": "Output:"
},
{
"code": null,
"e": 25658,
"s": 25562,
"text": "Now, to update an existing row in bank_emp_data table used the following CQL query given below."
},
{
"code": null,
"e": 25752,
"s": 25658,
"text": "Update bank_emp_data set emp_start_date = '2019-12-05' \nwhere E_id = 1007 and Name= 'shiv'; "
},
{
"code": null,
"e": 25805,
"s": 25752,
"text": "To see the updated row used the following CQL query."
},
{
"code": null,
"e": 25836,
"s": 25805,
"text": "Select * \nfrom bank_emp_data; "
},
{
"code": null,
"e": 25844,
"s": 25836,
"text": "Output:"
},
{
"code": null,
"e": 25960,
"s": 25844,
"text": "Now, here we are using BATCH statement and it also shows how we can good use of BATCH statement. Let’s have a look."
},
{
"code": null,
"e": 26386,
"s": 25960,
"text": "BEGIN BATCH\nINSERT INTO bank_emp_data(E_id, Name, emp_start_date, emp_end_date) \nVALUES (1005, 'Ashish', '2019-12-05', '2025-12-05');\n\nINSERT INTO bank_emp_data(E_id, Name, emp_start_date) \nVALUES (1006, 'Rana', '2019-12-05');\n\nINSERT INTO bank_emp_data(E_id, Name, emp_end_date) \nVALUES (1007, 'shiv', '2020-12-05');\n\nUpdate bank_emp_data set emp_start_date = '2019-12-05' \nwhere E_id = 1007 and Name= 'shiv'; \nAPPLY BATCH; "
},
{
"code": null,
"e": 26452,
"s": 26386,
"text": "Now, let’s see the output of bank_emp_data using BATCH statement."
},
{
"code": null,
"e": 26483,
"s": 26452,
"text": "Select * \nfrom bank_emp_data; "
},
{
"code": null,
"e": 26578,
"s": 26483,
"text": "Multiple partition batch:We can write data into different tables by using the BATCH statement."
},
{
"code": null,
"e": 26612,
"s": 26578,
"text": "Let’s understand with an example."
},
{
"code": null,
"e": 26628,
"s": 26612,
"text": "Table: Emp_data"
},
{
"code": null,
"e": 26698,
"s": 26628,
"text": "create table Emp_data(\nE_id int primary key,\nName text,\ncity text\n); "
},
{
"code": null,
"e": 26719,
"s": 26698,
"text": "Table: Emp_data_copy"
},
{
"code": null,
"e": 26783,
"s": 26719,
"text": "create table Emp_data_copy(\nName text primary key,\nE_id int\n); "
},
{
"code": null,
"e": 26845,
"s": 26783,
"text": "Now, we are using BATCH to insert data into different tables."
},
{
"code": null,
"e": 27015,
"s": 26845,
"text": "BEGIN BATCH\nINSERT INTO Emp_data (E_id, Name, city) \nVALUES (101, 'Ashish', 'california');\n\nINSERT INTO Emp_data_copy (Name, E_id) \nVALUES ('Ashish', 101);\nAPPLY BATCH; "
},
{
"code": null,
"e": 27060,
"s": 27015,
"text": "Now, let’s see the output of Emp_data table."
},
{
"code": null,
"e": 27085,
"s": 27060,
"text": "SELECT * \nFROM Emp_data;"
},
{
"code": null,
"e": 27093,
"s": 27085,
"text": "Output:"
},
{
"code": null,
"e": 27147,
"s": 27093,
"text": "Now, let’s see the output of the Emp_data_copy table."
},
{
"code": null,
"e": 27177,
"s": 27147,
"text": "SELECT * \nFROM Emp_data_copy;"
},
{
"code": null,
"e": 27185,
"s": 27177,
"text": "Output:"
},
{
"code": null,
"e": 27192,
"s": 27185,
"text": "Apache"
},
{
"code": null,
"e": 27197,
"s": 27192,
"text": "DBMS"
},
{
"code": null,
"e": 27202,
"s": 27197,
"text": "DBMS"
},
{
"code": null,
"e": 27300,
"s": 27202,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27323,
"s": 27300,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 27376,
"s": 27323,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 27387,
"s": 27376,
"text": "CTE in SQL"
},
{
"code": null,
"e": 27412,
"s": 27387,
"text": "Introduction of ER Model"
},
{
"code": null,
"e": 27424,
"s": 27412,
"text": "SQL | Views"
},
{
"code": null,
"e": 27448,
"s": 27424,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 27472,
"s": 27448,
"text": "Third Normal Form (3NF)"
},
{
"code": null,
"e": 27487,
"s": 27472,
"text": "SQL | GROUP BY"
},
{
"code": null,
"e": 27534,
"s": 27487,
"text": "Difference between Primary Key and Foreign Key"
}
] |
Count of all unique paths from given source to destination in a Matrix - GeeksforGeeks
|
16 Dec, 2021
Given a 2D matrix of size n*m, a source ‘s’ and a destination ‘d’, print the count of all unique paths from given ‘s’ to ‘d’. From each cell, you can either move only to the right or down.
Examples:
Input: arr[][] = { {1, 2, 3}, {4, 5, 6} }, s = {0, 0}, d = {1, 2}Output: 3Explanation: All possible paths from source to destination are:
1 -> 4 -> 5 -> 6
1 -> 2 -> 5 -> 6
1 -> 2 -> 3 -> 6
Input: arr[][] = { {1, 2}, {3, 4} }, s = {0, 1}, d = {1, 1}Output: 1
Approach: Use recursion to move right first & then down from each cell in the path of the matrix, starting from the source. If the destination is reached, increment the count of possible paths.
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 find the// count of all possible pathsint countPaths(int i, int j, int count, int p, int q){ // Destination is reached if (i == p || j == q) { count++; return count; } // Move right count = countPaths(i, j + 1, count, p, q); // Move down count = countPaths(i + 1, j, count, p, q); return count;} // Driver program to test above functionsint main(){ vector<vector<int> > mat = { { 1, 2, 3 }, { 4, 5, 6 } }; vector<int> s = { 0, 0 }; vector<int> d = { 1, 2 }; cout << countPaths(s[0], s[1], 0, d[0], d[1]); return 0;}
// Java program for the above approachclass GFG { // Function to find the // count of all possible paths static int countPaths(int i, int j, int count, int p, int q) { // Destination is reached if (i == p || j == q) { count++; return count; } // Move right count = countPaths(i, j + 1, count, p, q); // Move down count = countPaths(i + 1, j, count, p, q); return count; } // Driver program to test above functions public static void main(String args[]) { int[] s = { 0, 0 }; int[] d = { 1, 2 }; System.out.println(countPaths(s[0], s[1], 0, d[0], d[1])); }} // This code is contributed by gfgking.
# python program for the above approach # Function to find the# count of all possible pathsdef countPaths(i, j, count, p, q): # Destination is reached if (i == p or j == q): count += 1 return count # Move right count = countPaths(i, j + 1, count, p, q) # Move down count = countPaths(i + 1, j, count, p, q) return count # Driver program to test above functionsif __name__ == "__main__": mat = [[1, 2, 3], [4, 5, 6]] s = [0, 0] d = [1, 2] print(countPaths(s[0], s[1], 0, d[0], d[1])) # This code is contributed by rakeshsahni
// C# program for the above approach using System;class GFG { // Function to find the // count of all possible paths static int countPaths(int i, int j, int count, int p, int q) { // Destination is reached if (i == p || j == q) { count++; return count; } // Move right count = countPaths(i, j + 1, count, p, q); // Move down count = countPaths(i + 1, j, count, p, q); return count; } // Driver program to test above functions public static void Main() { int[] s = { 0, 0 }; int[] d = { 1, 2 }; Console.Write(countPaths(s[0], s[1], 0, d[0], d[1])); }} // This code is contributed by gfgking.
<script> // JavaScript code for the above approach // Function to find the // count of all possible paths function countPaths(i, j, count, p, q) { // Destination is reached if (i == p || j == q) { count++; return count; } // Move right count = countPaths(i, j + 1, count, p, q); // Move down count = countPaths(i + 1, j, count, p, q); return count; } // Driver program to test above functions let mat = [[1, 2, 3], [4, 5, 6]]; let s = [0, 0]; let d = [1, 2]; document.write(countPaths(s[0], s[1], 0, d[0], d[1])); // This code is contributed by Potta Lokesh </script>
3
Time Complexity: O(n+m)Auxiliary Space: O(1)
lokeshpotta20
rakeshsahni
gfgking
Backtracking
Matrix
Recursion
Recursion
Matrix
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tug of War
Difference between Backtracking and Branch-N-Bound technique
Find if there is a path of more than k length from a source
N-Queen Problem | Local Search using Hill climbing with random neighbour
Find shortest safe route in a path with landmines
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Print a given matrix in spiral form
Find the number of islands | Set 1 (Using DFS)
|
[
{
"code": null,
"e": 24958,
"s": 24930,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 25148,
"s": 24958,
"text": "Given a 2D matrix of size n*m, a source ‘s’ and a destination ‘d’, print the count of all unique paths from given ‘s’ to ‘d’. From each cell, you can either move only to the right or down."
},
{
"code": null,
"e": 25158,
"s": 25148,
"text": "Examples:"
},
{
"code": null,
"e": 25296,
"s": 25158,
"text": "Input: arr[][] = { {1, 2, 3}, {4, 5, 6} }, s = {0, 0}, d = {1, 2}Output: 3Explanation: All possible paths from source to destination are:"
},
{
"code": null,
"e": 25313,
"s": 25296,
"text": "1 -> 4 -> 5 -> 6"
},
{
"code": null,
"e": 25330,
"s": 25313,
"text": "1 -> 2 -> 5 -> 6"
},
{
"code": null,
"e": 25347,
"s": 25330,
"text": "1 -> 2 -> 3 -> 6"
},
{
"code": null,
"e": 25416,
"s": 25347,
"text": "Input: arr[][] = { {1, 2}, {3, 4} }, s = {0, 1}, d = {1, 1}Output: 1"
},
{
"code": null,
"e": 25610,
"s": 25416,
"text": "Approach: Use recursion to move right first & then down from each cell in the path of the matrix, starting from the source. If the destination is reached, increment the count of possible paths."
},
{
"code": null,
"e": 25661,
"s": 25610,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25665,
"s": 25661,
"text": "C++"
},
{
"code": null,
"e": 25670,
"s": 25665,
"text": "Java"
},
{
"code": null,
"e": 25678,
"s": 25670,
"text": "Python3"
},
{
"code": null,
"e": 25681,
"s": 25678,
"text": "C#"
},
{
"code": null,
"e": 25692,
"s": 25681,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the// count of all possible pathsint countPaths(int i, int j, int count, int p, int q){ // Destination is reached if (i == p || j == q) { count++; return count; } // Move right count = countPaths(i, j + 1, count, p, q); // Move down count = countPaths(i + 1, j, count, p, q); return count;} // Driver program to test above functionsint main(){ vector<vector<int> > mat = { { 1, 2, 3 }, { 4, 5, 6 } }; vector<int> s = { 0, 0 }; vector<int> d = { 1, 2 }; cout << countPaths(s[0], s[1], 0, d[0], d[1]); return 0;}",
"e": 26472,
"s": 25692,
"text": null
},
{
"code": "// Java program for the above approachclass GFG { // Function to find the // count of all possible paths static int countPaths(int i, int j, int count, int p, int q) { // Destination is reached if (i == p || j == q) { count++; return count; } // Move right count = countPaths(i, j + 1, count, p, q); // Move down count = countPaths(i + 1, j, count, p, q); return count; } // Driver program to test above functions public static void main(String args[]) { int[] s = { 0, 0 }; int[] d = { 1, 2 }; System.out.println(countPaths(s[0], s[1], 0, d[0], d[1])); }} // This code is contributed by gfgking.",
"e": 27241,
"s": 26472,
"text": null
},
{
"code": "# python program for the above approach # Function to find the# count of all possible pathsdef countPaths(i, j, count, p, q): # Destination is reached if (i == p or j == q): count += 1 return count # Move right count = countPaths(i, j + 1, count, p, q) # Move down count = countPaths(i + 1, j, count, p, q) return count # Driver program to test above functionsif __name__ == \"__main__\": mat = [[1, 2, 3], [4, 5, 6]] s = [0, 0] d = [1, 2] print(countPaths(s[0], s[1], 0, d[0], d[1])) # This code is contributed by rakeshsahni",
"e": 27831,
"s": 27241,
"text": null
},
{
"code": "// C# program for the above approach using System;class GFG { // Function to find the // count of all possible paths static int countPaths(int i, int j, int count, int p, int q) { // Destination is reached if (i == p || j == q) { count++; return count; } // Move right count = countPaths(i, j + 1, count, p, q); // Move down count = countPaths(i + 1, j, count, p, q); return count; } // Driver program to test above functions public static void Main() { int[] s = { 0, 0 }; int[] d = { 1, 2 }; Console.Write(countPaths(s[0], s[1], 0, d[0], d[1])); }} // This code is contributed by gfgking.",
"e": 28583,
"s": 27831,
"text": null
},
{
"code": "<script> // JavaScript code for the above approach // Function to find the // count of all possible paths function countPaths(i, j, count, p, q) { // Destination is reached if (i == p || j == q) { count++; return count; } // Move right count = countPaths(i, j + 1, count, p, q); // Move down count = countPaths(i + 1, j, count, p, q); return count; } // Driver program to test above functions let mat = [[1, 2, 3], [4, 5, 6]]; let s = [0, 0]; let d = [1, 2]; document.write(countPaths(s[0], s[1], 0, d[0], d[1])); // This code is contributed by Potta Lokesh </script>",
"e": 29406,
"s": 28583,
"text": null
},
{
"code": null,
"e": 29411,
"s": 29409,
"text": "3"
},
{
"code": null,
"e": 29458,
"s": 29413,
"text": "Time Complexity: O(n+m)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 29474,
"s": 29460,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 29486,
"s": 29474,
"text": "rakeshsahni"
},
{
"code": null,
"e": 29494,
"s": 29486,
"text": "gfgking"
},
{
"code": null,
"e": 29507,
"s": 29494,
"text": "Backtracking"
},
{
"code": null,
"e": 29514,
"s": 29507,
"text": "Matrix"
},
{
"code": null,
"e": 29524,
"s": 29514,
"text": "Recursion"
},
{
"code": null,
"e": 29534,
"s": 29524,
"text": "Recursion"
},
{
"code": null,
"e": 29541,
"s": 29534,
"text": "Matrix"
},
{
"code": null,
"e": 29554,
"s": 29541,
"text": "Backtracking"
},
{
"code": null,
"e": 29652,
"s": 29554,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29663,
"s": 29652,
"text": "Tug of War"
},
{
"code": null,
"e": 29724,
"s": 29663,
"text": "Difference between Backtracking and Branch-N-Bound technique"
},
{
"code": null,
"e": 29784,
"s": 29724,
"text": "Find if there is a path of more than k length from a source"
},
{
"code": null,
"e": 29857,
"s": 29784,
"text": "N-Queen Problem | Local Search using Hill climbing with random neighbour"
},
{
"code": null,
"e": 29907,
"s": 29857,
"text": "Find shortest safe route in a path with landmines"
},
{
"code": null,
"e": 29942,
"s": 29907,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 29986,
"s": 29942,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 30048,
"s": 29986,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
},
{
"code": null,
"e": 30084,
"s": 30048,
"text": "Print a given matrix in spiral form"
}
] |
strtoul() function in C/C++
|
30 Jun, 2021
The strtoul() function in C/C++ which converts the initial part of the string in str to an unsigned long int value according to the given base, which must be between 2 and 36 inclusive, or be the special value 0. This function discard any white space characters until the first non-whitespace character is found, then takes as many characters as possible to form a valid base-n unsigned integer number representation and converts them to an integer value.
Syntax:
unsigned long int strtoul(const char *str, char **end, int base)
Parameter: The function accepts three mandatory parameters which are described below:
str: Pointer to the null-terminated byte string to be interpreted
end : Pointer to a pointer to character (Reference to an object of type char*)
base : Base of the interpreted integer value
Return value: The function returns two value as below:
On success, it returns an integer value corresponding to the contents of str.
If no valid conversion is done, then 0 is returned.
Below programs illustrate the above function:
Program 1:
C++
// C++ program to illustrate the// strtoul() function#include <bits/stdc++.h>using namespace std; int main(){ // initializing the string char str[256] = "90600 Geeks For Geeks"; // reference pointer char* end; long result; // finding the unsigned long // integer with base 36 result = strtoul(str, &end, 36); // printing the unsigned number cout << "The unsigned long integer is : " << result << endl; cout << "String in str is : " << end; return 0;}
The unsigned long integer is : 15124320
String in str is : Geeks For Geeks
Program 2:
C++
// C++ program to illustrate the// strtoul() function with// different bases#include <bits/stdc++.h>using namespace std; int main(){ // initializing the string char str[256] = "12345 GFG"; // reference pointer char* end; long result; // finding the unsigned long integer // with base 36 result = strtoul(str, &end, 0); cout << "The unsigned long integer is : " << result << endl; cout << "String in str is : " << end << endl; // finding the unsigned long integer // with base 12 result = strtoul(str, &end, 12); cout << "The unsigned long integer is : " << result << endl; cout << "String in str is : " << end << endl; // finding the unsigned long integer // with base 30 result = strtoul(str, &end, 30); cout << "The unsigned long integer is : " << result << endl; cout << "String in str is : " << end << endl; return 0;}
The unsigned long integer is : 12345
String in str is : GFG
The unsigned long integer is : 24677
String in str is : GFG
The unsigned long integer is : 866825
String in str is : GFG
arorakashish0911
surindertarika1234
C-Library
CPP-Functions
CPP-Library
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Pair in C++ Standard Template Library (STL)
Friend class and function in C++
std::string class in C++
Queue in C++ Standard Template Library (STL)
std::find in C++
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
vector insert() function in C++ STL
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 484,
"s": 28,
"text": "The strtoul() function in C/C++ which converts the initial part of the string in str to an unsigned long int value according to the given base, which must be between 2 and 36 inclusive, or be the special value 0. This function discard any white space characters until the first non-whitespace character is found, then takes as many characters as possible to form a valid base-n unsigned integer number representation and converts them to an integer value."
},
{
"code": null,
"e": 494,
"s": 484,
"text": "Syntax: "
},
{
"code": null,
"e": 559,
"s": 494,
"text": "unsigned long int strtoul(const char *str, char **end, int base)"
},
{
"code": null,
"e": 647,
"s": 559,
"text": "Parameter: The function accepts three mandatory parameters which are described below: "
},
{
"code": null,
"e": 713,
"s": 647,
"text": "str: Pointer to the null-terminated byte string to be interpreted"
},
{
"code": null,
"e": 792,
"s": 713,
"text": "end : Pointer to a pointer to character (Reference to an object of type char*)"
},
{
"code": null,
"e": 837,
"s": 792,
"text": "base : Base of the interpreted integer value"
},
{
"code": null,
"e": 894,
"s": 837,
"text": "Return value: The function returns two value as below: "
},
{
"code": null,
"e": 972,
"s": 894,
"text": "On success, it returns an integer value corresponding to the contents of str."
},
{
"code": null,
"e": 1024,
"s": 972,
"text": "If no valid conversion is done, then 0 is returned."
},
{
"code": null,
"e": 1070,
"s": 1024,
"text": "Below programs illustrate the above function:"
},
{
"code": null,
"e": 1083,
"s": 1070,
"text": "Program 1: "
},
{
"code": null,
"e": 1087,
"s": 1083,
"text": "C++"
},
{
"code": "// C++ program to illustrate the// strtoul() function#include <bits/stdc++.h>using namespace std; int main(){ // initializing the string char str[256] = \"90600 Geeks For Geeks\"; // reference pointer char* end; long result; // finding the unsigned long // integer with base 36 result = strtoul(str, &end, 36); // printing the unsigned number cout << \"The unsigned long integer is : \" << result << endl; cout << \"String in str is : \" << end; return 0;}",
"e": 1587,
"s": 1087,
"text": null
},
{
"code": null,
"e": 1663,
"s": 1587,
"text": "The unsigned long integer is : 15124320\nString in str is : Geeks For Geeks"
},
{
"code": null,
"e": 1677,
"s": 1665,
"text": "Program 2: "
},
{
"code": null,
"e": 1681,
"s": 1677,
"text": "C++"
},
{
"code": "// C++ program to illustrate the// strtoul() function with// different bases#include <bits/stdc++.h>using namespace std; int main(){ // initializing the string char str[256] = \"12345 GFG\"; // reference pointer char* end; long result; // finding the unsigned long integer // with base 36 result = strtoul(str, &end, 0); cout << \"The unsigned long integer is : \" << result << endl; cout << \"String in str is : \" << end << endl; // finding the unsigned long integer // with base 12 result = strtoul(str, &end, 12); cout << \"The unsigned long integer is : \" << result << endl; cout << \"String in str is : \" << end << endl; // finding the unsigned long integer // with base 30 result = strtoul(str, &end, 30); cout << \"The unsigned long integer is : \" << result << endl; cout << \"String in str is : \" << end << endl; return 0;}",
"e": 2597,
"s": 1681,
"text": null
},
{
"code": null,
"e": 2781,
"s": 2597,
"text": "The unsigned long integer is : 12345\nString in str is : GFG\nThe unsigned long integer is : 24677\nString in str is : GFG\nThe unsigned long integer is : 866825\nString in str is : GFG"
},
{
"code": null,
"e": 2800,
"s": 2783,
"text": "arorakashish0911"
},
{
"code": null,
"e": 2819,
"s": 2800,
"text": "surindertarika1234"
},
{
"code": null,
"e": 2829,
"s": 2819,
"text": "C-Library"
},
{
"code": null,
"e": 2843,
"s": 2829,
"text": "CPP-Functions"
},
{
"code": null,
"e": 2855,
"s": 2843,
"text": "CPP-Library"
},
{
"code": null,
"e": 2859,
"s": 2855,
"text": "C++"
},
{
"code": null,
"e": 2863,
"s": 2859,
"text": "CPP"
},
{
"code": null,
"e": 2961,
"s": 2863,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2985,
"s": 2961,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 3005,
"s": 2985,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 3049,
"s": 3005,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3082,
"s": 3049,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 3107,
"s": 3082,
"text": "std::string class in C++"
},
{
"code": null,
"e": 3152,
"s": 3107,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3169,
"s": 3152,
"text": "std::find in C++"
},
{
"code": null,
"e": 3217,
"s": 3169,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 3261,
"s": 3217,
"text": "List in C++ Standard Template Library (STL)"
}
] |
std::string::rfind in C++ with Examples
|
26 May, 2022
The std::string::rfind is a string class member function that is used to search the last occurrence of any character in the string. If the character is present in the string then it returns the index of the last occurrence of that character in the string else it will return string::npos which denotes the pointer is at the end of the string. Header File:
#include < string >
Syntax 1:
rfind(char ch)
rfind(string str)
Parameters: This function takes a given character or a string as a parameter, whose index is to be found. Return value: This method returns the position of the last occurrence of that character or first index of the last occurrence of the string. Program 1: Below is the program to illustrate string::rfind(char ch):
CPP
// C++ program to demonstrate// rfind() method #include <cstddef>#include <iostream>#include <string>using namespace std; // Function to return last occurrence// of character in a stringvoid findLastOccurrence(string str, char ch){ // To store the index of the result size_t found; // Function to find the last // occurrence of character ch // in string str found = str.rfind(ch); // If string doesn't have // character ch present in it if (found == string::npos) { cout << "Character " << ch << " is not present in" << " the given string."; } // Else print the position else { cout << "The last occurrence of '" << ch << "' is found at index: " << found << endl; }} // Driver Codeint main(){ // Given String string str("Welcome to GeeksforGeeks!"); // Character to be found char ch = 'e'; findLastOccurrence(str, ch);}
Program 2: Below is the program to illustrate string::rfind(string str):
CPP
// C++ program to demonstrate// rfind() method #include <cstddef>#include <iostream>#include <string>using namespace std; // Function to return last occurrence// of string in a stringvoid findLastOccurrence(string str, string s){ // To store the index of the result size_t found; // Function to find the first index // of last occurrence of string s in str found = str.rfind(s); // If string doesn't have // string s present in it if (found == string::npos) { cout << "String '" << s << "' is not present in" << " the given string."; } // Else print the position else { cout << "The first index of last " << "occurrence of '" << s << "' is found at index: " << found << endl; }} // Driver Codeint main(){ // Given String string str("Welcome to GeeksforGeeks!"); // string to be found string s = "to"; findLastOccurrence(str, s);}
Syntax 2:
rfind(char ch, size_t position);
rfind(string s, size_t position);
Parameters: This function takes:
a given character or a string as a parameter, whose index is to be found.
a position till where the search is to be performed.
Return value: This method returns the position of the first character of the last match of that given character or string before that position else it returns string::npos Program 3: Below is the program to illustrate string::rfind(char ch, size_t position):
CPP
// C++ program to illustrate the function// string::rfind(char ch, size_t pos) #include <cstddef>#include <iostream>#include <string>using namespace std; // Function to return last occurrence// of character in a stringvoid findLastOccurrence( string str, char ch, size_t position){ // To store the index of the result size_t found; // Function to find the last occurrence // of character ch in str before pos 5 found = str.rfind(ch, position); // If string doesn't have // character ch present in it if (found == string::npos) { cout << "Character " << ch << " is not present in" << " the given string."; } // Else print the position else { cout << "The last occurrence of " << ch << " before position " << position << " is found at index: " << found << endl; }} // Driver Codeint main(){ // Given String string str("Welcome to GeeksforGeeks!"); // Character to be found char ch = 'e'; // Position till where // the search is to be done size_t position = 5; findLastOccurrence(str, ch, position);}
Program 4: Below is the program to illustrate string::rfind(string str, size_t position):
CPP
// C++ program to illustrate the function// string::rfind(string str, size_t pos)#include <cstddef>#include <iostream>#include <string>using namespace std; // Function to return last occurrence// of string in a stringvoid findLastOccurrence( string str, string s, size_t position){ // To store the index of result size_t found; // Function to find the last occurrence of // string s in str before given position found = str.rfind(s, position); // If string doesn't have // string s present in it // If string doesn't have // string s present in it if (found == string::npos) { cout << "String " << s << " is not present in" << " the given string."; } // Else print the position else { cout << "The last occurrence of " << s << " before position " << position << " is found at index: " << found << endl; }} // Driver Codeint main(){ // Given String string str("Welcome to GeeksforGeeks!"); // string to be found string s = "to"; // Position till where // the search is to be done size_t position = 5; findLastOccurrence(str, s, position);}
nikhatkhan11
C-Library
cpp-strings
C++
Searching
Strings
cpp-strings
Searching
Strings
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Pair in C++ Standard Template Library (STL)
Friend class and function in C++
std::string class in C++
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
K'th Smallest/Largest Element in Unsorted Array | Set 1
Search an element in a sorted and rotated array
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 May, 2022"
},
{
"code": null,
"e": 408,
"s": 52,
"text": "The std::string::rfind is a string class member function that is used to search the last occurrence of any character in the string. If the character is present in the string then it returns the index of the last occurrence of that character in the string else it will return string::npos which denotes the pointer is at the end of the string. Header File:"
},
{
"code": null,
"e": 428,
"s": 408,
"text": "#include < string >"
},
{
"code": null,
"e": 438,
"s": 428,
"text": "Syntax 1:"
},
{
"code": null,
"e": 471,
"s": 438,
"text": "rfind(char ch)\nrfind(string str)"
},
{
"code": null,
"e": 789,
"s": 471,
"text": "Parameters: This function takes a given character or a string as a parameter, whose index is to be found. Return value: This method returns the position of the last occurrence of that character or first index of the last occurrence of the string. Program 1: Below is the program to illustrate string::rfind(char ch): "
},
{
"code": null,
"e": 793,
"s": 789,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate// rfind() method #include <cstddef>#include <iostream>#include <string>using namespace std; // Function to return last occurrence// of character in a stringvoid findLastOccurrence(string str, char ch){ // To store the index of the result size_t found; // Function to find the last // occurrence of character ch // in string str found = str.rfind(ch); // If string doesn't have // character ch present in it if (found == string::npos) { cout << \"Character \" << ch << \" is not present in\" << \" the given string.\"; } // Else print the position else { cout << \"The last occurrence of '\" << ch << \"' is found at index: \" << found << endl; }} // Driver Codeint main(){ // Given String string str(\"Welcome to GeeksforGeeks!\"); // Character to be found char ch = 'e'; findLastOccurrence(str, ch);}",
"e": 1735,
"s": 793,
"text": null
},
{
"code": null,
"e": 1809,
"s": 1735,
"text": "Program 2: Below is the program to illustrate string::rfind(string str): "
},
{
"code": null,
"e": 1813,
"s": 1809,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate// rfind() method #include <cstddef>#include <iostream>#include <string>using namespace std; // Function to return last occurrence// of string in a stringvoid findLastOccurrence(string str, string s){ // To store the index of the result size_t found; // Function to find the first index // of last occurrence of string s in str found = str.rfind(s); // If string doesn't have // string s present in it if (found == string::npos) { cout << \"String '\" << s << \"' is not present in\" << \" the given string.\"; } // Else print the position else { cout << \"The first index of last \" << \"occurrence of '\" << s << \"' is found at index: \" << found << endl; }} // Driver Codeint main(){ // Given String string str(\"Welcome to GeeksforGeeks!\"); // string to be found string s = \"to\"; findLastOccurrence(str, s);}",
"e": 2774,
"s": 1813,
"text": null
},
{
"code": null,
"e": 2784,
"s": 2774,
"text": "Syntax 2:"
},
{
"code": null,
"e": 2852,
"s": 2784,
"text": "rfind(char ch, size_t position);\nrfind(string s, size_t position); "
},
{
"code": null,
"e": 2885,
"s": 2852,
"text": "Parameters: This function takes:"
},
{
"code": null,
"e": 2959,
"s": 2885,
"text": "a given character or a string as a parameter, whose index is to be found."
},
{
"code": null,
"e": 3012,
"s": 2959,
"text": "a position till where the search is to be performed."
},
{
"code": null,
"e": 3272,
"s": 3012,
"text": "Return value: This method returns the position of the first character of the last match of that given character or string before that position else it returns string::npos Program 3: Below is the program to illustrate string::rfind(char ch, size_t position): "
},
{
"code": null,
"e": 3276,
"s": 3272,
"text": "CPP"
},
{
"code": "// C++ program to illustrate the function// string::rfind(char ch, size_t pos) #include <cstddef>#include <iostream>#include <string>using namespace std; // Function to return last occurrence// of character in a stringvoid findLastOccurrence( string str, char ch, size_t position){ // To store the index of the result size_t found; // Function to find the last occurrence // of character ch in str before pos 5 found = str.rfind(ch, position); // If string doesn't have // character ch present in it if (found == string::npos) { cout << \"Character \" << ch << \" is not present in\" << \" the given string.\"; } // Else print the position else { cout << \"The last occurrence of \" << ch << \" before position \" << position << \" is found at index: \" << found << endl; }} // Driver Codeint main(){ // Given String string str(\"Welcome to GeeksforGeeks!\"); // Character to be found char ch = 'e'; // Position till where // the search is to be done size_t position = 5; findLastOccurrence(str, ch, position);}",
"e": 4430,
"s": 3276,
"text": null
},
{
"code": null,
"e": 4521,
"s": 4430,
"text": "Program 4: Below is the program to illustrate string::rfind(string str, size_t position): "
},
{
"code": null,
"e": 4525,
"s": 4521,
"text": "CPP"
},
{
"code": "// C++ program to illustrate the function// string::rfind(string str, size_t pos)#include <cstddef>#include <iostream>#include <string>using namespace std; // Function to return last occurrence// of string in a stringvoid findLastOccurrence( string str, string s, size_t position){ // To store the index of result size_t found; // Function to find the last occurrence of // string s in str before given position found = str.rfind(s, position); // If string doesn't have // string s present in it // If string doesn't have // string s present in it if (found == string::npos) { cout << \"String \" << s << \" is not present in\" << \" the given string.\"; } // Else print the position else { cout << \"The last occurrence of \" << s << \" before position \" << position << \" is found at index: \" << found << endl; }} // Driver Codeint main(){ // Given String string str(\"Welcome to GeeksforGeeks!\"); // string to be found string s = \"to\"; // Position till where // the search is to be done size_t position = 5; findLastOccurrence(str, s, position);}",
"e": 5728,
"s": 4525,
"text": null
},
{
"code": null,
"e": 5741,
"s": 5728,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 5751,
"s": 5741,
"text": "C-Library"
},
{
"code": null,
"e": 5763,
"s": 5751,
"text": "cpp-strings"
},
{
"code": null,
"e": 5767,
"s": 5763,
"text": "C++"
},
{
"code": null,
"e": 5777,
"s": 5767,
"text": "Searching"
},
{
"code": null,
"e": 5785,
"s": 5777,
"text": "Strings"
},
{
"code": null,
"e": 5797,
"s": 5785,
"text": "cpp-strings"
},
{
"code": null,
"e": 5807,
"s": 5797,
"text": "Searching"
},
{
"code": null,
"e": 5815,
"s": 5807,
"text": "Strings"
},
{
"code": null,
"e": 5819,
"s": 5815,
"text": "CPP"
},
{
"code": null,
"e": 5917,
"s": 5819,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5941,
"s": 5917,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 5961,
"s": 5941,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 6005,
"s": 5961,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 6038,
"s": 6005,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 6063,
"s": 6038,
"text": "std::string class in C++"
},
{
"code": null,
"e": 6077,
"s": 6063,
"text": "Binary Search"
},
{
"code": null,
"e": 6145,
"s": 6077,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 6159,
"s": 6145,
"text": "Linear Search"
},
{
"code": null,
"e": 6215,
"s": 6159,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
}
] |
Python Number round() Method
|
Python number method round() returns x rounded to n digits from the decimal point.
Following is the syntax for round() method −
round( x [, n] )
x − This is a numeric expression.
x − This is a numeric expression.
n − This is also a numeric expression.
n − This is also a numeric expression.
This method returns x rounded to n digits from the decimal point.
The following example shows the usage of round() method.
#!/usr/bin/python
print "round(80.23456, 2) : ", round(80.23456, 2)
print "round(100.000056, 3) : ", round(100.000056, 3)
print "round(-100.000056, 3) : ", round(-100.000056, 3)
When we run above program, it produces following result −
round(80.23456, 2) : 80.23
round(100.000056, 3) : 100.0
round(-100.000056, 3) : -100.0
|
[
{
"code": null,
"e": 2461,
"s": 2378,
"text": "Python number method round() returns x rounded to n digits from the decimal point."
},
{
"code": null,
"e": 2506,
"s": 2461,
"text": "Following is the syntax for round() method −"
},
{
"code": null,
"e": 2525,
"s": 2506,
"text": "round( x [, n] )\n"
},
{
"code": null,
"e": 2559,
"s": 2525,
"text": "x − This is a numeric expression."
},
{
"code": null,
"e": 2593,
"s": 2559,
"text": "x − This is a numeric expression."
},
{
"code": null,
"e": 2632,
"s": 2593,
"text": "n − This is also a numeric expression."
},
{
"code": null,
"e": 2671,
"s": 2632,
"text": "n − This is also a numeric expression."
},
{
"code": null,
"e": 2737,
"s": 2671,
"text": "This method returns x rounded to n digits from the decimal point."
},
{
"code": null,
"e": 2794,
"s": 2737,
"text": "The following example shows the usage of round() method."
},
{
"code": null,
"e": 2973,
"s": 2794,
"text": "#!/usr/bin/python\n\nprint \"round(80.23456, 2) : \", round(80.23456, 2)\nprint \"round(100.000056, 3) : \", round(100.000056, 3)\nprint \"round(-100.000056, 3) : \", round(-100.000056, 3)"
},
{
"code": null,
"e": 3031,
"s": 2973,
"text": "When we run above program, it produces following result −"
}
] |
Node.js http.ClientRequest.setTimeout() Method
|
06 May, 2021
The http.ClientRequest.setTimeout() is an inbuilt application programming interface of class ClientRequest within the HTTP module which is used to set the request time out for the client request.
Syntax:
request.setTimeout(timeout[, callback])
Parameters: This method takes the time out value as a parameter in milliseconds, and the second parameter is the callback function that executes after the given timeout value.
Return Value: This method returns nothing but a callback function for further operation.
Example 1: Filename-index.js
Javascript
// Node.js program to demonstrate the // request.setTimeout() method // Importing http moduleconst http = require('http'); // Create an HTTP serverconst server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('okay');}); // Now that server is runningserver.listen(3000, '127.0.0.1', () => { // Make a request const options = { port: 3000, host: '127.0.0.1', headers: { 'Connection': 'Upgrade', 'Upgrade': 'websocket' } }; // Getting client request const req = http.request(options); // Setting the timeout for the client request // by using host method req.setTimeout(3000, () => { console.log("timeout") process.exit(0) })});
Run the index.js file using the following command:
node index.js
Output:
timeout
Example 2: Filename-index.js
Javascript
// Node.js program to demonstrate the // request.setTimeout() method // Importing http moduleconst http = require('http'); // Create an HTTP serverhttp.createServer((req, res) => { }).listen(3000, '127.0.0.1', () => { // Getting client request const req = http.request({ port: 3000, host: '127.0.0.1', }); // Setting the timeout for the client request // by using host method req.setTimeout(5000, () => { console.log("timeout") process.exit(0) })});
Run the index.js file using the following command:
node index.js
Output:
timeout
Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_request_settimeout_timeout_callback
sweetyty
Node.js-Methods
Node.js
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 May, 2021"
},
{
"code": null,
"e": 224,
"s": 28,
"text": "The http.ClientRequest.setTimeout() is an inbuilt application programming interface of class ClientRequest within the HTTP module which is used to set the request time out for the client request."
},
{
"code": null,
"e": 232,
"s": 224,
"text": "Syntax:"
},
{
"code": null,
"e": 272,
"s": 232,
"text": "request.setTimeout(timeout[, callback])"
},
{
"code": null,
"e": 448,
"s": 272,
"text": "Parameters: This method takes the time out value as a parameter in milliseconds, and the second parameter is the callback function that executes after the given timeout value."
},
{
"code": null,
"e": 537,
"s": 448,
"text": "Return Value: This method returns nothing but a callback function for further operation."
},
{
"code": null,
"e": 566,
"s": 537,
"text": "Example 1: Filename-index.js"
},
{
"code": null,
"e": 577,
"s": 566,
"text": "Javascript"
},
{
"code": "// Node.js program to demonstrate the // request.setTimeout() method // Importing http moduleconst http = require('http'); // Create an HTTP serverconst server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('okay');}); // Now that server is runningserver.listen(3000, '127.0.0.1', () => { // Make a request const options = { port: 3000, host: '127.0.0.1', headers: { 'Connection': 'Upgrade', 'Upgrade': 'websocket' } }; // Getting client request const req = http.request(options); // Setting the timeout for the client request // by using host method req.setTimeout(3000, () => { console.log(\"timeout\") process.exit(0) })});",
"e": 1353,
"s": 577,
"text": null
},
{
"code": null,
"e": 1408,
"s": 1357,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 1424,
"s": 1410,
"text": "node index.js"
},
{
"code": null,
"e": 1432,
"s": 1424,
"text": "Output:"
},
{
"code": null,
"e": 1442,
"s": 1434,
"text": "timeout"
},
{
"code": null,
"e": 1471,
"s": 1442,
"text": "Example 2: Filename-index.js"
},
{
"code": null,
"e": 1484,
"s": 1473,
"text": "Javascript"
},
{
"code": "// Node.js program to demonstrate the // request.setTimeout() method // Importing http moduleconst http = require('http'); // Create an HTTP serverhttp.createServer((req, res) => { }).listen(3000, '127.0.0.1', () => { // Getting client request const req = http.request({ port: 3000, host: '127.0.0.1', }); // Setting the timeout for the client request // by using host method req.setTimeout(5000, () => { console.log(\"timeout\") process.exit(0) })});",
"e": 1985,
"s": 1484,
"text": null
},
{
"code": null,
"e": 2036,
"s": 1985,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 2050,
"s": 2036,
"text": "node index.js"
},
{
"code": null,
"e": 2058,
"s": 2050,
"text": "Output:"
},
{
"code": null,
"e": 2066,
"s": 2058,
"text": "timeout"
},
{
"code": null,
"e": 2174,
"s": 2066,
"text": "Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_request_settimeout_timeout_callback"
},
{
"code": null,
"e": 2183,
"s": 2174,
"text": "sweetyty"
},
{
"code": null,
"e": 2199,
"s": 2183,
"text": "Node.js-Methods"
},
{
"code": null,
"e": 2207,
"s": 2199,
"text": "Node.js"
}
] |
re.MatchObject.groupdict() function in Python – Regex
|
29 Aug, 2020
This method returns a dictionary with the groupname as keys and the matched string as the value for that key.
Syntax: re.MatchObject.groupdict()
Return: A dictionary with groupnames as the keys and matched string as the value for the key.
AttributeError: If a matching pattern is not found then it raise AttributeError.
Consider the below example:
Example 1:
A program to create and print a detailed dictionary which will consist of username, website, and the domain.
Python3
import re """We create a re.MatchObject and store it in match_object variable the '()' parenthesis are used to define a specific group""" match_object = re.match( r'(?P<Username>\w+)@(?P<Website>\w+)\.(?P<Domain>\w+)', 'jon@geekforgeeks.org') """ w in above pattern stands for alphabetical character + is used to match a consecutive set of characters satisfying a given condition so w+ will match a consecutive set of alphabetical characters The ?P<Username> in '()'(the round brackets) is used to capture subgroups of strings satisfying the above condition and the groupname is specified in the ''(angle brackets)in this case its Username.""" # generating a dictionary from the given emailIDdetails = match_object.groupdict() # printing the dictionaryprint(details)
Output:
{‘Username’: ‘jon’, ‘Website’: ‘geekforgeeks’, ‘Domain’: ‘org’}
It’s time to understand the above program. We use a re.match() method to find a match in the given string(‘jon@geekforgeeks.org‘) the ‘w‘ indicates that we are searching for an alphabetical character and the ‘+‘ indicates that we are searching for continuous alphabetical characters in the given string. Note the use of ‘()‘ the parenthesis is used to define different subgroups, in the above example, we have three subgroups in the match pattern. The ‘?P‘ syntax is used to define the groupname for capturing the specific groups. The result we get is a re.MatchObject which is stored in match_object.
To know more about regex patterns visit this post. Python regex
Example 2: If a match object is not found then it raises AttributeError.
Python3
import re """We create a re.MatchObject and store it in match_object variable the '()' parenthesis are used to define a specific group""" match_object = re.match( r'(?P<Username>\w+)@(?P<Website>\w+)\.(?P<Domain>\w+)', '1234567890') """ w in above pattern stands for alphabetical character + is used to match a consecutive set of characters satisfying a given condition so w+ will match a consecutive set of alphabetical characters The ?P<Username> in '()'(the round brackets) is used to capture subgroups of strings satisfying the above condition and the groupname is specified in the ''(angle brackets)in this case its Username.""" # Following line will raise AttributeError exceptionprint(match_object.groupdict())
Output:
Traceback (most recent call last):
File "/home/fae2ec2e63d04a63d590c2e93802a002.py", line 21, in
print(match_object.groupdict())
AttributeError: 'NoneType' object has no attribute 'groupdict'
python-regex
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 138,
"s": 28,
"text": "This method returns a dictionary with the groupname as keys and the matched string as the value for that key."
},
{
"code": null,
"e": 173,
"s": 138,
"text": "Syntax: re.MatchObject.groupdict()"
},
{
"code": null,
"e": 267,
"s": 173,
"text": "Return: A dictionary with groupnames as the keys and matched string as the value for the key."
},
{
"code": null,
"e": 348,
"s": 267,
"text": "AttributeError: If a matching pattern is not found then it raise AttributeError."
},
{
"code": null,
"e": 376,
"s": 348,
"text": "Consider the below example:"
},
{
"code": null,
"e": 387,
"s": 376,
"text": "Example 1:"
},
{
"code": null,
"e": 496,
"s": 387,
"text": "A program to create and print a detailed dictionary which will consist of username, website, and the domain."
},
{
"code": null,
"e": 504,
"s": 496,
"text": "Python3"
},
{
"code": "import re \"\"\"We create a re.MatchObject and store it in match_object variable the '()' parenthesis are used to define a specific group\"\"\" match_object = re.match( r'(?P<Username>\\w+)@(?P<Website>\\w+)\\.(?P<Domain>\\w+)', 'jon@geekforgeeks.org') \"\"\" w in above pattern stands for alphabetical character + is used to match a consecutive set of characters satisfying a given condition so w+ will match a consecutive set of alphabetical characters The ?P<Username> in '()'(the round brackets) is used to capture subgroups of strings satisfying the above condition and the groupname is specified in the ''(angle brackets)in this case its Username.\"\"\" # generating a dictionary from the given emailIDdetails = match_object.groupdict() # printing the dictionaryprint(details)",
"e": 1316,
"s": 504,
"text": null
},
{
"code": null,
"e": 1324,
"s": 1316,
"text": "Output:"
},
{
"code": null,
"e": 1388,
"s": 1324,
"text": "{‘Username’: ‘jon’, ‘Website’: ‘geekforgeeks’, ‘Domain’: ‘org’}"
},
{
"code": null,
"e": 1990,
"s": 1388,
"text": "It’s time to understand the above program. We use a re.match() method to find a match in the given string(‘jon@geekforgeeks.org‘) the ‘w‘ indicates that we are searching for an alphabetical character and the ‘+‘ indicates that we are searching for continuous alphabetical characters in the given string. Note the use of ‘()‘ the parenthesis is used to define different subgroups, in the above example, we have three subgroups in the match pattern. The ‘?P‘ syntax is used to define the groupname for capturing the specific groups. The result we get is a re.MatchObject which is stored in match_object."
},
{
"code": null,
"e": 2054,
"s": 1990,
"text": "To know more about regex patterns visit this post. Python regex"
},
{
"code": null,
"e": 2127,
"s": 2054,
"text": "Example 2: If a match object is not found then it raises AttributeError."
},
{
"code": null,
"e": 2135,
"s": 2127,
"text": "Python3"
},
{
"code": "import re \"\"\"We create a re.MatchObject and store it in match_object variable the '()' parenthesis are used to define a specific group\"\"\" match_object = re.match( r'(?P<Username>\\w+)@(?P<Website>\\w+)\\.(?P<Domain>\\w+)', '1234567890') \"\"\" w in above pattern stands for alphabetical character + is used to match a consecutive set of characters satisfying a given condition so w+ will match a consecutive set of alphabetical characters The ?P<Username> in '()'(the round brackets) is used to capture subgroups of strings satisfying the above condition and the groupname is specified in the ''(angle brackets)in this case its Username.\"\"\" # Following line will raise AttributeError exceptionprint(match_object.groupdict())",
"e": 2897,
"s": 2135,
"text": null
},
{
"code": null,
"e": 2905,
"s": 2897,
"text": "Output:"
},
{
"code": null,
"e": 3105,
"s": 2905,
"text": "Traceback (most recent call last):\n File \"/home/fae2ec2e63d04a63d590c2e93802a002.py\", line 21, in \n print(match_object.groupdict())\nAttributeError: 'NoneType' object has no attribute 'groupdict'\n"
},
{
"code": null,
"e": 3118,
"s": 3105,
"text": "python-regex"
},
{
"code": null,
"e": 3125,
"s": 3118,
"text": "Python"
}
] |
Swiggy Interview Experience for SDE-II
|
07 Jul, 2021
I applied on LinkedIn for Swiggy SDE-II (R&G). Got the first round link – Hackerrank after 9-10 days.
Round 1(Online Coding): HackerRank
3 Questions were asked in this round and time limit was 75 minutes. All the 3 questions were hard.
Flexible StringsGiven a string abccc, Given are below operationsb can be replaced by ca can be replaced by bCan the given string converted to all of the same charcters? The string abccc can be converted to ccccc by following operations:Convert b at index 1 to cConvert a at index 0 to bConvert b at index 0 to cThe given operations can be performed infinite number of times on the string. We need to find whether the string can be converted to a string containing all same characters. Note : the operations can be performed in any order and any number of times.Example 1:
Input : String - abccc
Operations -
b --> c
a --> b
Output - YES
Example 2: String - abcdc
Operations:
b --> c
a --> d
Output - NOProgramming ContestA programming organization is planning a contest for several programmers, each of which has a certain rating. (The higher the rating, the better the programmer.) Each programmer is paired with another programmer, and the difference between their ratings is referred to as the “bias amount”. Given the ratings of all the programmers in the contest, what is the minimum total bias amount that can be achieved by optimally planning the programmer pairs? [ Some modification in this problem]Maximum Swiggy Genie This sum is a variation of Maximum Profit in Job SchedulingGiven 3 arrays called as pickup, drop and tip. find the max profit the delivery guy can earn. The guy can only process one delivery at a time.E.g he gets profit of 5 - 0 + 1 = 6
6 units if delivers the 1st order
pickup: [0,2,9,10,11,12]
drop:[5,9,11,11,14,17]
tip:[1,2,3,2,2,1]
Flexible StringsGiven a string abccc, Given are below operationsb can be replaced by ca can be replaced by bCan the given string converted to all of the same charcters? The string abccc can be converted to ccccc by following operations:Convert b at index 1 to cConvert a at index 0 to bConvert b at index 0 to cThe given operations can be performed infinite number of times on the string. We need to find whether the string can be converted to a string containing all same characters. Note : the operations can be performed in any order and any number of times.Example 1:
Input : String - abccc
Operations -
b --> c
a --> b
Output - YES
Example 2: String - abcdc
Operations:
b --> c
a --> d
Output - NO
Given a string abccc, Given are below operations
b can be replaced by c
a can be replaced by b
Can the given string converted to all of the same charcters? The string abccc can be converted to ccccc by following operations:
Convert b at index 1 to c
Convert a at index 0 to b
Convert b at index 0 to c
The given operations can be performed infinite number of times on the string. We need to find whether the string can be converted to a string containing all same characters. Note : the operations can be performed in any order and any number of times.
Example 1:
Input : String - abccc
Operations -
b --> c
a --> b
Output - YES
Example 2: String - abcdc
Operations:
b --> c
a --> d
Output - NO
Programming ContestA programming organization is planning a contest for several programmers, each of which has a certain rating. (The higher the rating, the better the programmer.) Each programmer is paired with another programmer, and the difference between their ratings is referred to as the “bias amount”. Given the ratings of all the programmers in the contest, what is the minimum total bias amount that can be achieved by optimally planning the programmer pairs? [ Some modification in this problem]
A programming organization is planning a contest for several programmers, each of which has a certain rating. (The higher the rating, the better the programmer.) Each programmer is paired with another programmer, and the difference between their ratings is referred to as the “bias amount”. Given the ratings of all the programmers in the contest, what is the minimum total bias amount that can be achieved by optimally planning the programmer pairs? [ Some modification in this problem]
Maximum Swiggy Genie This sum is a variation of Maximum Profit in Job SchedulingGiven 3 arrays called as pickup, drop and tip. find the max profit the delivery guy can earn. The guy can only process one delivery at a time.E.g he gets profit of 5 - 0 + 1 = 6
6 units if delivers the 1st order
pickup: [0,2,9,10,11,12]
drop:[5,9,11,11,14,17]
tip:[1,2,3,2,2,1]
This sum is a variation of Maximum Profit in Job Scheduling
Given 3 arrays called as pickup, drop and tip. find the max profit the delivery guy can earn. The guy can only process one delivery at a time.
E.g he gets profit of 5 - 0 + 1 = 6
6 units if delivers the 1st order
pickup: [0,2,9,10,11,12]
drop:[5,9,11,11,14,17]
tip:[1,2,3,2,2,1]
Verdict :Rejected
Marketing
Swiggy
Interview Experiences
Swiggy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Jul, 2021"
},
{
"code": null,
"e": 156,
"s": 54,
"text": "I applied on LinkedIn for Swiggy SDE-II (R&G). Got the first round link – Hackerrank after 9-10 days."
},
{
"code": null,
"e": 191,
"s": 156,
"text": "Round 1(Online Coding): HackerRank"
},
{
"code": null,
"e": 290,
"s": 191,
"text": "3 Questions were asked in this round and time limit was 75 minutes. All the 3 questions were hard."
},
{
"code": null,
"e": 1856,
"s": 290,
"text": "Flexible StringsGiven a string abccc, Given are below operationsb can be replaced by ca can be replaced by bCan the given string converted to all of the same charcters? The string abccc can be converted to ccccc by following operations:Convert b at index 1 to cConvert a at index 0 to bConvert b at index 0 to cThe given operations can be performed infinite number of times on the string. We need to find whether the string can be converted to a string containing all same characters. Note : the operations can be performed in any order and any number of times.Example 1:\nInput : String - abccc\nOperations -\nb --> c\na --> b\nOutput - YES\nExample 2: String - abcdc\nOperations:\nb --> c\na --> d\nOutput - NOProgramming ContestA programming organization is planning a contest for several programmers, each of which has a certain rating. (The higher the rating, the better the programmer.) Each programmer is paired with another programmer, and the difference between their ratings is referred to as the “bias amount”. Given the ratings of all the programmers in the contest, what is the minimum total bias amount that can be achieved by optimally planning the programmer pairs? [ Some modification in this problem]Maximum Swiggy Genie This sum is a variation of Maximum Profit in Job SchedulingGiven 3 arrays called as pickup, drop and tip. find the max profit the delivery guy can earn. The guy can only process one delivery at a time.E.g he gets profit of 5 - 0 + 1 = 6\n6 units if delivers the 1st order\npickup: [0,2,9,10,11,12]\ndrop:[5,9,11,11,14,17]\ntip:[1,2,3,2,2,1]"
},
{
"code": null,
"e": 2559,
"s": 1856,
"text": "Flexible StringsGiven a string abccc, Given are below operationsb can be replaced by ca can be replaced by bCan the given string converted to all of the same charcters? The string abccc can be converted to ccccc by following operations:Convert b at index 1 to cConvert a at index 0 to bConvert b at index 0 to cThe given operations can be performed infinite number of times on the string. We need to find whether the string can be converted to a string containing all same characters. Note : the operations can be performed in any order and any number of times.Example 1:\nInput : String - abccc\nOperations -\nb --> c\na --> b\nOutput - YES\nExample 2: String - abcdc\nOperations:\nb --> c\na --> d\nOutput - NO"
},
{
"code": null,
"e": 2608,
"s": 2559,
"text": "Given a string abccc, Given are below operations"
},
{
"code": null,
"e": 2631,
"s": 2608,
"text": "b can be replaced by c"
},
{
"code": null,
"e": 2654,
"s": 2631,
"text": "a can be replaced by b"
},
{
"code": null,
"e": 2783,
"s": 2654,
"text": "Can the given string converted to all of the same charcters? The string abccc can be converted to ccccc by following operations:"
},
{
"code": null,
"e": 2809,
"s": 2783,
"text": "Convert b at index 1 to c"
},
{
"code": null,
"e": 2835,
"s": 2809,
"text": "Convert a at index 0 to b"
},
{
"code": null,
"e": 2861,
"s": 2835,
"text": "Convert b at index 0 to c"
},
{
"code": null,
"e": 3112,
"s": 2861,
"text": "The given operations can be performed infinite number of times on the string. We need to find whether the string can be converted to a string containing all same characters. Note : the operations can be performed in any order and any number of times."
},
{
"code": null,
"e": 3254,
"s": 3112,
"text": "Example 1:\nInput : String - abccc\nOperations -\nb --> c\na --> b\nOutput - YES\nExample 2: String - abcdc\nOperations:\nb --> c\na --> d\nOutput - NO"
},
{
"code": null,
"e": 3761,
"s": 3254,
"text": "Programming ContestA programming organization is planning a contest for several programmers, each of which has a certain rating. (The higher the rating, the better the programmer.) Each programmer is paired with another programmer, and the difference between their ratings is referred to as the “bias amount”. Given the ratings of all the programmers in the contest, what is the minimum total bias amount that can be achieved by optimally planning the programmer pairs? [ Some modification in this problem]"
},
{
"code": null,
"e": 4249,
"s": 3761,
"text": "A programming organization is planning a contest for several programmers, each of which has a certain rating. (The higher the rating, the better the programmer.) Each programmer is paired with another programmer, and the difference between their ratings is referred to as the “bias amount”. Given the ratings of all the programmers in the contest, what is the minimum total bias amount that can be achieved by optimally planning the programmer pairs? [ Some modification in this problem]"
},
{
"code": null,
"e": 4607,
"s": 4249,
"text": "Maximum Swiggy Genie This sum is a variation of Maximum Profit in Job SchedulingGiven 3 arrays called as pickup, drop and tip. find the max profit the delivery guy can earn. The guy can only process one delivery at a time.E.g he gets profit of 5 - 0 + 1 = 6\n6 units if delivers the 1st order\npickup: [0,2,9,10,11,12]\ndrop:[5,9,11,11,14,17]\ntip:[1,2,3,2,2,1]"
},
{
"code": null,
"e": 4667,
"s": 4607,
"text": "This sum is a variation of Maximum Profit in Job Scheduling"
},
{
"code": null,
"e": 4810,
"s": 4667,
"text": "Given 3 arrays called as pickup, drop and tip. find the max profit the delivery guy can earn. The guy can only process one delivery at a time."
},
{
"code": null,
"e": 4946,
"s": 4810,
"text": "E.g he gets profit of 5 - 0 + 1 = 6\n6 units if delivers the 1st order\npickup: [0,2,9,10,11,12]\ndrop:[5,9,11,11,14,17]\ntip:[1,2,3,2,2,1]"
},
{
"code": null,
"e": 4964,
"s": 4946,
"text": "Verdict :Rejected"
},
{
"code": null,
"e": 4974,
"s": 4964,
"text": "Marketing"
},
{
"code": null,
"e": 4981,
"s": 4974,
"text": "Swiggy"
},
{
"code": null,
"e": 5003,
"s": 4981,
"text": "Interview Experiences"
},
{
"code": null,
"e": 5010,
"s": 5003,
"text": "Swiggy"
}
] |
C# | Get or set the number of elements that the ArrayList can contain
|
01 Feb, 2019
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Capacity property is used to get or set the number of elements that the ArrayList can contain.
Properties of ArrayList Class:
Elements can be added or removed from the Array List collection at any point in time.
The ArrayList is not guaranteed to be sorted.
The capacity of an ArrayList is the number of elements the ArrayList can hold.
Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.
It also allows duplicate elements.
Using multidimensional arrays as elements in an ArrayList collection is not supported.
Syntax:
public virtual int Capacity { get; set; }
Return Value: The number of elements that the ArrayList can contain.
Exceptions:
ArgumentOutOfRangeException : If the Capacity is set to a value that is less than Count i.e, number of elements in the ArrayList.
OutOfMemoryException : If there is not enough memory available on the system.
Example:
// C# code to get or set the number // of elements that the ArrayList can containusing System; using System.Collections; class GFG { // Driver codepublic static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(); // Adding elements to ArrayList myList.Add(1); myList.Add(2); myList.Add(3); myList.Add(4); myList.Add(5); // Displaying count of elements of ArrayList Console.WriteLine("Number of elements: " + myList.Count); // Displaying Current capacity of ArrayList Console.WriteLine("Current capacity: " + myList.Capacity); } }
Number of elements: 5
Current capacity: 8
Important Points:
Capacity is the number of elements that the ArrayList can store. The Count is the number of elements that are actually in the ArrayList.
Capacity is always greater than or equal to Count. If Count exceeds Capacity while adding elements, the capacity is automatically increased by reallocating the internal array before copying the old elements and adding the new elements.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.capacity?view=netframework-4.7.2
CSharp-Collections-ArrayList
CSharp-Collections-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
HashSet in C# with Examples
C# | .NET Framework (Basic Architecture and Component Stack)
Switch Statement in C#
Partial Classes in C#
Lambda Expressions in C#
Hello World in C#
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 358,
"s": 28,
"text": "ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Capacity property is used to get or set the number of elements that the ArrayList can contain."
},
{
"code": null,
"e": 389,
"s": 358,
"text": "Properties of ArrayList Class:"
},
{
"code": null,
"e": 475,
"s": 389,
"text": "Elements can be added or removed from the Array List collection at any point in time."
},
{
"code": null,
"e": 521,
"s": 475,
"text": "The ArrayList is not guaranteed to be sorted."
},
{
"code": null,
"e": 600,
"s": 521,
"text": "The capacity of an ArrayList is the number of elements the ArrayList can hold."
},
{
"code": null,
"e": 711,
"s": 600,
"text": "Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based."
},
{
"code": null,
"e": 746,
"s": 711,
"text": "It also allows duplicate elements."
},
{
"code": null,
"e": 833,
"s": 746,
"text": "Using multidimensional arrays as elements in an ArrayList collection is not supported."
},
{
"code": null,
"e": 841,
"s": 833,
"text": "Syntax:"
},
{
"code": null,
"e": 884,
"s": 841,
"text": "public virtual int Capacity { get; set; }\n"
},
{
"code": null,
"e": 953,
"s": 884,
"text": "Return Value: The number of elements that the ArrayList can contain."
},
{
"code": null,
"e": 965,
"s": 953,
"text": "Exceptions:"
},
{
"code": null,
"e": 1095,
"s": 965,
"text": "ArgumentOutOfRangeException : If the Capacity is set to a value that is less than Count i.e, number of elements in the ArrayList."
},
{
"code": null,
"e": 1173,
"s": 1095,
"text": "OutOfMemoryException : If there is not enough memory available on the system."
},
{
"code": null,
"e": 1182,
"s": 1173,
"text": "Example:"
},
{
"code": "// C# code to get or set the number // of elements that the ArrayList can containusing System; using System.Collections; class GFG { // Driver codepublic static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(); // Adding elements to ArrayList myList.Add(1); myList.Add(2); myList.Add(3); myList.Add(4); myList.Add(5); // Displaying count of elements of ArrayList Console.WriteLine(\"Number of elements: \" + myList.Count); // Displaying Current capacity of ArrayList Console.WriteLine(\"Current capacity: \" + myList.Capacity); } }",
"e": 1803,
"s": 1182,
"text": null
},
{
"code": null,
"e": 1846,
"s": 1803,
"text": "Number of elements: 5\nCurrent capacity: 8\n"
},
{
"code": null,
"e": 1864,
"s": 1846,
"text": "Important Points:"
},
{
"code": null,
"e": 2001,
"s": 1864,
"text": "Capacity is the number of elements that the ArrayList can store. The Count is the number of elements that are actually in the ArrayList."
},
{
"code": null,
"e": 2237,
"s": 2001,
"text": "Capacity is always greater than or equal to Count. If Count exceeds Capacity while adding elements, the capacity is automatically increased by reallocating the internal array before copying the old elements and adding the new elements."
},
{
"code": null,
"e": 2248,
"s": 2237,
"text": "Reference:"
},
{
"code": null,
"e": 2354,
"s": 2248,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.capacity?view=netframework-4.7.2"
},
{
"code": null,
"e": 2383,
"s": 2354,
"text": "CSharp-Collections-ArrayList"
},
{
"code": null,
"e": 2412,
"s": 2383,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 2415,
"s": 2412,
"text": "C#"
},
{
"code": null,
"e": 2513,
"s": 2415,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2556,
"s": 2513,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 2605,
"s": 2556,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 2628,
"s": 2605,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 2644,
"s": 2628,
"text": "C# | List Class"
},
{
"code": null,
"e": 2672,
"s": 2644,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 2733,
"s": 2672,
"text": "C# | .NET Framework (Basic Architecture and Component Stack)"
},
{
"code": null,
"e": 2756,
"s": 2733,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 2778,
"s": 2756,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 2803,
"s": 2778,
"text": "Lambda Expressions in C#"
}
] |
How to convert CSV File to PDF File using Python?
|
16 Mar, 2021
In this article, we will learn how to do Conversion of CSV to PDF file format. This simple task can be easily done using two Steps :
Firstly, We convert our CSV file to HTML using the PandasIn the Second Step, we use PDFkit Python API to convert our HTML file to the PDF file format.
Firstly, We convert our CSV file to HTML using the Pandas
In the Second Step, we use PDFkit Python API to convert our HTML file to the PDF file format.
Approach:
1. Converting CSV file to HTML using Pandas Framework.
Pandas is a fast, powerful, flexible, and easy-to-use open-source data analysis and manipulation tool, built on top of the Python programming language.
CSV File Used:
For this section of tutorial we will be using :
pandas.read_csv(): read_csv is an important pandas function to read CSV files and do operations on it.We will be using it to read our input CSV file..to_html(): With help of DataFrame.to_html() method, we can get the html format of a dataframe by using DataFrame.to_html() method.This function takes in a CSV file as input, converts it, and saves it locally in HTML file format.
pandas.read_csv(): read_csv is an important pandas function to read CSV files and do operations on it.We will be using it to read our input CSV file.
.to_html(): With help of DataFrame.to_html() method, we can get the html format of a dataframe by using DataFrame.to_html() method.This function takes in a CSV file as input, converts it, and saves it locally in HTML file format.
Syntax for converting CSV to HTML using Pandas :
import pandas as pd
CSV = pd.read_csv(“MyCSV.csv”)
CSV.to_html(“MyCSV.html”)
HTML File Used: MyCSV
2. Converting HTML file to CSV using PDFKit Python API
There are many approaches for generating PDF in python. pdfkit is one of the better approaches as, it renders HTML into PDF with various image formats, HTML forms, and other complex printable documents.
We can create a PDF document with pdfkit in 3 ways. They are :
from URL
from a HTML file
from the string.
2.1. Generate PDF from URL: The following script gives us the pdf file from a website URL.
import pdfkit
pdfkit.from_url('https://www.geeksforgeeks.org', 'Output.pdf')
2.2. Generate PDF from file: The following script gives us the pdf file from an HTML file.
import pdfkit
pdfkit.from_file('LocalHTMLFile.html', 'Output.pdf')
2.3. Generate PDF from the string: The following script gives us the pdf file from a string.
import pdfkit
pdfkit.from_string('Geeks For Geeks', 'Output.pdf')
Since we have already converted our CSV file to HTML we will be using the first method i.e. Generating PDF from URL wherein either we can give any website’s address or any local HTML file.
If one already have wkhtmltopdf installed on machine we may use this syntax directly :
Syntax for converting HTML to PDF using PDFKit :
import pdfkit
pdfkit.from_url(“MyCSV.html”, “FinalOutput.pdf”)
Else, we also need to install wkhtmltopdf for the script to run on our PC and set the installed file wkhtmltopdf.exe ‘s path to our PC’s Environment Variables and we can now skip the configuration section in the script.
or
We can alternatively set Configuration as shown for the installed wkhtmltopdf.exe file and pass on the config variable to pdfkit.from_url function :
Path Configuration
path_wkhtmltopdf = r’D:\Softwares\wkhtmltopdf\bin\wkhtmltopdf.exe’
config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)
Convert HTML file to PDF with pdfkit
pdfkit.from_url(“MyCSV.html”, “FinalOutput.pdf”, configuration=config)
Implementation:
Initial files in the folder
INITIAL FILES IN FOLDER
Python
import pandas as pdimport pdfkit # SAVE CSV TO HTML USING PANDAScsv = 'MyCSV.csv'html_file = csv_file[:-3]+'html' df = pd.read_csv(csv_file, sep=',')df.to_html(html_file) # INSTALL wkhtmltopdf AND SET PATH IN CONFIGURATION# These two Steps could be eliminated By Installing wkhtmltopdf -# - and setting it's path to Environment Variablespath_wkhtmltopdf = r'D:\Softwares\wkhtmltopdf\bin\wkhtmltopdf.exe'config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf) # CONVERT HTML FILE TO PDF WITH PDFKITpdfkit.from_url("MyCSV.html", "FinalOutput.pdf", configuration=config)
After Running Above Python Script :
FILES IN the SAME DIRECTORY AFTER RUNNING PYTHON SCRIPT
Final Output :
Picked
python-csv
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
Check if element exists in list in Python
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Defaultdict in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Mar, 2021"
},
{
"code": null,
"e": 161,
"s": 28,
"text": "In this article, we will learn how to do Conversion of CSV to PDF file format. This simple task can be easily done using two Steps :"
},
{
"code": null,
"e": 312,
"s": 161,
"text": "Firstly, We convert our CSV file to HTML using the PandasIn the Second Step, we use PDFkit Python API to convert our HTML file to the PDF file format."
},
{
"code": null,
"e": 370,
"s": 312,
"text": "Firstly, We convert our CSV file to HTML using the Pandas"
},
{
"code": null,
"e": 464,
"s": 370,
"text": "In the Second Step, we use PDFkit Python API to convert our HTML file to the PDF file format."
},
{
"code": null,
"e": 474,
"s": 464,
"text": "Approach:"
},
{
"code": null,
"e": 529,
"s": 474,
"text": "1. Converting CSV file to HTML using Pandas Framework."
},
{
"code": null,
"e": 681,
"s": 529,
"text": "Pandas is a fast, powerful, flexible, and easy-to-use open-source data analysis and manipulation tool, built on top of the Python programming language."
},
{
"code": null,
"e": 696,
"s": 681,
"text": "CSV File Used:"
},
{
"code": null,
"e": 744,
"s": 696,
"text": "For this section of tutorial we will be using :"
},
{
"code": null,
"e": 1123,
"s": 744,
"text": "pandas.read_csv(): read_csv is an important pandas function to read CSV files and do operations on it.We will be using it to read our input CSV file..to_html(): With help of DataFrame.to_html() method, we can get the html format of a dataframe by using DataFrame.to_html() method.This function takes in a CSV file as input, converts it, and saves it locally in HTML file format."
},
{
"code": null,
"e": 1273,
"s": 1123,
"text": "pandas.read_csv(): read_csv is an important pandas function to read CSV files and do operations on it.We will be using it to read our input CSV file."
},
{
"code": null,
"e": 1503,
"s": 1273,
"text": ".to_html(): With help of DataFrame.to_html() method, we can get the html format of a dataframe by using DataFrame.to_html() method.This function takes in a CSV file as input, converts it, and saves it locally in HTML file format."
},
{
"code": null,
"e": 1552,
"s": 1503,
"text": "Syntax for converting CSV to HTML using Pandas :"
},
{
"code": null,
"e": 1573,
"s": 1552,
"text": "import pandas as pd "
},
{
"code": null,
"e": 1606,
"s": 1573,
"text": "CSV = pd.read_csv(“MyCSV.csv”) "
},
{
"code": null,
"e": 1634,
"s": 1606,
"text": "CSV.to_html(“MyCSV.html”) "
},
{
"code": null,
"e": 1656,
"s": 1634,
"text": "HTML File Used: MyCSV"
},
{
"code": null,
"e": 1711,
"s": 1656,
"text": "2. Converting HTML file to CSV using PDFKit Python API"
},
{
"code": null,
"e": 1914,
"s": 1711,
"text": "There are many approaches for generating PDF in python. pdfkit is one of the better approaches as, it renders HTML into PDF with various image formats, HTML forms, and other complex printable documents."
},
{
"code": null,
"e": 1977,
"s": 1914,
"text": "We can create a PDF document with pdfkit in 3 ways. They are :"
},
{
"code": null,
"e": 1986,
"s": 1977,
"text": "from URL"
},
{
"code": null,
"e": 2003,
"s": 1986,
"text": "from a HTML file"
},
{
"code": null,
"e": 2020,
"s": 2003,
"text": "from the string."
},
{
"code": null,
"e": 2111,
"s": 2020,
"text": "2.1. Generate PDF from URL: The following script gives us the pdf file from a website URL."
},
{
"code": null,
"e": 2188,
"s": 2111,
"text": "import pdfkit\npdfkit.from_url('https://www.geeksforgeeks.org', 'Output.pdf')"
},
{
"code": null,
"e": 2279,
"s": 2188,
"text": "2.2. Generate PDF from file: The following script gives us the pdf file from an HTML file."
},
{
"code": null,
"e": 2346,
"s": 2279,
"text": "import pdfkit\npdfkit.from_file('LocalHTMLFile.html', 'Output.pdf')"
},
{
"code": null,
"e": 2439,
"s": 2346,
"text": "2.3. Generate PDF from the string: The following script gives us the pdf file from a string."
},
{
"code": null,
"e": 2505,
"s": 2439,
"text": "import pdfkit\npdfkit.from_string('Geeks For Geeks', 'Output.pdf')"
},
{
"code": null,
"e": 2694,
"s": 2505,
"text": "Since we have already converted our CSV file to HTML we will be using the first method i.e. Generating PDF from URL wherein either we can give any website’s address or any local HTML file."
},
{
"code": null,
"e": 2782,
"s": 2694,
"text": "If one already have wkhtmltopdf installed on machine we may use this syntax directly : "
},
{
"code": null,
"e": 2832,
"s": 2782,
"text": "Syntax for converting HTML to PDF using PDFKit :"
},
{
"code": null,
"e": 2847,
"s": 2832,
"text": "import pdfkit "
},
{
"code": null,
"e": 2896,
"s": 2847,
"text": "pdfkit.from_url(“MyCSV.html”, “FinalOutput.pdf”)"
},
{
"code": null,
"e": 3116,
"s": 2896,
"text": "Else, we also need to install wkhtmltopdf for the script to run on our PC and set the installed file wkhtmltopdf.exe ‘s path to our PC’s Environment Variables and we can now skip the configuration section in the script."
},
{
"code": null,
"e": 3120,
"s": 3116,
"text": "or "
},
{
"code": null,
"e": 3269,
"s": 3120,
"text": "We can alternatively set Configuration as shown for the installed wkhtmltopdf.exe file and pass on the config variable to pdfkit.from_url function :"
},
{
"code": null,
"e": 3289,
"s": 3269,
"text": " Path Configuration"
},
{
"code": null,
"e": 3356,
"s": 3289,
"text": "path_wkhtmltopdf = r’D:\\Softwares\\wkhtmltopdf\\bin\\wkhtmltopdf.exe’"
},
{
"code": null,
"e": 3416,
"s": 3356,
"text": "config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)"
},
{
"code": null,
"e": 3453,
"s": 3416,
"text": "Convert HTML file to PDF with pdfkit"
},
{
"code": null,
"e": 3524,
"s": 3453,
"text": "pdfkit.from_url(“MyCSV.html”, “FinalOutput.pdf”, configuration=config)"
},
{
"code": null,
"e": 3540,
"s": 3524,
"text": "Implementation:"
},
{
"code": null,
"e": 3568,
"s": 3540,
"text": "Initial files in the folder"
},
{
"code": null,
"e": 3592,
"s": 3568,
"text": "INITIAL FILES IN FOLDER"
},
{
"code": null,
"e": 3599,
"s": 3592,
"text": "Python"
},
{
"code": "import pandas as pdimport pdfkit # SAVE CSV TO HTML USING PANDAScsv = 'MyCSV.csv'html_file = csv_file[:-3]+'html' df = pd.read_csv(csv_file, sep=',')df.to_html(html_file) # INSTALL wkhtmltopdf AND SET PATH IN CONFIGURATION# These two Steps could be eliminated By Installing wkhtmltopdf -# - and setting it's path to Environment Variablespath_wkhtmltopdf = r'D:\\Softwares\\wkhtmltopdf\\bin\\wkhtmltopdf.exe'config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf) # CONVERT HTML FILE TO PDF WITH PDFKITpdfkit.from_url(\"MyCSV.html\", \"FinalOutput.pdf\", configuration=config)",
"e": 4175,
"s": 3599,
"text": null
},
{
"code": null,
"e": 4211,
"s": 4175,
"text": "After Running Above Python Script :"
},
{
"code": null,
"e": 4267,
"s": 4211,
"text": "FILES IN the SAME DIRECTORY AFTER RUNNING PYTHON SCRIPT"
},
{
"code": null,
"e": 4282,
"s": 4267,
"text": "Final Output :"
},
{
"code": null,
"e": 4289,
"s": 4282,
"text": "Picked"
},
{
"code": null,
"e": 4300,
"s": 4289,
"text": "python-csv"
},
{
"code": null,
"e": 4307,
"s": 4300,
"text": "Python"
},
{
"code": null,
"e": 4405,
"s": 4307,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4437,
"s": 4405,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4464,
"s": 4437,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4485,
"s": 4464,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4508,
"s": 4485,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4564,
"s": 4508,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4606,
"s": 4564,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4637,
"s": 4606,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4679,
"s": 4637,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4718,
"s": 4679,
"text": "Python | Get unique values from a list"
}
] |
Non linear Regression examples – ML
|
07 Oct, 2021
Non-Linear regression is a type of polynomial regression. It is a method to model a non-linear relationship between the dependent and independent variables. It is used in place when the data shows a curvy trend, and linear regression would not produce very accurate results when compared to non-linear regression. This is because in linear regression it is pre-assumed that the data is linear.
Code:
Python3
import numpy as npimport pandas as pd # downloading dataset! wget -nv -O china_gdp.csv https://s3-api.us-geo.objectstorage.softlayer.net/ cf-courses-data/CognitiveClass/ML0101ENv3/labs/china_gdp.csv df = pd.read_csv("china_gdp.csv") def sigmoid(x, Beta_1, Beta_2): y = 1 / (1 + np.exp(-Beta_1*(x-Beta_2))) return y beta_1 = 0.10beta_2 = 1990.0 # logistic functionY_pred = sigmoid(x_data, beta_1, beta_2) # plot initial prediction against datapointsplt.plot(x_data, Y_pred * 15000000000000.)plt.plot(x_data, y_data, 'ro')
The scatter plot shows the relationship between GDP and time of a country, but the relationship is not linear. Instead after 2005 the line starts to become curve and does not follow a linear straight path. In such cases, a special estimation method is required called the non-linear regression.
Code:
Python3
import numpy as npimport pandas as pd # downloading dataset! wget -nv -O china_gdp.csv https://s3-api.us-geo.objectstorage.softlayer.net/ cf-courses-data / CognitiveClass / ML0101ENv3 / labs / china_gdp.csv df = pd.read_csv("china_gdp.csv") def sigmoid(x, Beta_1, Beta_2): y = 1 / (1 + np.exp(-Beta_1*(x-Beta_2))) return y x = np.linspace(1960, 2015, 55)x = x / max(x)y = sigmoid(x, *popt) plt.figure(figsize =(8, 5))plt.plot(xdata, ydata, 'ro', label ='data')plt.plot(x, y, linewidth = 3.0, label ='fit')plt.legend(loc ='best')plt.ylabel('GDP')plt.xlabel('Year')plt.show()
Output:
There are many different regressions that exists and can be used to fit whatever the dataset looks like such as quadratic, cubic regression, and so on to infinite degrees according to our requirement.
Code:
Python3
import numpy as npimport matplotlib.pyplot as plt % matplotlib inline x = np.arange(-5.0, 5.0, 0.1) ## You can adjust the slope and intercept to verify the changes in the graphy = 2*(x) + 3y_noise = 2 * np.random.normal(size = x.size)ydata = y + y_noise# plt.figure(figsize =(8, 6))plt.plot(x, ydata, 'bo')plt.plot(x, y, 'r')plt.ylabel('Dependent Variable')plt.xlabel('Independent Variable')plt.show()
Output:
Linear regression
Code:
Python3
import numpy as npimport matplotlib.pyplot as plt % matplotlib inline x = np.arange(-5.0, 5.0, 0.1) ## You can adjust the slope and intercept to verify the changes in the graph y = np.power(x, 2)y_noise = 2 * np.random.normal(size = x.size)ydata = y + y_noiseplt.plot(x, ydata, 'bo')plt.plot(x, y, 'r')plt.ylabel('Dependent Variable')plt.xlabel('Independent Variable')plt.show()
Output:
Quadratic Regression
Code:
Python3
import numpy as npimport matplotlib.pyplot as plt % matplotlib inline x = np.arange(-5.0, 5.0, 0.1) ## You can adjust the slope and intercept to verify the changes in the graphy = 1*(x**3) + 1*(x**2) + 1 * x + 3y_noise = 20 * np.random.normal(size = x.size)ydata = y + y_noiseplt.plot(x, ydata, 'bo')plt.plot(x, y, 'r')plt.ylabel('Dependent Variable')plt.xlabel('Independent Variable')plt.show()
Output:
Cubic Regression
We can call all of these polynomial regressions, where the relationship between the independent variable X and the dependent variable Y is modeled as an Nth degree polynomial in X.
Polynomial Regression
For a model to be considered non-linear, Y hat must be a non-linear function of the parameters Theta, not necessarily the features X. When it comes to non-linear equation, it can be the shape of exponential, logarithmic, and logistic, or many other types.
Output:
Non-Linear Regression Equations
As you can see in all of these equations, the change of Y hat depends on changes in the parameters Theta, not necessarily on X only. That is, in non-linear regression, a model is non-linear by parameters.
arorakashish0911
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
DBSCAN Clustering in ML | Density based clustering
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 423,
"s": 28,
"text": "Non-Linear regression is a type of polynomial regression. It is a method to model a non-linear relationship between the dependent and independent variables. It is used in place when the data shows a curvy trend, and linear regression would not produce very accurate results when compared to non-linear regression. This is because in linear regression it is pre-assumed that the data is linear. "
},
{
"code": null,
"e": 430,
"s": 423,
"text": "Code: "
},
{
"code": null,
"e": 438,
"s": 430,
"text": "Python3"
},
{
"code": "import numpy as npimport pandas as pd # downloading dataset! wget -nv -O china_gdp.csv https://s3-api.us-geo.objectstorage.softlayer.net/ cf-courses-data/CognitiveClass/ML0101ENv3/labs/china_gdp.csv df = pd.read_csv(\"china_gdp.csv\") def sigmoid(x, Beta_1, Beta_2): y = 1 / (1 + np.exp(-Beta_1*(x-Beta_2))) return y beta_1 = 0.10beta_2 = 1990.0 # logistic functionY_pred = sigmoid(x_data, beta_1, beta_2) # plot initial prediction against datapointsplt.plot(x_data, Y_pred * 15000000000000.)plt.plot(x_data, y_data, 'ro') ",
"e": 997,
"s": 438,
"text": null
},
{
"code": null,
"e": 1293,
"s": 997,
"text": "The scatter plot shows the relationship between GDP and time of a country, but the relationship is not linear. Instead after 2005 the line starts to become curve and does not follow a linear straight path. In such cases, a special estimation method is required called the non-linear regression. "
},
{
"code": null,
"e": 1300,
"s": 1293,
"text": "Code: "
},
{
"code": null,
"e": 1308,
"s": 1300,
"text": "Python3"
},
{
"code": "import numpy as npimport pandas as pd # downloading dataset! wget -nv -O china_gdp.csv https://s3-api.us-geo.objectstorage.softlayer.net/ cf-courses-data / CognitiveClass / ML0101ENv3 / labs / china_gdp.csv df = pd.read_csv(\"china_gdp.csv\") def sigmoid(x, Beta_1, Beta_2): y = 1 / (1 + np.exp(-Beta_1*(x-Beta_2))) return y x = np.linspace(1960, 2015, 55)x = x / max(x)y = sigmoid(x, *popt) plt.figure(figsize =(8, 5))plt.plot(xdata, ydata, 'ro', label ='data')plt.plot(x, y, linewidth = 3.0, label ='fit')plt.legend(loc ='best')plt.ylabel('GDP')plt.xlabel('Year')plt.show()",
"e": 1907,
"s": 1308,
"text": null
},
{
"code": null,
"e": 1917,
"s": 1907,
"text": "Output: "
},
{
"code": null,
"e": 2119,
"s": 1917,
"text": "There are many different regressions that exists and can be used to fit whatever the dataset looks like such as quadratic, cubic regression, and so on to infinite degrees according to our requirement. "
},
{
"code": null,
"e": 2126,
"s": 2119,
"text": "Code: "
},
{
"code": null,
"e": 2134,
"s": 2126,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt % matplotlib inline x = np.arange(-5.0, 5.0, 0.1) ## You can adjust the slope and intercept to verify the changes in the graphy = 2*(x) + 3y_noise = 2 * np.random.normal(size = x.size)ydata = y + y_noise# plt.figure(figsize =(8, 6))plt.plot(x, ydata, 'bo')plt.plot(x, y, 'r')plt.ylabel('Dependent Variable')plt.xlabel('Independent Variable')plt.show()",
"e": 2537,
"s": 2134,
"text": null
},
{
"code": null,
"e": 2547,
"s": 2537,
"text": "Output: "
},
{
"code": null,
"e": 2565,
"s": 2547,
"text": "Linear regression"
},
{
"code": null,
"e": 2572,
"s": 2565,
"text": "Code: "
},
{
"code": null,
"e": 2580,
"s": 2572,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt % matplotlib inline x = np.arange(-5.0, 5.0, 0.1) ## You can adjust the slope and intercept to verify the changes in the graph y = np.power(x, 2)y_noise = 2 * np.random.normal(size = x.size)ydata = y + y_noiseplt.plot(x, ydata, 'bo')plt.plot(x, y, 'r')plt.ylabel('Dependent Variable')plt.xlabel('Independent Variable')plt.show()",
"e": 2960,
"s": 2580,
"text": null
},
{
"code": null,
"e": 2969,
"s": 2960,
"text": "Output: "
},
{
"code": null,
"e": 2990,
"s": 2969,
"text": "Quadratic Regression"
},
{
"code": null,
"e": 2997,
"s": 2990,
"text": "Code: "
},
{
"code": null,
"e": 3005,
"s": 2997,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt % matplotlib inline x = np.arange(-5.0, 5.0, 0.1) ## You can adjust the slope and intercept to verify the changes in the graphy = 1*(x**3) + 1*(x**2) + 1 * x + 3y_noise = 20 * np.random.normal(size = x.size)ydata = y + y_noiseplt.plot(x, ydata, 'bo')plt.plot(x, y, 'r')plt.ylabel('Dependent Variable')plt.xlabel('Independent Variable')plt.show()",
"e": 3402,
"s": 3005,
"text": null
},
{
"code": null,
"e": 3411,
"s": 3402,
"text": "Output: "
},
{
"code": null,
"e": 3428,
"s": 3411,
"text": "Cubic Regression"
},
{
"code": null,
"e": 3611,
"s": 3428,
"text": "We can call all of these polynomial regressions, where the relationship between the independent variable X and the dependent variable Y is modeled as an Nth degree polynomial in X. "
},
{
"code": null,
"e": 3633,
"s": 3611,
"text": "Polynomial Regression"
},
{
"code": null,
"e": 3890,
"s": 3633,
"text": "For a model to be considered non-linear, Y hat must be a non-linear function of the parameters Theta, not necessarily the features X. When it comes to non-linear equation, it can be the shape of exponential, logarithmic, and logistic, or many other types. "
},
{
"code": null,
"e": 3899,
"s": 3890,
"text": "Output: "
},
{
"code": null,
"e": 3931,
"s": 3899,
"text": "Non-Linear Regression Equations"
},
{
"code": null,
"e": 4138,
"s": 3931,
"text": "As you can see in all of these equations, the change of Y hat depends on changes in the parameters Theta, not necessarily on X only. That is, in non-linear regression, a model is non-linear by parameters. "
},
{
"code": null,
"e": 4155,
"s": 4138,
"text": "arorakashish0911"
},
{
"code": null,
"e": 4172,
"s": 4155,
"text": "Machine Learning"
},
{
"code": null,
"e": 4179,
"s": 4172,
"text": "Python"
},
{
"code": null,
"e": 4196,
"s": 4179,
"text": "Machine Learning"
},
{
"code": null,
"e": 4294,
"s": 4196,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4335,
"s": 4294,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 4368,
"s": 4335,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 4404,
"s": 4368,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 4428,
"s": 4404,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 4479,
"s": 4428,
"text": "DBSCAN Clustering in ML | Density based clustering"
},
{
"code": null,
"e": 4507,
"s": 4479,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 4557,
"s": 4507,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 4579,
"s": 4557,
"text": "Python map() function"
},
{
"code": null,
"e": 4597,
"s": 4579,
"text": "Python Dictionary"
}
] |
Scala | Nested Functions
|
06 Jun, 2021
A function definition inside an another function is known as Nested Function. It is not supported by C++, Java, etc. In other languages, we can call a function inside a function, but it’s not a nested function. In Scala, we can define functions inside a function and functions defined inside other functions are called nested or local functions. Syntax:
def FunctionName1( parameter1, parameter2, ..) = { def FunctionName2() = { // code } }
Single Nested Function Here is an example of single nested function that takes two numbers as parameters and returns the Maximum and Minimum of them. Example
Scala
// Scala program of Single Nested Functionobject MaxAndMin{ // Main method def main(args: Array[String]) { println("Min and Max from 5, 7") maxAndMin(5, 7); } // Function def maxAndMin(a: Int, b: Int) = { // Nested Function def maxValue() = { if(a > b) { println("Max is: " + a) } else { println("Max is: " + b) } } // Nested Function def minValue() = { if (a < b) { println("Min is: " + a) } else { println("Min is: " + b) } } maxValue(); minValue(); }}
Output
Min and Max from 5, 7
Max is: 7
Min is: 5
In above code maxAndMin is a function and maxValue is another inner function returns maximum value between a and b similarly minValue is another inner function which is also nested function this function returns minimum value between a and b. Multiple Nested Function Here is an implementation of multiple nested function. Example
Scala
// Scala program of Multiple Nested Functionobject MaxAndMin{ // Main method def main(args: Array[String]) { fun(); } // Function def fun() = { geeks(); // First Nested Function def geeks() = { println("geeks"); gfg(); // Second Nested Function def gfg() = { println("gfg"); geeksforgeeks(); // Third Nested Function def geeksforgeeks() = { println("geeksforgeeks"); } } } }}
Output
geeks
gfg
geeksforgeeks
In above code fun is a function and geeks, gfg, geeksforgeeks are nested functions or local function .
sumitgumber28
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 408,
"s": 52,
"text": "A function definition inside an another function is known as Nested Function. It is not supported by C++, Java, etc. In other languages, we can call a function inside a function, but it’s not a nested function. In Scala, we can define functions inside a function and functions defined inside other functions are called nested or local functions. Syntax: "
},
{
"code": null,
"e": 495,
"s": 408,
"text": "def FunctionName1( parameter1, parameter2, ..) = { def FunctionName2() = { // code } }"
},
{
"code": null,
"e": 656,
"s": 495,
"text": " Single Nested Function Here is an example of single nested function that takes two numbers as parameters and returns the Maximum and Minimum of them. Example "
},
{
"code": null,
"e": 662,
"s": 656,
"text": "Scala"
},
{
"code": "// Scala program of Single Nested Functionobject MaxAndMin{ // Main method def main(args: Array[String]) { println(\"Min and Max from 5, 7\") maxAndMin(5, 7); } // Function def maxAndMin(a: Int, b: Int) = { // Nested Function def maxValue() = { if(a > b) { println(\"Max is: \" + a) } else { println(\"Max is: \" + b) } } // Nested Function def minValue() = { if (a < b) { println(\"Min is: \" + a) } else { println(\"Min is: \" + b) } } maxValue(); minValue(); }}",
"e": 1383,
"s": 662,
"text": null
},
{
"code": null,
"e": 1392,
"s": 1383,
"text": "Output "
},
{
"code": null,
"e": 1434,
"s": 1392,
"text": "Min and Max from 5, 7\nMax is: 7\nMin is: 5"
},
{
"code": null,
"e": 1767,
"s": 1434,
"text": "In above code maxAndMin is a function and maxValue is another inner function returns maximum value between a and b similarly minValue is another inner function which is also nested function this function returns minimum value between a and b. Multiple Nested Function Here is an implementation of multiple nested function. Example "
},
{
"code": null,
"e": 1773,
"s": 1767,
"text": "Scala"
},
{
"code": "// Scala program of Multiple Nested Functionobject MaxAndMin{ // Main method def main(args: Array[String]) { fun(); } // Function def fun() = { geeks(); // First Nested Function def geeks() = { println(\"geeks\"); gfg(); // Second Nested Function def gfg() = { println(\"gfg\"); geeksforgeeks(); // Third Nested Function def geeksforgeeks() = { println(\"geeksforgeeks\"); } } } }}",
"e": 2405,
"s": 1773,
"text": null
},
{
"code": null,
"e": 2414,
"s": 2405,
"text": "Output "
},
{
"code": null,
"e": 2438,
"s": 2414,
"text": "geeks\ngfg\ngeeksforgeeks"
},
{
"code": null,
"e": 2542,
"s": 2438,
"text": "In above code fun is a function and geeks, gfg, geeksforgeeks are nested functions or local function . "
},
{
"code": null,
"e": 2556,
"s": 2542,
"text": "sumitgumber28"
},
{
"code": null,
"e": 2569,
"s": 2556,
"text": "Scala-Method"
},
{
"code": null,
"e": 2575,
"s": 2569,
"text": "Scala"
}
] |
Difference Between DART and C++ - GeeksforGeeks
|
20 Aug, 2021
Competitive Programming teaches one to find the easiest solution in the quickest way possible. And C++ has always been loved by almost all the competitive programmers. C++ language is capable of boosting the speed of debugging and problem-solving which are the necessities for this brain sport.
Why is C++ a high in-demand language in competitive programming?
C++ was developed in 1980 by Bjarne Stroustrup. Ever since then, it has been actively used by the coders for real-world applications like game development, browsers, banking, graphics, advanced computations, and more. This is one reason why C++ hasn’t lost its place.
In-built functions: C++ is rich with the in-built functions that are associated with it. Eg: Sorting can be done in C++ using: sort(A, A+n) where ‘A’ is an array and ‘n’ indicates the length of the array.
A very vast library: The templates in C++ help the programmers quickly tackle basic data structures and functions. They include lists, stacks, arrays, etc. Also, many header files can be replaced by using a single STL(Standard Template Library). It actually makes the life of competitive programmers easier.
Speed: C++ is very fast compared to languages like Python and Java.Whether it’s compiling or I/O operations, C++ is swift compared to these languages using interpreters and complex codes.
This has made C++ by far the best and most popular languages in the competitive programming world.
Is DART a rival to C++?
DART is basically a client-optimized language and is meant for serving applications at the server-side as well as the browser side. It is also used in mobile applications. These days, Dart is seen replacing Kotlin in app development using Flutter as it avoids the need for a separate declarative layout language like XML and JSX. While C++ is an object-oriented programming language with generic features, Dart is an object-oriented, web-based programming language. Therefore, it can be easily compiled to JavaScript for browser applications. Also, we can use the Dart virtual machine on the server-side to replace Node.js. This has enabled Dart to erase the imprints of the C++ family in modern applications.
Basic Differences
Let’s peep into the basic dissimilarities between Dart and C++. How to read and display your name using these two languages?
1. Reading input from the user: C++ uses ‘cin’ and ‘scanf’ command to read the input from the user.
C++
Dart
#include <iostream>using namespace std;int main() { string name; cin>>name; return 0;}
import 'dart:io';void main(){ var name = stdin.readLineSync();}
2. Displaying an output: C++ displays the output using ‘cout’ and ‘printf’ commands. Whereas Dart uses the normal print statement as in Python or ‘write’ command. Also, parenthesis is used to specify the elements to be displayed in the Dart language.
C++
Dart
#include <iostream>using namespace std;int main(){ string name; cin>>name; cout<<name; return 0;}
import 'dart:io';void main(){ var name = stdin.readLineSync(); stdout.write(name);}
3. Language type: C++ is an object-oriented language. It supports the basic OOP features like polymorphism, encapsulation, classes, objects, abstraction, etc.
Did you know?
C++ is an impure object-oriented language. The reasons include:
Encapsulation is violated by the use of global variables in C++.
The use of classes is not important as in Java and if used they have to be specified inside the main function. This prevents the usage of multiple classes in C++.
On the other hand, the Dart language is a web-based programming language. It is also object-oriented, class-based, and garbage collected language. It is enabled with features like spread operator for expanding collections. Most importantly, Dart language is used for reactive programming where it can support features like user interface widgets. It also deals with data streams that are responsible for every change that takes place in a program.
4. Translator: Language translators like compiler and interpreter are used to convert a high-level language into machine level language. C++ is a compiled language and thus it becomes speedier when compared with Python which is interpreted.
Dart can also be compiled. But instead of resulting in a machine language, the Dart compiler will result in the JavaScript code which is in turn an interpreted language.dart can also be compiled into the native code to use with Node.js. Also, there is a Dart Virtual Machine that acts as an interpreter. Thus, Dart is an interpreted compiler language.
hanifullah007
C++
Dart
Difference Between
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Socket Programming in C/C++
Iterators in C++ STL
Operator Overloading in C++
C++ Classes and Objects
Flutter - DropDownButton Widget
Listview.builder in Flutter
Flutter - Asset Image
Splash Screen in Flutter
Flutter - Custom Bottom Navigation Bar
|
[
{
"code": null,
"e": 24187,
"s": 24159,
"text": "\n20 Aug, 2021"
},
{
"code": null,
"e": 24482,
"s": 24187,
"text": "Competitive Programming teaches one to find the easiest solution in the quickest way possible. And C++ has always been loved by almost all the competitive programmers. C++ language is capable of boosting the speed of debugging and problem-solving which are the necessities for this brain sport."
},
{
"code": null,
"e": 24548,
"s": 24482,
"text": "Why is C++ a high in-demand language in competitive programming? "
},
{
"code": null,
"e": 24816,
"s": 24548,
"text": "C++ was developed in 1980 by Bjarne Stroustrup. Ever since then, it has been actively used by the coders for real-world applications like game development, browsers, banking, graphics, advanced computations, and more. This is one reason why C++ hasn’t lost its place."
},
{
"code": null,
"e": 25021,
"s": 24816,
"text": "In-built functions: C++ is rich with the in-built functions that are associated with it. Eg: Sorting can be done in C++ using: sort(A, A+n) where ‘A’ is an array and ‘n’ indicates the length of the array."
},
{
"code": null,
"e": 25329,
"s": 25021,
"text": "A very vast library: The templates in C++ help the programmers quickly tackle basic data structures and functions. They include lists, stacks, arrays, etc. Also, many header files can be replaced by using a single STL(Standard Template Library). It actually makes the life of competitive programmers easier."
},
{
"code": null,
"e": 25517,
"s": 25329,
"text": "Speed: C++ is very fast compared to languages like Python and Java.Whether it’s compiling or I/O operations, C++ is swift compared to these languages using interpreters and complex codes."
},
{
"code": null,
"e": 25616,
"s": 25517,
"text": "This has made C++ by far the best and most popular languages in the competitive programming world."
},
{
"code": null,
"e": 25640,
"s": 25616,
"text": "Is DART a rival to C++?"
},
{
"code": null,
"e": 26350,
"s": 25640,
"text": "DART is basically a client-optimized language and is meant for serving applications at the server-side as well as the browser side. It is also used in mobile applications. These days, Dart is seen replacing Kotlin in app development using Flutter as it avoids the need for a separate declarative layout language like XML and JSX. While C++ is an object-oriented programming language with generic features, Dart is an object-oriented, web-based programming language. Therefore, it can be easily compiled to JavaScript for browser applications. Also, we can use the Dart virtual machine on the server-side to replace Node.js. This has enabled Dart to erase the imprints of the C++ family in modern applications."
},
{
"code": null,
"e": 26368,
"s": 26350,
"text": "Basic Differences"
},
{
"code": null,
"e": 26493,
"s": 26368,
"text": "Let’s peep into the basic dissimilarities between Dart and C++. How to read and display your name using these two languages?"
},
{
"code": null,
"e": 26594,
"s": 26493,
"text": "1. Reading input from the user: C++ uses ‘cin’ and ‘scanf’ command to read the input from the user."
},
{
"code": null,
"e": 26598,
"s": 26594,
"text": "C++"
},
{
"code": null,
"e": 26603,
"s": 26598,
"text": "Dart"
},
{
"code": "#include <iostream>using namespace std;int main() { string name; cin>>name; return 0;}",
"e": 26699,
"s": 26603,
"text": null
},
{
"code": "import 'dart:io';void main(){ var name = stdin.readLineSync();}",
"e": 26764,
"s": 26699,
"text": null
},
{
"code": null,
"e": 27022,
"s": 26771,
"text": "2. Displaying an output: C++ displays the output using ‘cout’ and ‘printf’ commands. Whereas Dart uses the normal print statement as in Python or ‘write’ command. Also, parenthesis is used to specify the elements to be displayed in the Dart language."
},
{
"code": null,
"e": 27028,
"s": 27024,
"text": "C++"
},
{
"code": null,
"e": 27033,
"s": 27028,
"text": "Dart"
},
{
"code": "#include <iostream>using namespace std;int main(){ string name; cin>>name; cout<<name; return 0;}",
"e": 27143,
"s": 27033,
"text": null
},
{
"code": "import 'dart:io';void main(){ var name = stdin.readLineSync(); stdout.write(name);}",
"e": 27230,
"s": 27143,
"text": null
},
{
"code": null,
"e": 27391,
"s": 27232,
"text": "3. Language type: C++ is an object-oriented language. It supports the basic OOP features like polymorphism, encapsulation, classes, objects, abstraction, etc."
},
{
"code": null,
"e": 27405,
"s": 27391,
"text": "Did you know?"
},
{
"code": null,
"e": 27470,
"s": 27405,
"text": " C++ is an impure object-oriented language. The reasons include:"
},
{
"code": null,
"e": 27535,
"s": 27470,
"text": "Encapsulation is violated by the use of global variables in C++."
},
{
"code": null,
"e": 27698,
"s": 27535,
"text": "The use of classes is not important as in Java and if used they have to be specified inside the main function. This prevents the usage of multiple classes in C++."
},
{
"code": null,
"e": 28146,
"s": 27698,
"text": "On the other hand, the Dart language is a web-based programming language. It is also object-oriented, class-based, and garbage collected language. It is enabled with features like spread operator for expanding collections. Most importantly, Dart language is used for reactive programming where it can support features like user interface widgets. It also deals with data streams that are responsible for every change that takes place in a program."
},
{
"code": null,
"e": 28387,
"s": 28146,
"text": "4. Translator: Language translators like compiler and interpreter are used to convert a high-level language into machine level language. C++ is a compiled language and thus it becomes speedier when compared with Python which is interpreted."
},
{
"code": null,
"e": 28739,
"s": 28387,
"text": "Dart can also be compiled. But instead of resulting in a machine language, the Dart compiler will result in the JavaScript code which is in turn an interpreted language.dart can also be compiled into the native code to use with Node.js. Also, there is a Dart Virtual Machine that acts as an interpreter. Thus, Dart is an interpreted compiler language."
},
{
"code": null,
"e": 28753,
"s": 28739,
"text": "hanifullah007"
},
{
"code": null,
"e": 28757,
"s": 28753,
"text": "C++"
},
{
"code": null,
"e": 28762,
"s": 28757,
"text": "Dart"
},
{
"code": null,
"e": 28781,
"s": 28762,
"text": "Difference Between"
},
{
"code": null,
"e": 28785,
"s": 28781,
"text": "CPP"
},
{
"code": null,
"e": 28883,
"s": 28785,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28892,
"s": 28883,
"text": "Comments"
},
{
"code": null,
"e": 28905,
"s": 28892,
"text": "Old Comments"
},
{
"code": null,
"e": 28924,
"s": 28905,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 28952,
"s": 28924,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 28973,
"s": 28952,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 29001,
"s": 28973,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 29025,
"s": 29001,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 29057,
"s": 29025,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 29085,
"s": 29057,
"text": "Listview.builder in Flutter"
},
{
"code": null,
"e": 29107,
"s": 29085,
"text": "Flutter - Asset Image"
},
{
"code": null,
"e": 29132,
"s": 29107,
"text": "Splash Screen in Flutter"
}
] |
Append to StringBuilder in C# with a new line on the end
|
The AppendLine() method appends the content and add a new line on the end.
Firstly, set the StringBuilder −
StringBuilder str = new StringBuilder();
Use AppendLine() −
str.AppendLine("Accessories");
str.AppendLine();
str.AppendLine("Electronics");
The following is the complete code −
Live Demo
using System;
using System.Text;
class Demo {
static void Main() {
StringBuilder str = new StringBuilder();
str.AppendLine("Accessories");
str.AppendLine();
str.AppendLine("Electronics");
Console.Write(str);
}
}
Accessories
Electronics
|
[
{
"code": null,
"e": 1137,
"s": 1062,
"text": "The AppendLine() method appends the content and add a new line on the end."
},
{
"code": null,
"e": 1170,
"s": 1137,
"text": "Firstly, set the StringBuilder −"
},
{
"code": null,
"e": 1211,
"s": 1170,
"text": "StringBuilder str = new StringBuilder();"
},
{
"code": null,
"e": 1230,
"s": 1211,
"text": "Use AppendLine() −"
},
{
"code": null,
"e": 1310,
"s": 1230,
"text": "str.AppendLine(\"Accessories\");\nstr.AppendLine();\nstr.AppendLine(\"Electronics\");"
},
{
"code": null,
"e": 1347,
"s": 1310,
"text": "The following is the complete code −"
},
{
"code": null,
"e": 1358,
"s": 1347,
"text": " Live Demo"
},
{
"code": null,
"e": 1607,
"s": 1358,
"text": "using System;\nusing System.Text;\n\nclass Demo {\n static void Main() {\n StringBuilder str = new StringBuilder();\n str.AppendLine(\"Accessories\");\n str.AppendLine();\n str.AppendLine(\"Electronics\");\n Console.Write(str);\n }\n}"
},
{
"code": null,
"e": 1632,
"s": 1607,
"text": "Accessories\n\nElectronics"
}
] |
Convert datetime to get month name in MySQL?
|
To get only month name, the syntax is as follows −
select date_format(yourColumnName,'%M %Y') from yourTableName;
Let us first create a table −
mysql> create table DemoTable1619
-> (
-> ArrivalTime datetime
-> );
Query OK, 0 rows affected (0.45 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1619 values(now());
Query OK, 1 row affected (0.40 sec)
mysql> insert into DemoTable1619 values(curdate());
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1619 values('2019-12-31');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1619;
This will produce the following output −
+---------------------+
| ArrivalTime |
+---------------------+
| 2019-10-20 15:02:12 |
| 2019-10-20 00:00:00 |
| 2019-12-31 00:00:00 |
+---------------------+
3 rows in set (0.00 sec)
Following is the query to convert datetime to get month name in MySQL −
mysql> select date_format(ArrivalTime,'%M %Y') from DemoTable1619;
This will produce the following output −
+----------------------------------+
| date_format(ArrivalTime,'%M %Y') |
+----------------------------------+
| October 2019 |
| October 2019 |
| December 2019 |
+----------------------------------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1113,
"s": 1062,
"text": "To get only month name, the syntax is as follows −"
},
{
"code": null,
"e": 1176,
"s": 1113,
"text": "select date_format(yourColumnName,'%M %Y') from yourTableName;"
},
{
"code": null,
"e": 1206,
"s": 1176,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1324,
"s": 1206,
"text": "mysql> create table DemoTable1619\n -> (\n -> ArrivalTime datetime\n -> );\nQuery OK, 0 rows affected (0.45 sec)"
},
{
"code": null,
"e": 1380,
"s": 1324,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1643,
"s": 1380,
"text": "mysql> insert into DemoTable1619 values(now());\nQuery OK, 1 row affected (0.40 sec)\nmysql> insert into DemoTable1619 values(curdate());\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable1619 values('2019-12-31');\nQuery OK, 1 row affected (0.17 sec)"
},
{
"code": null,
"e": 1703,
"s": 1643,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1739,
"s": 1703,
"text": "mysql> select * from DemoTable1619;"
},
{
"code": null,
"e": 1780,
"s": 1739,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1973,
"s": 1780,
"text": "+---------------------+\n| ArrivalTime |\n+---------------------+\n| 2019-10-20 15:02:12 |\n| 2019-10-20 00:00:00 |\n| 2019-12-31 00:00:00 |\n+---------------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2045,
"s": 1973,
"text": "Following is the query to convert datetime to get month name in MySQL −"
},
{
"code": null,
"e": 2112,
"s": 2045,
"text": "mysql> select date_format(ArrivalTime,'%M %Y') from DemoTable1619;"
},
{
"code": null,
"e": 2153,
"s": 2112,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2437,
"s": 2153,
"text": "+----------------------------------+\n| date_format(ArrivalTime,'%M %Y') |\n+----------------------------------+\n| October 2019 |\n| October 2019 |\n| December 2019 |\n+----------------------------------+\n3 rows in set (0.00 sec)"
}
] |
How to set up a cookie that never expires in JavaScript ?
|
29 Oct, 2021
We can set up a cookie that never expires in JavaScript using the following approach:
Prerequisites :
Intermediate level knowledge of JavaScript
Basic HTML
Disclaimer: All the cookies expire as per the cookie specification. So, there is no block of code you can write in JavaScript to set up a cookie that never expires. It is just impossible and is a fact.
Solution: But you can set up a cookie that expires in JavaScript and pick some very large value as expiry date as specified below:
document.cookie = "cookieName= true; expires=Fri, 31 Dec 9999 23:59:59 GMT";
NOTE: But browsers have a problem with the dates after 2038-01-19 04:14:07 as the Unix epoch time exceeds 32-bit int. This problem is also called the Year 2038 problem (also called Y2038, Epochalypse, Y2k38, or Unix Y2K).
Hence, the maximum value you can set as an expiry date for a cookie that is supported by the majority of web browsers is:
231 - 1 = 2147483647 ie. 2038-01-19 04:14:07
Syntax:
document.cookie = "cookieName= true; expires=Tue, 19 Jan 2038 04:14:07 GMT";
// OR
const cookieName = "something";
const cookieValue = "something";
const daysToExpire = new Date(2147483647 * 1000).toUTCString();
document.cookie = cookieName + '=' + cookieValue + '; expires=' + daysToExpire;
Code:
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script type="text/javascript"> const createCookieWithY2K38 = (cookieName, cookieValue) => { // Expiry date conversion into UTC standard string const daysToExpire = new Date(2147483647 * 1000).toUTCString(); // Setting up the cookie name, value with the expiry date document.cookie = cookieName + '=' + cookieValue + '; expires=' + daysToExpire; alert('Welcome ' + cookieValue); } const extractUserNameFromCookie = (cookieName) => { var userName = cookieName + '='; // Splitting cookie var allCookieArray = document.cookie.split(';'); for (var i = 0; i < allCookieArray.length; i++) { // Extracting userName and returning the same var temp = allCookieArray[i].trim(); if (temp.indexOf(userName) == 0) return temp.substring(userName.length, temp.length); } // Else return empty string return ''; } const readCookieAndGreetUser = () => { var userName = extractUserNameFromCookie('testCookie'); if (userName != '') { // If user is visiting the page again // "user" variable will not be a empty string // returned by the accessCookie() function // and will greet the user alert('Welcome ' + userName); } else { userName = prompt('Please enter your name'); if (userName != '' && userName != null) { createCookieWithY2K38('testCookie', userName); } } } </script></head><body onload="readCookieAndGreetUser()"></body></html>
Output:
Long Lasting Cookie
kashishsoda
HTML5
JavaScript-Questions
Picked
Technical Scripter 2020
HTML
JavaScript
Technical Scripter
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": "\n29 Oct, 2021"
},
{
"code": null,
"e": 114,
"s": 28,
"text": "We can set up a cookie that never expires in JavaScript using the following approach:"
},
{
"code": null,
"e": 130,
"s": 114,
"text": "Prerequisites :"
},
{
"code": null,
"e": 173,
"s": 130,
"text": "Intermediate level knowledge of JavaScript"
},
{
"code": null,
"e": 186,
"s": 173,
"text": "Basic HTML "
},
{
"code": null,
"e": 388,
"s": 186,
"text": "Disclaimer: All the cookies expire as per the cookie specification. So, there is no block of code you can write in JavaScript to set up a cookie that never expires. It is just impossible and is a fact."
},
{
"code": null,
"e": 519,
"s": 388,
"text": "Solution: But you can set up a cookie that expires in JavaScript and pick some very large value as expiry date as specified below:"
},
{
"code": null,
"e": 596,
"s": 519,
"text": "document.cookie = \"cookieName= true; expires=Fri, 31 Dec 9999 23:59:59 GMT\";"
},
{
"code": null,
"e": 818,
"s": 596,
"text": "NOTE: But browsers have a problem with the dates after 2038-01-19 04:14:07 as the Unix epoch time exceeds 32-bit int. This problem is also called the Year 2038 problem (also called Y2038, Epochalypse, Y2k38, or Unix Y2K)."
},
{
"code": null,
"e": 940,
"s": 818,
"text": "Hence, the maximum value you can set as an expiry date for a cookie that is supported by the majority of web browsers is:"
},
{
"code": null,
"e": 986,
"s": 940,
"text": "231 - 1 = 2147483647 ie. 2038-01-19 04:14:07 "
},
{
"code": null,
"e": 994,
"s": 986,
"text": "Syntax:"
},
{
"code": null,
"e": 1287,
"s": 994,
"text": "document.cookie = \"cookieName= true; expires=Tue, 19 Jan 2038 04:14:07 GMT\";\n\n// OR\nconst cookieName = \"something\";\nconst cookieValue = \"something\";\nconst daysToExpire = new Date(2147483647 * 1000).toUTCString();\ndocument.cookie = cookieName + '=' + cookieValue + '; expires=' + daysToExpire;"
},
{
"code": null,
"e": 1294,
"s": 1287,
"text": "Code: "
},
{
"code": null,
"e": 1299,
"s": 1294,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <script type=\"text/javascript\"> const createCookieWithY2K38 = (cookieName, cookieValue) => { // Expiry date conversion into UTC standard string const daysToExpire = new Date(2147483647 * 1000).toUTCString(); // Setting up the cookie name, value with the expiry date document.cookie = cookieName + '=' + cookieValue + '; expires=' + daysToExpire; alert('Welcome ' + cookieValue); } const extractUserNameFromCookie = (cookieName) => { var userName = cookieName + '='; // Splitting cookie var allCookieArray = document.cookie.split(';'); for (var i = 0; i < allCookieArray.length; i++) { // Extracting userName and returning the same var temp = allCookieArray[i].trim(); if (temp.indexOf(userName) == 0) return temp.substring(userName.length, temp.length); } // Else return empty string return ''; } const readCookieAndGreetUser = () => { var userName = extractUserNameFromCookie('testCookie'); if (userName != '') { // If user is visiting the page again // \"user\" variable will not be a empty string // returned by the accessCookie() function // and will greet the user alert('Welcome ' + userName); } else { userName = prompt('Please enter your name'); if (userName != '' && userName != null) { createCookieWithY2K38('testCookie', userName); } } } </script></head><body onload=\"readCookieAndGreetUser()\"></body></html>",
"e": 3271,
"s": 1299,
"text": null
},
{
"code": null,
"e": 3282,
"s": 3274,
"text": "Output:"
},
{
"code": null,
"e": 3304,
"s": 3284,
"text": "Long Lasting Cookie"
},
{
"code": null,
"e": 3318,
"s": 3306,
"text": "kashishsoda"
},
{
"code": null,
"e": 3324,
"s": 3318,
"text": "HTML5"
},
{
"code": null,
"e": 3345,
"s": 3324,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 3352,
"s": 3345,
"text": "Picked"
},
{
"code": null,
"e": 3376,
"s": 3352,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3381,
"s": 3376,
"text": "HTML"
},
{
"code": null,
"e": 3392,
"s": 3381,
"text": "JavaScript"
},
{
"code": null,
"e": 3411,
"s": 3392,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3428,
"s": 3411,
"text": "Web Technologies"
},
{
"code": null,
"e": 3455,
"s": 3428,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3460,
"s": 3455,
"text": "HTML"
}
] |
Sorting rows of matrix in ascending order followed by columns in descending order
|
06 Jul, 2022
Given a matrix, sort the rows of matrix in ascending order followed by sorting the columns in descending order. Examples :
Input : a[3][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
Output : 7 8 9
4 5 6
1 2 3
Input : a[3][3] = {{3, 2, 1},
{9, 8, 7},
{6, 5, 4}};
Output : 7 8 9
4 5 6
1 2 3
Approach:
Traverse all rows one by one and sort rows in ascending order using a simple array sort.
Convert matrix to its transpose
Again sort all rows, but this time in descending order.
Again convert a matrix to its transpose
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to sort the rows// of matrix in ascending order followed by// sorting the columns in descending order#include <bits/stdc++.h>using namespace std; #define MAX_SIZE 10 // function to sort each row of the matrix// according to the order specified by// ascending.void sortByRow(int mat[][MAX_SIZE], int n, bool ascending){ for (int i = 0; i < n; i++) { if (ascending) sort(mat[i], mat[i] + n); else sort(mat[i], mat[i] + n, greater<int>()); } } // function to find transpose of the matrixvoid transpose(int mat[][MAX_SIZE], int n){ for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) // swapping element at index (i, j) // by element at index (j, i) swap(mat[i][j], mat[j][i]);} // function to sort the matrix row-wise// and column-wisevoid sortMatRowAndColWise(int mat[][MAX_SIZE], int n){ // sort rows of mat[][] sortByRow(mat, n, true); // get transpose of mat[][] transpose(mat, n); // again sort rows of mat[][] in descending // order. sortByRow(mat, n, false); // again get transpose of mat[][] transpose(mat, n);} // function to print the matrixvoid printMat(int mat[][MAX_SIZE], int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << mat[i][j] << " "; cout << endl; }} // Driver program to test aboveint main(){ int n = 3; int mat[n][MAX_SIZE] = {{3, 2, 1}, {9, 8, 7}, {6, 5, 4}}; cout << "Original Matrix:\n"; printMat(mat, n); sortMatRowAndColWise(mat, n); cout << "\nMatrix After Sorting:\n"; printMat(mat, n); return 0;}
// Java implementation to sort the rows// of matrix in ascending order followed by// sorting the columns in descending orderimport java.util.Arrays;import java.util.Collections; class GFG{ static int MAX_SIZE=10; // function to sort each row of the matrix // according to the order specified by // ascending. static void sortByRow(Integer mat[][], int n, boolean ascending) { for (int i = 0; i < n; i++) { if (ascending) Arrays.sort(mat[i]); else Arrays.sort(mat[i],Collections.reverseOrder()); } } // function to find transpose of the matrix static void transpose(Integer mat[][], int n) { for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) { // swapping element at index (i, j) // by element at index (j, i) int temp = mat[i][j]; mat[i][j] = mat[j][i]; mat[j][i] = temp; } } // function to sort the matrix row-wise // and column-wise static void sortMatRowAndColWise(Integer mat[][], int n) { // sort rows of mat[][] sortByRow(mat, n, true); // get transpose of mat[][] transpose(mat, n); // again sort rows of mat[][] in descending // order. sortByRow(mat, n, false); // again get transpose of mat[][] transpose(mat, n); } // function to print the matrix static void printMat(Integer mat[][], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) System.out.print(mat[i][j] + " "); System.out.println(); } } // Driver code public static void main (String[] args) { int n = 3; Integer mat[][] = {{3, 2, 1}, {9, 8, 7}, {6, 5, 4}}; System.out.print("Original Matrix:\n"); printMat(mat, n); sortMatRowAndColWise(mat, n); System.out.print("\nMatrix After Sorting:\n"); printMat(mat, n); }} // This code is contributed by Anant Agarwal.
# Python implementation to sort the rows# of matrix in ascending order followed by# sorting the columns in descending order MAX_SIZE=10 # function to sort each row of the matrix# according to the order specified by# ascending.def sortByRow(mat, n, ascending): for i in range(n): if (ascending): mat[i].sort() else: mat[i].sort(reverse=True) # function to find# transpose of the matrixdef transpose(mat, n): for i in range(n): for j in range(i + 1, n): # swapping element at index (i, j) # by element at index (j, i) temp = mat[i][j] mat[i][j] = mat[j][i] mat[j][i] = temp # function to sort# the matrix row-wise# and column-wisedef sortMatRowAndColWise(mat, n): # sort rows of mat[][] sortByRow(mat, n, True) # get transpose of mat[][] transpose(mat, n) # again sort rows of # mat[][] in descending # order. sortByRow(mat, n, False) # again get transpose of mat[][] transpose(mat, n) # function to print the matrixdef printMat(mat, n): for i in range(n): for j in range(n): print(mat[i][j] , " ", end="") print() #Driver coden = 3 mat = [[3, 2, 1], [9, 8, 7], [6, 5, 4]] print("Original Matrix:")printMat(mat, n) sortMatRowAndColWise(mat, n) print("Matrix After Sorting:")printMat(mat, n) # This code is contributed# by Anant Agarwal.
// C# implementation to sort the rows// of matrix in ascending order followed by// sorting the columns in descending orderusing System; public static class GFG { // function to sort each row of the matrix // according to the order specified by // ascending. static void sortByRow(int[, ] m) { // loop for rows of matrix for (int i = 0; i < m.GetLength(0); i++) { // loop for column of matrix for (int j = 0; j < m.GetLength(1); j++) { // loop for comparison and swapping for (int k = 0; k < m.GetLength(1) - j - 1; k++) { if (m[i, k] > m[i, k + 1]) { // swapping of elements int t = m[i, k]; m[i, k] = m[i, k + 1]; m[i, k + 1] = t; } } } } } static void reverseArray(int[, ] arr) { // Traverse each row of [,]arr for (int i = 0; i < arr.GetLength(1); i++) { // Initialise start and end index int start = 0; int end = arr.GetLength(0) - 1; // Till start < end, swap the element // at start and end index while (start < end) { // Swap the element int temp = arr[i, start]; arr[i, start] = arr[i, end]; arr[i, end] = temp; // Increment start and decrement // end for next pair of swapping start++; end--; } } } // function to find transpose of the matrix public static void transpose(int[, ] mat, int n) { for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // swapping element at index (i, j) // by element at index (j, i) int temp = mat[i, j]; mat[i, j] = mat[j, i]; mat[j, i] = temp; } } } // function to sort the matrix row-wise // and column-wise public static void sortMatRowAndColWise(int[, ] mat, int n) { // sort rows of mat[][] sortByRow(mat); // get transpose of mat[][] transpose(mat, n); // again sort rows of mat[][] in descending // order. sortByRow(mat); reverseArray(mat); // again get transpose of mat[][] transpose(mat, n); } // function to print the matrix public static void printMat(int[, ] mat, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { Console.Write(mat[i, j]); Console.Write(" "); } Console.Write("\n"); } } // Driver program to test above internal static void Main() { int n = 3; int[, ] mat = { { 3, 2, 1 }, { 9, 8, 7 }, { 6, 5, 4 } }; Console.Write("Original Matrix:\n"); printMat(mat, n); sortMatRowAndColWise(mat, n); Console.Write("\nMatrix After Sorting:\n"); printMat(mat, n); }} // This code is contributed by Aarti_Rathi
<?php// PHP implementation to sort the rows// of matrix in ascending order followed by// sorting the columns in descending order$MAX_SIZE = 10; // function to sort each row of the matrix// according to the order specified by// ascending.function sortByRow(&$mat, $n, $ascending){ for ($i = 0; $i < $n; $i++) { if ($ascending) sort($mat[$i]); else rsort($mat[$i]); } } // function to find transpose// of the matrixfunction transpose(&$mat, $n){ for ($i = 0; $i < $n; $i++) { for ($j = $i + 1; $j < $n; $j++) { // swapping element at index (i, j) // by element at index (j, i) $temp = $mat[$i][$j]; $mat[$i][$j] = $mat[$j][$i]; $mat[$j][$i] = $temp; } }} // function to sort the matrix row-wise// and column-wisefunction sortMatRowAndColWise(&$mat, $n){ // sort rows of mat[][] sortByRow($mat, $n, true); // get transpose of mat[][] transpose($mat, $n); // again sort rows of mat[][] in // descending order. sortByRow($mat, $n, false); // again get transpose of mat[][] transpose($mat, $n);} // function to print the matrixfunction printMat(&$mat, $n){ for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) echo $mat[$i][$j] . " "; echo "\n" ; }} // Driver Code$n = 3; $mat = array(array(3, 2, 1), array(9, 8, 7), array(6, 5, 4)); echo "Original Matrix:\n";printMat($mat, $n); sortMatRowAndColWise($mat, $n); echo "\nMatrix After Sorting:\n";printMat($mat, $n); // This code is contributed by Ita_c?>
<script>// Javascript implementation to sort the rows// of matrix in ascending order followed by// sorting the columns in descending order let MAX_SIZE=10; // function to sort each row of the matrix // according to the order specified by // ascending. function sortByRow(mat,n,ascending) { for (let i = 0; i < n; i++) { if (ascending) mat[i].sort(function(a,b){return a-b;}); else mat[i].sort(function(a,b){return b-a;}); } } // function to find transpose of the matrix function transpose(mat,n) { for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) { // swapping element at index (i, j) // by element at index (j, i) let temp = mat[i][j]; mat[i][j] = mat[j][i]; mat[j][i] = temp; } } // function to sort the matrix row-wise // and column-wise function sortMatRowAndColWise(mat,n) { // sort rows of mat[][] sortByRow(mat, n, true); // get transpose of mat[][] transpose(mat, n); // again sort rows of mat[][] in descending // order. sortByRow(mat, n, false); // again get transpose of mat[][] transpose(mat, n); } // function to print the matrix function printMat(mat,n) { for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) document.write(mat[i][j] + " "); document.write("<br>"); } } // Driver code let n = 3; let mat = [[3, 2, 1], [9, 8, 7], [6, 5, 4]]; document.write("Original Matrix:<br>"); printMat(mat, n); sortMatRowAndColWise(mat, n); document.write("\nMatrix After Sorting:<br>"); printMat(mat, n); // This code is contributed by avanitrachhadiya2155</script>
Original Matrix:
3 2 1
9 8 7
6 5 4
Matrix After Sorting:
7 8 9
4 5 6
1 2 3
Time Complexity: O(N2 log N)Auxiliary Space: O(1)
ukasp
avanitrachhadiya2155
singhh3010
codewithshinchan
harendrakumar123
Matrix
Sorting
Sorting
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Rat in a Maze | Backtracking-2
Sudoku | Backtracking-7
The Celebrity Problem
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Jul, 2022"
},
{
"code": null,
"e": 178,
"s": 54,
"text": "Given a matrix, sort the rows of matrix in ascending order followed by sorting the columns in descending order. Examples : "
},
{
"code": null,
"e": 449,
"s": 178,
"text": "Input : a[3][3] = {{1, 2, 3},\n {4, 5, 6}, \n {7, 8, 9}};\nOutput : 7 8 9\n 4 5 6\n 1 2 3\n\nInput : a[3][3] = {{3, 2, 1},\n {9, 8, 7}, \n {6, 5, 4}};\nOutput : 7 8 9\n 4 5 6\n 1 2 3"
},
{
"code": null,
"e": 459,
"s": 449,
"text": "Approach:"
},
{
"code": null,
"e": 549,
"s": 459,
"text": "Traverse all rows one by one and sort rows in ascending order using a simple array sort. "
},
{
"code": null,
"e": 582,
"s": 549,
"text": "Convert matrix to its transpose "
},
{
"code": null,
"e": 639,
"s": 582,
"text": "Again sort all rows, but this time in descending order. "
},
{
"code": null,
"e": 680,
"s": 639,
"text": "Again convert a matrix to its transpose "
},
{
"code": null,
"e": 731,
"s": 680,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 735,
"s": 731,
"text": "C++"
},
{
"code": null,
"e": 740,
"s": 735,
"text": "Java"
},
{
"code": null,
"e": 748,
"s": 740,
"text": "Python3"
},
{
"code": null,
"e": 751,
"s": 748,
"text": "C#"
},
{
"code": null,
"e": 755,
"s": 751,
"text": "PHP"
},
{
"code": null,
"e": 766,
"s": 755,
"text": "Javascript"
},
{
"code": "// C++ implementation to sort the rows// of matrix in ascending order followed by// sorting the columns in descending order#include <bits/stdc++.h>using namespace std; #define MAX_SIZE 10 // function to sort each row of the matrix// according to the order specified by// ascending.void sortByRow(int mat[][MAX_SIZE], int n, bool ascending){ for (int i = 0; i < n; i++) { if (ascending) sort(mat[i], mat[i] + n); else sort(mat[i], mat[i] + n, greater<int>()); } } // function to find transpose of the matrixvoid transpose(int mat[][MAX_SIZE], int n){ for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) // swapping element at index (i, j) // by element at index (j, i) swap(mat[i][j], mat[j][i]);} // function to sort the matrix row-wise// and column-wisevoid sortMatRowAndColWise(int mat[][MAX_SIZE], int n){ // sort rows of mat[][] sortByRow(mat, n, true); // get transpose of mat[][] transpose(mat, n); // again sort rows of mat[][] in descending // order. sortByRow(mat, n, false); // again get transpose of mat[][] transpose(mat, n);} // function to print the matrixvoid printMat(int mat[][MAX_SIZE], int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << mat[i][j] << \" \"; cout << endl; }} // Driver program to test aboveint main(){ int n = 3; int mat[n][MAX_SIZE] = {{3, 2, 1}, {9, 8, 7}, {6, 5, 4}}; cout << \"Original Matrix:\\n\"; printMat(mat, n); sortMatRowAndColWise(mat, n); cout << \"\\nMatrix After Sorting:\\n\"; printMat(mat, n); return 0;}",
"e": 2543,
"s": 766,
"text": null
},
{
"code": "// Java implementation to sort the rows// of matrix in ascending order followed by// sorting the columns in descending orderimport java.util.Arrays;import java.util.Collections; class GFG{ static int MAX_SIZE=10; // function to sort each row of the matrix // according to the order specified by // ascending. static void sortByRow(Integer mat[][], int n, boolean ascending) { for (int i = 0; i < n; i++) { if (ascending) Arrays.sort(mat[i]); else Arrays.sort(mat[i],Collections.reverseOrder()); } } // function to find transpose of the matrix static void transpose(Integer mat[][], int n) { for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) { // swapping element at index (i, j) // by element at index (j, i) int temp = mat[i][j]; mat[i][j] = mat[j][i]; mat[j][i] = temp; } } // function to sort the matrix row-wise // and column-wise static void sortMatRowAndColWise(Integer mat[][], int n) { // sort rows of mat[][] sortByRow(mat, n, true); // get transpose of mat[][] transpose(mat, n); // again sort rows of mat[][] in descending // order. sortByRow(mat, n, false); // again get transpose of mat[][] transpose(mat, n); } // function to print the matrix static void printMat(Integer mat[][], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) System.out.print(mat[i][j] + \" \"); System.out.println(); } } // Driver code public static void main (String[] args) { int n = 3; Integer mat[][] = {{3, 2, 1}, {9, 8, 7}, {6, 5, 4}}; System.out.print(\"Original Matrix:\\n\"); printMat(mat, n); sortMatRowAndColWise(mat, n); System.out.print(\"\\nMatrix After Sorting:\\n\"); printMat(mat, n); }} // This code is contributed by Anant Agarwal.",
"e": 4826,
"s": 2543,
"text": null
},
{
"code": "# Python implementation to sort the rows# of matrix in ascending order followed by# sorting the columns in descending order MAX_SIZE=10 # function to sort each row of the matrix# according to the order specified by# ascending.def sortByRow(mat, n, ascending): for i in range(n): if (ascending): mat[i].sort() else: mat[i].sort(reverse=True) # function to find# transpose of the matrixdef transpose(mat, n): for i in range(n): for j in range(i + 1, n): # swapping element at index (i, j) # by element at index (j, i) temp = mat[i][j] mat[i][j] = mat[j][i] mat[j][i] = temp # function to sort# the matrix row-wise# and column-wisedef sortMatRowAndColWise(mat, n): # sort rows of mat[][] sortByRow(mat, n, True) # get transpose of mat[][] transpose(mat, n) # again sort rows of # mat[][] in descending # order. sortByRow(mat, n, False) # again get transpose of mat[][] transpose(mat, n) # function to print the matrixdef printMat(mat, n): for i in range(n): for j in range(n): print(mat[i][j] , \" \", end=\"\") print() #Driver coden = 3 mat = [[3, 2, 1], [9, 8, 7], [6, 5, 4]] print(\"Original Matrix:\")printMat(mat, n) sortMatRowAndColWise(mat, n) print(\"Matrix After Sorting:\")printMat(mat, n) # This code is contributed# by Anant Agarwal.",
"e": 6262,
"s": 4826,
"text": null
},
{
"code": "// C# implementation to sort the rows// of matrix in ascending order followed by// sorting the columns in descending orderusing System; public static class GFG { // function to sort each row of the matrix // according to the order specified by // ascending. static void sortByRow(int[, ] m) { // loop for rows of matrix for (int i = 0; i < m.GetLength(0); i++) { // loop for column of matrix for (int j = 0; j < m.GetLength(1); j++) { // loop for comparison and swapping for (int k = 0; k < m.GetLength(1) - j - 1; k++) { if (m[i, k] > m[i, k + 1]) { // swapping of elements int t = m[i, k]; m[i, k] = m[i, k + 1]; m[i, k + 1] = t; } } } } } static void reverseArray(int[, ] arr) { // Traverse each row of [,]arr for (int i = 0; i < arr.GetLength(1); i++) { // Initialise start and end index int start = 0; int end = arr.GetLength(0) - 1; // Till start < end, swap the element // at start and end index while (start < end) { // Swap the element int temp = arr[i, start]; arr[i, start] = arr[i, end]; arr[i, end] = temp; // Increment start and decrement // end for next pair of swapping start++; end--; } } } // function to find transpose of the matrix public static void transpose(int[, ] mat, int n) { for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // swapping element at index (i, j) // by element at index (j, i) int temp = mat[i, j]; mat[i, j] = mat[j, i]; mat[j, i] = temp; } } } // function to sort the matrix row-wise // and column-wise public static void sortMatRowAndColWise(int[, ] mat, int n) { // sort rows of mat[][] sortByRow(mat); // get transpose of mat[][] transpose(mat, n); // again sort rows of mat[][] in descending // order. sortByRow(mat); reverseArray(mat); // again get transpose of mat[][] transpose(mat, n); } // function to print the matrix public static void printMat(int[, ] mat, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { Console.Write(mat[i, j]); Console.Write(\" \"); } Console.Write(\"\\n\"); } } // Driver program to test above internal static void Main() { int n = 3; int[, ] mat = { { 3, 2, 1 }, { 9, 8, 7 }, { 6, 5, 4 } }; Console.Write(\"Original Matrix:\\n\"); printMat(mat, n); sortMatRowAndColWise(mat, n); Console.Write(\"\\nMatrix After Sorting:\\n\"); printMat(mat, n); }} // This code is contributed by Aarti_Rathi",
"e": 9486,
"s": 6262,
"text": null
},
{
"code": "<?php// PHP implementation to sort the rows// of matrix in ascending order followed by// sorting the columns in descending order$MAX_SIZE = 10; // function to sort each row of the matrix// according to the order specified by// ascending.function sortByRow(&$mat, $n, $ascending){ for ($i = 0; $i < $n; $i++) { if ($ascending) sort($mat[$i]); else rsort($mat[$i]); } } // function to find transpose// of the matrixfunction transpose(&$mat, $n){ for ($i = 0; $i < $n; $i++) { for ($j = $i + 1; $j < $n; $j++) { // swapping element at index (i, j) // by element at index (j, i) $temp = $mat[$i][$j]; $mat[$i][$j] = $mat[$j][$i]; $mat[$j][$i] = $temp; } }} // function to sort the matrix row-wise// and column-wisefunction sortMatRowAndColWise(&$mat, $n){ // sort rows of mat[][] sortByRow($mat, $n, true); // get transpose of mat[][] transpose($mat, $n); // again sort rows of mat[][] in // descending order. sortByRow($mat, $n, false); // again get transpose of mat[][] transpose($mat, $n);} // function to print the matrixfunction printMat(&$mat, $n){ for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) echo $mat[$i][$j] . \" \"; echo \"\\n\" ; }} // Driver Code$n = 3; $mat = array(array(3, 2, 1), array(9, 8, 7), array(6, 5, 4)); echo \"Original Matrix:\\n\";printMat($mat, $n); sortMatRowAndColWise($mat, $n); echo \"\\nMatrix After Sorting:\\n\";printMat($mat, $n); // This code is contributed by Ita_c?>",
"e": 11110,
"s": 9486,
"text": null
},
{
"code": "<script>// Javascript implementation to sort the rows// of matrix in ascending order followed by// sorting the columns in descending order let MAX_SIZE=10; // function to sort each row of the matrix // according to the order specified by // ascending. function sortByRow(mat,n,ascending) { for (let i = 0; i < n; i++) { if (ascending) mat[i].sort(function(a,b){return a-b;}); else mat[i].sort(function(a,b){return b-a;}); } } // function to find transpose of the matrix function transpose(mat,n) { for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) { // swapping element at index (i, j) // by element at index (j, i) let temp = mat[i][j]; mat[i][j] = mat[j][i]; mat[j][i] = temp; } } // function to sort the matrix row-wise // and column-wise function sortMatRowAndColWise(mat,n) { // sort rows of mat[][] sortByRow(mat, n, true); // get transpose of mat[][] transpose(mat, n); // again sort rows of mat[][] in descending // order. sortByRow(mat, n, false); // again get transpose of mat[][] transpose(mat, n); } // function to print the matrix function printMat(mat,n) { for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) document.write(mat[i][j] + \" \"); document.write(\"<br>\"); } } // Driver code let n = 3; let mat = [[3, 2, 1], [9, 8, 7], [6, 5, 4]]; document.write(\"Original Matrix:<br>\"); printMat(mat, n); sortMatRowAndColWise(mat, n); document.write(\"\\nMatrix After Sorting:<br>\"); printMat(mat, n); // This code is contributed by avanitrachhadiya2155</script>",
"e": 13085,
"s": 11110,
"text": null
},
{
"code": null,
"e": 13168,
"s": 13085,
"text": "Original Matrix:\n3 2 1 \n9 8 7 \n6 5 4 \n\nMatrix After Sorting:\n7 8 9 \n4 5 6 \n1 2 3 \n"
},
{
"code": null,
"e": 13218,
"s": 13168,
"text": "Time Complexity: O(N2 log N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 13224,
"s": 13218,
"text": "ukasp"
},
{
"code": null,
"e": 13245,
"s": 13224,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 13256,
"s": 13245,
"text": "singhh3010"
},
{
"code": null,
"e": 13273,
"s": 13256,
"text": "codewithshinchan"
},
{
"code": null,
"e": 13290,
"s": 13273,
"text": "harendrakumar123"
},
{
"code": null,
"e": 13297,
"s": 13290,
"text": "Matrix"
},
{
"code": null,
"e": 13305,
"s": 13297,
"text": "Sorting"
},
{
"code": null,
"e": 13313,
"s": 13305,
"text": "Sorting"
},
{
"code": null,
"e": 13320,
"s": 13313,
"text": "Matrix"
},
{
"code": null,
"e": 13418,
"s": 13320,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13453,
"s": 13418,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 13497,
"s": 13453,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 13528,
"s": 13497,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 13552,
"s": 13528,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 13574,
"s": 13552,
"text": "The Celebrity Problem"
},
{
"code": null,
"e": 13585,
"s": 13574,
"text": "Merge Sort"
},
{
"code": null,
"e": 13607,
"s": 13585,
"text": "Bubble Sort Algorithm"
},
{
"code": null,
"e": 13617,
"s": 13607,
"text": "QuickSort"
},
{
"code": null,
"e": 13632,
"s": 13617,
"text": "Insertion Sort"
}
] |
Moving a file from one directory to another using Java
|
21 Oct, 2021
Java provides functions to move files between directories. Two ways to achieve this are described here. The first method utilizes Files package for moving while the other method first copies the file to destination and then deletes the original copy from the source.
Using Files.Path move() method: Renaming and moving the file permanently to a new location. Syntax:
public static Path move(Path source, Path target, CopyOption..options)
throws IOException
Parameters:
source - the path to the file to move
target - the path to the target file
(may be associated with a different provider to the source path)
options - options specifying how the move should be done
Returns: the path to the target file
Java
// Java program to illustrate renaming and// moving a file permanently to a new locationimport java.io.*;import java.nio.file.Files;import java.nio.file.*; public class Test{ public static void main(String[] args) throws IOException { Path temp = Files.move (Paths.get("C:\\Users\\Mayank\\Desktop\\44.txt"), Paths.get("C:\\Users\\Mayank\\Desktop\\dest\\445.txt")); if(temp != null) { System.out.println("File renamed and moved successfully"); } else { System.out.println("Failed to move the file"); } }}
Output:
File renamed and moved successfully
Using Java.io.File.renameTo() and Java.io.File.delete() methods: Copying the file and deleting the original file using these two methods. Syntax of renameTo():
public boolean renameTo(File dest)
Description: Renames the file denoted by this abstract path name.
Parameters: dest - The new abstract path name for the named file
Returns: true if and only if the renaming succeeded; false otherwise
Syntax of delete():
public boolean delete()
Description: Deletes the file or directory
denoted by this abstract path name.
Returns: true if and only if the file or
directory is successfully deleted; false otherwise
Java
// Java program to illustrate Copying the file// and deleting the original fileimport java.io.*; public class Test{ public static void main(String[] args) { File file = new File("C:\\Users\\Mayank\\Desktop\\1.txt"); // renaming the file and moving it to a new location if(file.renameTo (new File("C:\\Users\\Mayank\\Desktop\\dest\\newFile.txt"))) { // if file copied successfully then delete the original file file.delete(); System.out.println("File moved successfully"); } else { System.out.println("Failed to move the file"); } }}
Output
File moved successfully
References:
Oracle
This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
kashishsoda
Java-Library
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Stack Class in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 323,
"s": 54,
"text": "Java provides functions to move files between directories. Two ways to achieve this are described here. The first method utilizes Files package for moving while the other method first copies the file to destination and then deletes the original copy from the source. "
},
{
"code": null,
"e": 424,
"s": 323,
"text": "Using Files.Path move() method: Renaming and moving the file permanently to a new location. Syntax: "
},
{
"code": null,
"e": 773,
"s": 424,
"text": "public static Path move(Path source, Path target, CopyOption..options)\n throws IOException\nParameters: \nsource - the path to the file to move\ntarget - the path to the target file \n(may be associated with a different provider to the source path)\noptions - options specifying how the move should be done\nReturns: the path to the target file"
},
{
"code": null,
"e": 778,
"s": 773,
"text": "Java"
},
{
"code": "// Java program to illustrate renaming and// moving a file permanently to a new locationimport java.io.*;import java.nio.file.Files;import java.nio.file.*; public class Test{ public static void main(String[] args) throws IOException { Path temp = Files.move (Paths.get(\"C:\\\\Users\\\\Mayank\\\\Desktop\\\\44.txt\"), Paths.get(\"C:\\\\Users\\\\Mayank\\\\Desktop\\\\dest\\\\445.txt\")); if(temp != null) { System.out.println(\"File renamed and moved successfully\"); } else { System.out.println(\"Failed to move the file\"); } }}",
"e": 1377,
"s": 778,
"text": null
},
{
"code": null,
"e": 1386,
"s": 1377,
"text": "Output: "
},
{
"code": null,
"e": 1422,
"s": 1386,
"text": "File renamed and moved successfully"
},
{
"code": null,
"e": 1583,
"s": 1422,
"text": "Using Java.io.File.renameTo() and Java.io.File.delete() methods: Copying the file and deleting the original file using these two methods. Syntax of renameTo(): "
},
{
"code": null,
"e": 1818,
"s": 1583,
"text": "public boolean renameTo(File dest)\nDescription: Renames the file denoted by this abstract path name.\nParameters: dest - The new abstract path name for the named file\nReturns: true if and only if the renaming succeeded; false otherwise"
},
{
"code": null,
"e": 1848,
"s": 1818,
"text": " Syntax of delete(): "
},
{
"code": null,
"e": 2045,
"s": 1848,
"text": "public boolean delete()\nDescription: Deletes the file or directory \ndenoted by this abstract path name.\nReturns: true if and only if the file or \ndirectory is successfully deleted; false otherwise"
},
{
"code": null,
"e": 2050,
"s": 2045,
"text": "Java"
},
{
"code": "// Java program to illustrate Copying the file// and deleting the original fileimport java.io.*; public class Test{ public static void main(String[] args) { File file = new File(\"C:\\\\Users\\\\Mayank\\\\Desktop\\\\1.txt\"); // renaming the file and moving it to a new location if(file.renameTo (new File(\"C:\\\\Users\\\\Mayank\\\\Desktop\\\\dest\\\\newFile.txt\"))) { // if file copied successfully then delete the original file file.delete(); System.out.println(\"File moved successfully\"); } else { System.out.println(\"Failed to move the file\"); } }}",
"e": 2721,
"s": 2050,
"text": null
},
{
"code": null,
"e": 2729,
"s": 2721,
"text": "Output "
},
{
"code": null,
"e": 2753,
"s": 2729,
"text": "File moved successfully"
},
{
"code": null,
"e": 2765,
"s": 2753,
"text": "References:"
},
{
"code": null,
"e": 2773,
"s": 2765,
"text": "Oracle "
},
{
"code": null,
"e": 3073,
"s": 2773,
"text": "This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 3198,
"s": 3073,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3210,
"s": 3198,
"text": "kashishsoda"
},
{
"code": null,
"e": 3223,
"s": 3210,
"text": "Java-Library"
},
{
"code": null,
"e": 3228,
"s": 3223,
"text": "Java"
},
{
"code": null,
"e": 3233,
"s": 3228,
"text": "Java"
},
{
"code": null,
"e": 3331,
"s": 3233,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3382,
"s": 3331,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 3413,
"s": 3382,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 3432,
"s": 3413,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3462,
"s": 3432,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3480,
"s": 3462,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3495,
"s": 3480,
"text": "Stream In Java"
},
{
"code": null,
"e": 3515,
"s": 3495,
"text": "Collections in Java"
},
{
"code": null,
"e": 3539,
"s": 3515,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 3571,
"s": 3539,
"text": "Multidimensional Arrays in Java"
}
] |
Redux and The Flux Architecture
|
31 Oct, 2019
Flux Architecture:Flux is AN architecture that Facebook uses internally when operating with React.It is not a framework or a library.It is merely a replacement quite an architecture that enhances React and also the idea of unidirectional data flow.
Redux is a predictable state container for JavaScript apps. Redux is a state-management tool that is mostly used to React. Now speaking in terms of React, simple applications have some components and the main component which acts as the leader for the state of our application. Any changes made are reflected back to the main component which then modifies the state.But in reality, while creating a web application to solve a real-world problem, we encounter hundreds of components that are organized into multiple groups rather than one group with one main component. So they are organized into multiple groups wherein each group has a main component managing the state of that group.
Now, if you make changes to one of the components then one of the other components may need re-rendering but if they don’t share a common main component then passing of information between them can be difficult.This is where we need an MVC (Model, View, Controller) model for the application.
MVC model: An MVC model basically captures the entire state of the application and any changes you want to make to the model from the view will have to go through the controller to the model.
Need for Flux Architecture:
MVC faced certain issues due to which it couldn’t manage the application the way we wanted it to. That’s where a new approach called Flux architecture originated from the MVC model was designed. This approach was basically designed to organize your code in a simpler web. The problems that with MVC encountered was the fact that the updates, lead to a cascading flow of updates within the models, and this becomes a tangled web, which makes the application really complex.The flux architecture, however, provides a unidirectional flow where a central unit for the entire application is called the store. In Flux architecture, you can have multiple stores. A store basically acts as a storehouse for the application state. So, you can only modify the state of your application by requesting the store.The dispatcher becomes a controlling unit for serializing any actions that are requested for changing the store. The store can be subscribed by views, be it React views or controller views.
The storehouse of the state is the main component that will get its state from the store of the flux architecture. Now whenever a change is made, the controller views go back are able to get the updated state.And this, in turn, might result in re-rendering of some parts of your views or some parts of your components within your application. So, this is what is meant by the unidirectional flow of data which forms the basis for the Flux architecture.
Redux Architecture:
Redux is a predictable state container for JavaScript applications. Redux derives its ideas form the Flux architecture. It is basically a flux-like approach to React applications.Redux doesn’t necessarily have to be used with React only, you can use it for AngularJS or JS too. But Redux works really well with React. Redux basically provides a way for managing the store, unidirectional flow of data and much more.Flux architecture has multiple stores that are coordinated together by the dispatcher and when there is a change all the stores need to update themselves. But in Redux we have a single store. A single store that handles the entire application. Any changes to the store are done through actions.
Now, in Redux we have some functions which are called reducer functions. These functions basically take the previous state of the application and the action specified and generate the next state for the application. In Redux, changes in the state can only be made using these reducer functions. The previous state still remains intact and a new state is generate originated from the previous one.
Use of Redux:
Time-travel debugging: In Redux you can always walk back and check the changes you have made to the states. Easy logging of states.
Undo & Redo: While walking back you can always update/modify the states as required by you.
A Single Source: Redux has only one single store which makes it really simple to understand.
Reducer Functions: These functions generate a new state which is originated from the previous state and hence it helps to link all the states together
Use of JS: In the reducer function along with the previous state, the action is specified. Action comprises of a basic JavaScript Object which is called as a Payload.
immutability: When a new state is generated, the previous state remains as is and is not modified in any way.
Redux gets integrated together with React using a model called react-redux. Now for this integration, we use the react-redux package. But here we will be covering only Redux. So as a first step, you need to install redux into your React application:
npm install redux --save
OR
yarn add redux
Examples:
import { createStore}from 'redux' function count(state = 0, action) { switch (action.type) { case 'INCR': return state + 1 case 'DECR': return state - 1 default: return state }}let sample_store = createStore(count)sample_store.subscribe(() => console.log(sample_store.getState()))sample_store.dispatch({ type: 'INCR' }) //Output:1sample_store.dispatch({ type: 'INCR' }) //Output:2sample_store.dispatch({ type: 'DECR' }) //Output:1
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Oct, 2019"
},
{
"code": null,
"e": 277,
"s": 28,
"text": "Flux Architecture:Flux is AN architecture that Facebook uses internally when operating with React.It is not a framework or a library.It is merely a replacement quite an architecture that enhances React and also the idea of unidirectional data flow."
},
{
"code": null,
"e": 963,
"s": 277,
"text": "Redux is a predictable state container for JavaScript apps. Redux is a state-management tool that is mostly used to React. Now speaking in terms of React, simple applications have some components and the main component which acts as the leader for the state of our application. Any changes made are reflected back to the main component which then modifies the state.But in reality, while creating a web application to solve a real-world problem, we encounter hundreds of components that are organized into multiple groups rather than one group with one main component. So they are organized into multiple groups wherein each group has a main component managing the state of that group."
},
{
"code": null,
"e": 1256,
"s": 963,
"text": "Now, if you make changes to one of the components then one of the other components may need re-rendering but if they don’t share a common main component then passing of information between them can be difficult.This is where we need an MVC (Model, View, Controller) model for the application."
},
{
"code": null,
"e": 1448,
"s": 1256,
"text": "MVC model: An MVC model basically captures the entire state of the application and any changes you want to make to the model from the view will have to go through the controller to the model."
},
{
"code": null,
"e": 1476,
"s": 1448,
"text": "Need for Flux Architecture:"
},
{
"code": null,
"e": 2466,
"s": 1476,
"text": "MVC faced certain issues due to which it couldn’t manage the application the way we wanted it to. That’s where a new approach called Flux architecture originated from the MVC model was designed. This approach was basically designed to organize your code in a simpler web. The problems that with MVC encountered was the fact that the updates, lead to a cascading flow of updates within the models, and this becomes a tangled web, which makes the application really complex.The flux architecture, however, provides a unidirectional flow where a central unit for the entire application is called the store. In Flux architecture, you can have multiple stores. A store basically acts as a storehouse for the application state. So, you can only modify the state of your application by requesting the store.The dispatcher becomes a controlling unit for serializing any actions that are requested for changing the store. The store can be subscribed by views, be it React views or controller views."
},
{
"code": null,
"e": 2919,
"s": 2466,
"text": "The storehouse of the state is the main component that will get its state from the store of the flux architecture. Now whenever a change is made, the controller views go back are able to get the updated state.And this, in turn, might result in re-rendering of some parts of your views or some parts of your components within your application. So, this is what is meant by the unidirectional flow of data which forms the basis for the Flux architecture."
},
{
"code": null,
"e": 2939,
"s": 2919,
"text": "Redux Architecture:"
},
{
"code": null,
"e": 3649,
"s": 2939,
"text": "Redux is a predictable state container for JavaScript applications. Redux derives its ideas form the Flux architecture. It is basically a flux-like approach to React applications.Redux doesn’t necessarily have to be used with React only, you can use it for AngularJS or JS too. But Redux works really well with React. Redux basically provides a way for managing the store, unidirectional flow of data and much more.Flux architecture has multiple stores that are coordinated together by the dispatcher and when there is a change all the stores need to update themselves. But in Redux we have a single store. A single store that handles the entire application. Any changes to the store are done through actions."
},
{
"code": null,
"e": 4046,
"s": 3649,
"text": "Now, in Redux we have some functions which are called reducer functions. These functions basically take the previous state of the application and the action specified and generate the next state for the application. In Redux, changes in the state can only be made using these reducer functions. The previous state still remains intact and a new state is generate originated from the previous one."
},
{
"code": null,
"e": 4060,
"s": 4046,
"text": "Use of Redux:"
},
{
"code": null,
"e": 4192,
"s": 4060,
"text": "Time-travel debugging: In Redux you can always walk back and check the changes you have made to the states. Easy logging of states."
},
{
"code": null,
"e": 4284,
"s": 4192,
"text": "Undo & Redo: While walking back you can always update/modify the states as required by you."
},
{
"code": null,
"e": 4377,
"s": 4284,
"text": "A Single Source: Redux has only one single store which makes it really simple to understand."
},
{
"code": null,
"e": 4528,
"s": 4377,
"text": "Reducer Functions: These functions generate a new state which is originated from the previous state and hence it helps to link all the states together"
},
{
"code": null,
"e": 4695,
"s": 4528,
"text": "Use of JS: In the reducer function along with the previous state, the action is specified. Action comprises of a basic JavaScript Object which is called as a Payload."
},
{
"code": null,
"e": 4805,
"s": 4695,
"text": "immutability: When a new state is generated, the previous state remains as is and is not modified in any way."
},
{
"code": null,
"e": 5055,
"s": 4805,
"text": "Redux gets integrated together with React using a model called react-redux. Now for this integration, we use the react-redux package. But here we will be covering only Redux. So as a first step, you need to install redux into your React application:"
},
{
"code": null,
"e": 5080,
"s": 5055,
"text": "npm install redux --save"
},
{
"code": null,
"e": 5083,
"s": 5080,
"text": "OR"
},
{
"code": null,
"e": 5098,
"s": 5083,
"text": "yarn add redux"
},
{
"code": null,
"e": 5108,
"s": 5098,
"text": "Examples:"
},
{
"code": "import { createStore}from 'redux' function count(state = 0, action) { switch (action.type) { case 'INCR': return state + 1 case 'DECR': return state - 1 default: return state }}let sample_store = createStore(count)sample_store.subscribe(() => console.log(sample_store.getState()))sample_store.dispatch({ type: 'INCR' }) //Output:1sample_store.dispatch({ type: 'INCR' }) //Output:2sample_store.dispatch({ type: 'DECR' }) //Output:1",
"e": 5633,
"s": 5108,
"text": null
},
{
"code": null,
"e": 5642,
"s": 5633,
"text": "react-js"
},
{
"code": null,
"e": 5659,
"s": 5642,
"text": "Web Technologies"
}
] |
How to use Pandas filter with IQR?
|
02 Dec, 2021
The IQR or Inter Quartile Range is a statistical measure used to measure the variability in a given data. In naive terms, it tells us inside what range the bulk of our data lies. It can be calculated by taking the difference between the third quartile and the first quartile within a dataset.
IQR = Q3 - Q1
Where, Q3 = the 75th percentile value (it is the middle value between the median and the largest value inside a dataset). Q1 = the 25th percentile value (it is the middle value between the median and the smallest value inside a dataset). Also, Q2 denotes the 50th percentile i.e., the median of a dataset. For more information about IQR please read https://www.geeksforgeeks.org/interquartile-range-iqr/.
In this article, we will be knowing how to filter a dataset using Pandas with the help of IQR.
The Inter Quartile Range (IQR) is a methodology that is generally used to filter outliers in a dataset. Outliers are extreme values that lie far from the regular observations that can possibly be got generated because of variability in measurement or experimental error. Many a time we want to identify these outliers and filter them out to reduce errors. Here, we will be showing an example to detect outliers and filter them out using Pandas in Python programming language.
Let’s first begin by importing important libraries that we will require to identify and filter the outliers.
Python
# Importing important librariesimport numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltplt.style.use('seaborn')
Now, we will read the dataset in which we want to detect and filter outliers. The dataset can be downloaded from https://tinyurl.com/gfgdata. It can be done using the read_csv() method present in the Pandas library and can be written as:
Python
# Reading the datasetdata = pd.read_csv('Dataset.csv')print("The shape of the dataframe is: ", data.shape)
Output:
The shape of the dataframe is: (20, 4)
Printing the dataset
We can print the dataset to have a look at the data.
Python
print(data)
Our dataset looks like this:
We can observe some statistical information about this dataset using data.describe() method, which can be done as:
Python
data.describe()
Output:
It can be observed that features such as ‘Height’, ‘Width’, ‘Area’ have very deferred maximum value as compared to the 75% value, thus we can say there are certain observations that act as outliers in the dataset. Similarly, the minimum value in these columns differs greatly from the 25% value, so it signifies the presence of outliers.
It can be verified by plotting a box plot of the above features, here I’m plotting the box plot for the Height column and in the same manner box plot for other features can be plotted.
Python
plt.figure(figsize=(6,4))sns.boxplot(data['Height (in cm)'])plt.show()
Output:
We can observe the presence of outliers beyond the first quartile and the third quartile in the box plot.
To find out and filter such outliers in the dataset we will create a custom function that will help us remove outliers. In the function, we first need to find out the IQR value that can be calculated by finding the difference between the third and first quartile values. Secondly, we will write a query to select observations that lie outside the lower_range and upper_range IQR region and remove them. It can be written as:
Python
# Removing the outliersdef removeOutliers(data, col): Q3 = np.quantile(data[col], 0.75) Q1 = np.quantile(data[col], 0.25) IQR = Q3 - Q1 print("IQR value for column %s is: %s" % (col, IQR)) global outlier_free_list global filtered_data lower_range = Q1 - 1.5 * IQR upper_range = Q3 + 1.5 * IQR outlier_free_list = [x for x in data[col] if ( (x > lower_range) & (x < upper_range))] filtered_data = data.loc[data[col].isin(outlier_free_list)] for i in data.columns: if i == data.columns[0]: removeOutliers(data, i) else: removeOutliers(filtered_data, i) # Assigning filtered data back to our original variabledata = filtered_dataprint("Shape of data after outlier removal is: ", data.shape)
Output:
IQR value for column Height (in cm) is: 9.5
IQR value for column Width (in cm) is: 16.75
IQR value for column Area (in cm2) is: 706.0
Shape of data after outlier removal is: (18, 3)
Printing the data afterward we can notice two of our extreme observations which were acting as outliers get removed.
Python
print(data)
Output:
We can observe the rows with index numbers 7 and 15 got removed from the original dataset.
simranarora5sos
frojasr60
Picked
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": "\n02 Dec, 2021"
},
{
"code": null,
"e": 321,
"s": 28,
"text": "The IQR or Inter Quartile Range is a statistical measure used to measure the variability in a given data. In naive terms, it tells us inside what range the bulk of our data lies. It can be calculated by taking the difference between the third quartile and the first quartile within a dataset."
},
{
"code": null,
"e": 335,
"s": 321,
"text": "IQR = Q3 - Q1"
},
{
"code": null,
"e": 740,
"s": 335,
"text": "Where, Q3 = the 75th percentile value (it is the middle value between the median and the largest value inside a dataset). Q1 = the 25th percentile value (it is the middle value between the median and the smallest value inside a dataset). Also, Q2 denotes the 50th percentile i.e., the median of a dataset. For more information about IQR please read https://www.geeksforgeeks.org/interquartile-range-iqr/."
},
{
"code": null,
"e": 835,
"s": 740,
"text": "In this article, we will be knowing how to filter a dataset using Pandas with the help of IQR."
},
{
"code": null,
"e": 1311,
"s": 835,
"text": "The Inter Quartile Range (IQR) is a methodology that is generally used to filter outliers in a dataset. Outliers are extreme values that lie far from the regular observations that can possibly be got generated because of variability in measurement or experimental error. Many a time we want to identify these outliers and filter them out to reduce errors. Here, we will be showing an example to detect outliers and filter them out using Pandas in Python programming language."
},
{
"code": null,
"e": 1420,
"s": 1311,
"text": "Let’s first begin by importing important libraries that we will require to identify and filter the outliers."
},
{
"code": null,
"e": 1427,
"s": 1420,
"text": "Python"
},
{
"code": "# Importing important librariesimport numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltplt.style.use('seaborn')",
"e": 1572,
"s": 1427,
"text": null
},
{
"code": null,
"e": 1811,
"s": 1572,
"text": "Now, we will read the dataset in which we want to detect and filter outliers. The dataset can be downloaded from https://tinyurl.com/gfgdata. It can be done using the read_csv() method present in the Pandas library and can be written as: "
},
{
"code": null,
"e": 1818,
"s": 1811,
"text": "Python"
},
{
"code": "# Reading the datasetdata = pd.read_csv('Dataset.csv')print(\"The shape of the dataframe is: \", data.shape)",
"e": 1925,
"s": 1818,
"text": null
},
{
"code": null,
"e": 1933,
"s": 1925,
"text": "Output:"
},
{
"code": null,
"e": 1974,
"s": 1933,
"text": " The shape of the dataframe is: (20, 4)"
},
{
"code": null,
"e": 1995,
"s": 1974,
"text": "Printing the dataset"
},
{
"code": null,
"e": 2048,
"s": 1995,
"text": "We can print the dataset to have a look at the data."
},
{
"code": null,
"e": 2055,
"s": 2048,
"text": "Python"
},
{
"code": "print(data)",
"e": 2067,
"s": 2055,
"text": null
},
{
"code": null,
"e": 2097,
"s": 2067,
"text": "Our dataset looks like this: "
},
{
"code": null,
"e": 2213,
"s": 2097,
"text": "We can observe some statistical information about this dataset using data.describe() method, which can be done as: "
},
{
"code": null,
"e": 2220,
"s": 2213,
"text": "Python"
},
{
"code": "data.describe()",
"e": 2236,
"s": 2220,
"text": null
},
{
"code": null,
"e": 2244,
"s": 2236,
"text": "Output:"
},
{
"code": null,
"e": 2583,
"s": 2244,
"text": "It can be observed that features such as ‘Height’, ‘Width’, ‘Area’ have very deferred maximum value as compared to the 75% value, thus we can say there are certain observations that act as outliers in the dataset. Similarly, the minimum value in these columns differs greatly from the 25% value, so it signifies the presence of outliers. "
},
{
"code": null,
"e": 2769,
"s": 2583,
"text": "It can be verified by plotting a box plot of the above features, here I’m plotting the box plot for the Height column and in the same manner box plot for other features can be plotted. "
},
{
"code": null,
"e": 2776,
"s": 2769,
"text": "Python"
},
{
"code": "plt.figure(figsize=(6,4))sns.boxplot(data['Height (in cm)'])plt.show()",
"e": 2847,
"s": 2776,
"text": null
},
{
"code": null,
"e": 2855,
"s": 2847,
"text": "Output:"
},
{
"code": null,
"e": 2962,
"s": 2855,
"text": "We can observe the presence of outliers beyond the first quartile and the third quartile in the box plot. "
},
{
"code": null,
"e": 3387,
"s": 2962,
"text": "To find out and filter such outliers in the dataset we will create a custom function that will help us remove outliers. In the function, we first need to find out the IQR value that can be calculated by finding the difference between the third and first quartile values. Secondly, we will write a query to select observations that lie outside the lower_range and upper_range IQR region and remove them. It can be written as:"
},
{
"code": null,
"e": 3394,
"s": 3387,
"text": "Python"
},
{
"code": "# Removing the outliersdef removeOutliers(data, col): Q3 = np.quantile(data[col], 0.75) Q1 = np.quantile(data[col], 0.25) IQR = Q3 - Q1 print(\"IQR value for column %s is: %s\" % (col, IQR)) global outlier_free_list global filtered_data lower_range = Q1 - 1.5 * IQR upper_range = Q3 + 1.5 * IQR outlier_free_list = [x for x in data[col] if ( (x > lower_range) & (x < upper_range))] filtered_data = data.loc[data[col].isin(outlier_free_list)] for i in data.columns: if i == data.columns[0]: removeOutliers(data, i) else: removeOutliers(filtered_data, i) # Assigning filtered data back to our original variabledata = filtered_dataprint(\"Shape of data after outlier removal is: \", data.shape)",
"e": 4142,
"s": 3394,
"text": null
},
{
"code": null,
"e": 4150,
"s": 4142,
"text": "Output:"
},
{
"code": null,
"e": 4333,
"s": 4150,
"text": "IQR value for column Height (in cm) is: 9.5\nIQR value for column Width (in cm) is: 16.75\nIQR value for column Area (in cm2) is: 706.0\nShape of data after outlier removal is: (18, 3)"
},
{
"code": null,
"e": 4450,
"s": 4333,
"text": "Printing the data afterward we can notice two of our extreme observations which were acting as outliers get removed."
},
{
"code": null,
"e": 4457,
"s": 4450,
"text": "Python"
},
{
"code": "print(data)",
"e": 4469,
"s": 4457,
"text": null
},
{
"code": null,
"e": 4477,
"s": 4469,
"text": "Output:"
},
{
"code": null,
"e": 4568,
"s": 4477,
"text": "We can observe the rows with index numbers 7 and 15 got removed from the original dataset."
},
{
"code": null,
"e": 4584,
"s": 4568,
"text": "simranarora5sos"
},
{
"code": null,
"e": 4594,
"s": 4584,
"text": "frojasr60"
},
{
"code": null,
"e": 4601,
"s": 4594,
"text": "Picked"
},
{
"code": null,
"e": 4615,
"s": 4601,
"text": "Python-pandas"
},
{
"code": null,
"e": 4622,
"s": 4615,
"text": "Python"
}
] |
How to read multiple text files from folder in Python?
|
02 Feb, 2021
Prerequisite:
File Handling
os
Python is a strong language which is extremely capable even when it comes to file handling. In this article, we will learn how to read multiple text files from a folder using python.
Approach:
Import modules
Add path of the folder
Change directory
Get the list of a file from a folder
Iterate through the file list and check whether the extension of the file is in .txt format or not.
If text-file exist, read the file using File Handling
Functions used:
os.chdir() method in Python used to change the current working directory to specified path. It takes only a single argument as new directory path.
Syntax: os.chdir(path)
Parameters:
path: A complete path of directory to be changed to new directory path.
Returns: Doesn’t return any value
os.listdir() method in python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then list of files and directories in the current working directory will be returned.
Syntax: os.listdir(path)
Parameters:
path (optional) : path of the directory
Return Type: This method returns the list of all files and directories in the specified path. The return type of this method is list.
Below is the Implementation:
Program:
Python3
# Import Moduleimport os # Folder Pathpath = "Enter Folder Path" # Change the directoryos.chdir(path) # Read text File def read_text_file(file_path): with open(file_path, 'r') as f: print(f.read()) # iterate through all filefor file in os.listdir(): # Check whether file is in text format or not if file.endswith(".txt"): file_path = f"{path}\{file}" # call read text file function read_text_file(file_path)
Output:
Picked
Python file-handling-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Feb, 2021"
},
{
"code": null,
"e": 68,
"s": 54,
"text": "Prerequisite:"
},
{
"code": null,
"e": 82,
"s": 68,
"text": "File Handling"
},
{
"code": null,
"e": 85,
"s": 82,
"text": "os"
},
{
"code": null,
"e": 268,
"s": 85,
"text": "Python is a strong language which is extremely capable even when it comes to file handling. In this article, we will learn how to read multiple text files from a folder using python."
},
{
"code": null,
"e": 278,
"s": 268,
"text": "Approach:"
},
{
"code": null,
"e": 293,
"s": 278,
"text": "Import modules"
},
{
"code": null,
"e": 316,
"s": 293,
"text": "Add path of the folder"
},
{
"code": null,
"e": 333,
"s": 316,
"text": "Change directory"
},
{
"code": null,
"e": 370,
"s": 333,
"text": "Get the list of a file from a folder"
},
{
"code": null,
"e": 470,
"s": 370,
"text": "Iterate through the file list and check whether the extension of the file is in .txt format or not."
},
{
"code": null,
"e": 524,
"s": 470,
"text": "If text-file exist, read the file using File Handling"
},
{
"code": null,
"e": 540,
"s": 524,
"text": "Functions used:"
},
{
"code": null,
"e": 687,
"s": 540,
"text": "os.chdir() method in Python used to change the current working directory to specified path. It takes only a single argument as new directory path."
},
{
"code": null,
"e": 710,
"s": 687,
"text": "Syntax: os.chdir(path)"
},
{
"code": null,
"e": 722,
"s": 710,
"text": "Parameters:"
},
{
"code": null,
"e": 794,
"s": 722,
"text": "path: A complete path of directory to be changed to new directory path."
},
{
"code": null,
"e": 828,
"s": 794,
"text": "Returns: Doesn’t return any value"
},
{
"code": null,
"e": 1060,
"s": 828,
"text": "os.listdir() method in python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then list of files and directories in the current working directory will be returned."
},
{
"code": null,
"e": 1085,
"s": 1060,
"text": "Syntax: os.listdir(path)"
},
{
"code": null,
"e": 1097,
"s": 1085,
"text": "Parameters:"
},
{
"code": null,
"e": 1137,
"s": 1097,
"text": "path (optional) : path of the directory"
},
{
"code": null,
"e": 1271,
"s": 1137,
"text": "Return Type: This method returns the list of all files and directories in the specified path. The return type of this method is list."
},
{
"code": null,
"e": 1300,
"s": 1271,
"text": "Below is the Implementation:"
},
{
"code": null,
"e": 1309,
"s": 1300,
"text": "Program:"
},
{
"code": null,
"e": 1317,
"s": 1309,
"text": "Python3"
},
{
"code": "# Import Moduleimport os # Folder Pathpath = \"Enter Folder Path\" # Change the directoryos.chdir(path) # Read text File def read_text_file(file_path): with open(file_path, 'r') as f: print(f.read()) # iterate through all filefor file in os.listdir(): # Check whether file is in text format or not if file.endswith(\".txt\"): file_path = f\"{path}\\{file}\" # call read text file function read_text_file(file_path)",
"e": 1773,
"s": 1317,
"text": null
},
{
"code": null,
"e": 1781,
"s": 1773,
"text": "Output:"
},
{
"code": null,
"e": 1788,
"s": 1781,
"text": "Picked"
},
{
"code": null,
"e": 1818,
"s": 1788,
"text": "Python file-handling-programs"
},
{
"code": null,
"e": 1825,
"s": 1818,
"text": "Python"
}
] |
Program to sort an array of strings using Selection Sort
|
08 Jun, 2022
Given an array of strings, sort the array using Selection Sort.
Examples:
Input : paper true soap floppy flower
Output : floppy, flower, paper, soap, true
Prerequisite : Selection Sort.
C++
C
Java
Python3
C#
Javascript
// C++ program to implement selection sort for// array of strings.#include <bits/stdc++.h>#include <string.h>using namespace std;#define MAX_LEN 100 // Sorts an array of strings where length of every// string should be smaller than MAX_LENvoid selectionSort(char arr[][MAX_LEN], int n){ int i, j, min_idx; // One by one move boundary of unsorted subarray char minStr[MAX_LEN]; for (i = 0; i < n-1; i++) { // Find the minimum element in unsorted array int min_idx = i; strcpy(minStr, arr[i]); for (j = i + 1; j < n; j++) { // If min is greater than arr[j] if (strcmp(minStr, arr[j]) > 0) { // Make arr[j] as minStr and update min_idx strcpy(minStr, arr[j]); min_idx = j; } } // Swap the found minimum element with the first element if (min_idx != i) { char temp[MAX_LEN]; strcpy(temp, arr[i]); //swap item[pos] and item[i] strcpy(arr[i], arr[min_idx]); strcpy(arr[min_idx], temp); } }} // Driver codeint main(){ char arr[][MAX_LEN] = {"GeeksforGeeks", "Practice.GeeksforGeeks", "GeeksQuiz"}; int n = sizeof(arr)/sizeof(arr[0]); int i; cout<<"Given array is\n"; for (i = 0; i < n; i++) cout << i << ": " << arr[i] << endl; selectionSort(arr, n); cout << "\nSorted array is\n"; for (i = 0; i < n; i++) cout << i << ": " << arr[i] << endl; return 0;} // This is code is contributed by rathbhupendra
// C program to implement selection sort for// array of strings.#include <stdio.h>#include <string.h>#define MAX_LEN 100 // Sorts an array of strings where length of every// string should be smaller than MAX_LENvoid selectionSort(char arr[][MAX_LEN], int n){ int i, j, min_idx; // One by one move boundary of unsorted subarray char minStr[MAX_LEN]; for (i = 0; i < n-1; i++) { // Find the minimum element in unsorted array int min_idx = i; strcpy(minStr, arr[i]); for (j = i+1; j < n; j++) { // If min is greater than arr[j] if (strcmp(minStr, arr[j]) > 0) { // Make arr[j] as minStr and update min_idx strcpy(minStr, arr[j]); min_idx = j; } } // Swap the found minimum element with the first element if (min_idx != i) { char temp[MAX_LEN]; strcpy(temp, arr[i]); //swap item[pos] and item[i] strcpy(arr[i], arr[min_idx]); strcpy(arr[min_idx], temp); } }} // Driver codeint main(){ char arr[][MAX_LEN] = {"GeeksforGeeks", "Practice.GeeksforGeeks", "GeeksQuiz"}; int n = sizeof(arr)/sizeof(arr[0]); int i; printf("Given array is\n"); for (i = 0; i < n; i++) printf("%d: %s \n", i, arr[i]); selectionSort(arr, n); printf("\nSorted array is\n"); for (i = 0; i < n; i++) printf("%d: %s \n", i, arr[i]); return 0;}
// Java program to implement selection sort// on array of stringsimport java.util.*;import java.io.*; class Main{ // Sorts an array of stringsstatic void selectionSort(String arr[],int n){ // One by one move boundary of unsorted subarray for(int i = 0; i < n - 1; i++) { // Find the minimum element in unsorted array int min_index = i; String minStr = arr[i]; for(int j = i + 1; j < n; j++) { /*compareTo() will return a -ve value, if string1 (arr[j]) is smaller than string2 (minStr)*/ // If arr[j] is smaller than minStr if(arr[j].compareTo(minStr) < 0) { // Make arr[j] as minStr and update min_idx minStr = arr[j]; min_index = j; } } // Swapping the minimum element // found with the first element. if(min_index != i) { String temp = arr[min_index]; arr[min_index] = arr[i]; arr[i] = temp; } }} // Driver codepublic static void main(String args[]){ String arr[] = {"GeeksforGeeks", "Practice.GeeksforGeeks", "GeeksQuiz"}; int n = arr.length; System.out.println("Given array is"); // Printing the array before sorting for(int i = 0; i < n; i++) { System.out.println(i+": "+arr[i]); } System.out.println(); selectionSort(arr, n); System.out.println("Sorted array is"); // Printing the array after sorting for(int i = 0; i < n; i++) { System.out.println(i+": "+arr[i]); }}} /*This code is contributed by rajesh999*/
# Python program to implement Selection Sort for# array of strings # Function defined for sorting the array of stringsdef Selection(arr,n): # One by one move boundary of unsorted subarray for i in range(n): min_index = i min_str = arr[i] # Find the minimum element in unsorted subarray for j in range(i+1,n): # If min_str is greater than arr[j] if min_str>arr[j]: # Make arr[j] as min_str and update min_index as j min_str = arr[j] min_index = j # Swap the found minimum element with the first element if min_index != i: # Store the first element in temp temp = arr[i] # Place the min element at the first position arr[i] = arr[min_index] # place the element in temp at min_index arr[min_index] = temp # Return the sorted array return arr arr = ["GeeksforGeeks", "Practice.GeeksforGeeks", "GeeksQuiz"] print("Given array is")for i in range(len(arr)): print(i,":",arr[i]) print("\nSorted array is")for i in range(len(Selection(arr,len(arr)))): print(i,":",Selection(arr,len(arr))[i]) # This code is contributed by Manish KC# profile: mkumarchaudhary06
// C# program to implement selection sort// on array of stringsusing System; class GFG{ // Sorts an array of stringsstatic void selectionSort(string[] arr, int n){ // One by one move boundary of // unsorted subarray for(int i = 0; i < n - 1; i++) { // Find the minimum element in // unsorted array int min_index = i; string minStr = arr[i]; for(int j = i + 1; j < n; j++) { /*compareTo() will return a -ve value, if string1 (arr[j]) is smaller than string2 (minStr)*/ // If arr[j] is smaller than minStr if (arr[j].CompareTo(minStr) != 0) { // Make arr[j] as minStr and // update min_idx minStr = arr[j]; min_index = j; } } // Swapping the minimum element // found with the first element. if (min_index != i) { string temp = arr[min_index]; arr[min_index] = arr[i]; arr[i] = temp; } }} // Driver Codestatic void Main(){ string[] arr = { "GeeksforGeeks", "Practice.GeeksforGeeks", "GeeksQuiz" }; int n = arr.Length; Console.WriteLine("Given array is"); // Printing the array before sorting for(int i = 0; i < n; i++) { Console.WriteLine(i + ": " + arr[i]); } Console.WriteLine(); selectionSort(arr, n); Console.WriteLine("Sorted array is"); // Printing the array after sorting for(int i = 0; i < n; i++) { Console.WriteLine(i + ": " + arr[i]); }}} // This code is contributed by divyesh072019
<script> // Javascript program to implement selection sort on array of strings // Sorts an array of strings function selectionSort(arr, n) { // One by one move boundary of // unsorted subarray for(let i = 0; i < n - 1; i++) { // Find the minimum element in // unsorted array let min_index = i; let minStr = arr[i]; for(let j = i + 1; j < n; j++) { /*compareTo() will return a -ve value, if string1 (arr[j]) is smaller than string2 (minStr)*/ // If arr[j] is smaller than minStr if ((arr[j]).localeCompare(minStr) === -1) { // Make arr[j] as minStr and // update min_idx minStr = arr[j]; min_index = j; } } // Swapping the minimum element // found with the first element. if (min_index != i) { let temp = arr[min_index]; arr[min_index] = arr[i]; arr[i] = temp; } } } let arr = [ "GeeksforGeeks", "Practice.GeeksforGeeks", "GeeksQuiz" ]; let n = arr.length; document.write("Given array is" + "</br>"); // Printing the array before sorting for(let i = 0; i < n; i++) { document.write(i + ": " + arr[i] + "</br>"); } document.write("</br>"); selectionSort(arr, n); document.write("Sorted array is" + "</br>"); // Printing the array after sorting for(let i = 0; i < n; i++) { document.write(i + ": " + arr[i] + "</br>"); } // This code is contributed by vaibhavrabadiya117.</script>
Given array is
0: GeeksforGeeks
1: Practice.GeeksforGeeks
2: GeeksQuiz
Sorted array is
0: GeeksQuiz
1: GeeksforGeeks
2: Practice.GeeksforGeeks
Time Complexity: O(n2), where n represents the size of the character array.Auxiliary Space: O(100), no extra space is required, so it is a constant.
This article is contributed by Nikhil Rawat. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
rathbhupendra
mkumarchaudhary06
rajesh999
divyesh072019
vaibhavrabadiya117
sourabhbgp1994
tamanna17122007
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Longest Common Prefix using Sorting
Sort a nearly sorted (or K sorted) array
Segregate 0s and 1s in an array
Sorting in Java
Find whether an array is subset of another array
Quick Sort vs Merge Sort
Quickselect Algorithm
Stability in sorting algorithms
Find all triplets with zero sum
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jun, 2022"
},
{
"code": null,
"e": 116,
"s": 52,
"text": "Given an array of strings, sort the array using Selection Sort."
},
{
"code": null,
"e": 127,
"s": 116,
"text": "Examples: "
},
{
"code": null,
"e": 209,
"s": 127,
"text": "Input : paper true soap floppy flower\nOutput : floppy, flower, paper, soap, true"
},
{
"code": null,
"e": 241,
"s": 209,
"text": "Prerequisite : Selection Sort. "
},
{
"code": null,
"e": 245,
"s": 241,
"text": "C++"
},
{
"code": null,
"e": 247,
"s": 245,
"text": "C"
},
{
"code": null,
"e": 252,
"s": 247,
"text": "Java"
},
{
"code": null,
"e": 260,
"s": 252,
"text": "Python3"
},
{
"code": null,
"e": 263,
"s": 260,
"text": "C#"
},
{
"code": null,
"e": 274,
"s": 263,
"text": "Javascript"
},
{
"code": "// C++ program to implement selection sort for// array of strings.#include <bits/stdc++.h>#include <string.h>using namespace std;#define MAX_LEN 100 // Sorts an array of strings where length of every// string should be smaller than MAX_LENvoid selectionSort(char arr[][MAX_LEN], int n){ int i, j, min_idx; // One by one move boundary of unsorted subarray char minStr[MAX_LEN]; for (i = 0; i < n-1; i++) { // Find the minimum element in unsorted array int min_idx = i; strcpy(minStr, arr[i]); for (j = i + 1; j < n; j++) { // If min is greater than arr[j] if (strcmp(minStr, arr[j]) > 0) { // Make arr[j] as minStr and update min_idx strcpy(minStr, arr[j]); min_idx = j; } } // Swap the found minimum element with the first element if (min_idx != i) { char temp[MAX_LEN]; strcpy(temp, arr[i]); //swap item[pos] and item[i] strcpy(arr[i], arr[min_idx]); strcpy(arr[min_idx], temp); } }} // Driver codeint main(){ char arr[][MAX_LEN] = {\"GeeksforGeeks\", \"Practice.GeeksforGeeks\", \"GeeksQuiz\"}; int n = sizeof(arr)/sizeof(arr[0]); int i; cout<<\"Given array is\\n\"; for (i = 0; i < n; i++) cout << i << \": \" << arr[i] << endl; selectionSort(arr, n); cout << \"\\nSorted array is\\n\"; for (i = 0; i < n; i++) cout << i << \": \" << arr[i] << endl; return 0;} // This is code is contributed by rathbhupendra",
"e": 1888,
"s": 274,
"text": null
},
{
"code": "// C program to implement selection sort for// array of strings.#include <stdio.h>#include <string.h>#define MAX_LEN 100 // Sorts an array of strings where length of every// string should be smaller than MAX_LENvoid selectionSort(char arr[][MAX_LEN], int n){ int i, j, min_idx; // One by one move boundary of unsorted subarray char minStr[MAX_LEN]; for (i = 0; i < n-1; i++) { // Find the minimum element in unsorted array int min_idx = i; strcpy(minStr, arr[i]); for (j = i+1; j < n; j++) { // If min is greater than arr[j] if (strcmp(minStr, arr[j]) > 0) { // Make arr[j] as minStr and update min_idx strcpy(minStr, arr[j]); min_idx = j; } } // Swap the found minimum element with the first element if (min_idx != i) { char temp[MAX_LEN]; strcpy(temp, arr[i]); //swap item[pos] and item[i] strcpy(arr[i], arr[min_idx]); strcpy(arr[min_idx], temp); } }} // Driver codeint main(){ char arr[][MAX_LEN] = {\"GeeksforGeeks\", \"Practice.GeeksforGeeks\", \"GeeksQuiz\"}; int n = sizeof(arr)/sizeof(arr[0]); int i; printf(\"Given array is\\n\"); for (i = 0; i < n; i++) printf(\"%d: %s \\n\", i, arr[i]); selectionSort(arr, n); printf(\"\\nSorted array is\\n\"); for (i = 0; i < n; i++) printf(\"%d: %s \\n\", i, arr[i]); return 0;}",
"e": 3424,
"s": 1888,
"text": null
},
{
"code": "// Java program to implement selection sort// on array of stringsimport java.util.*;import java.io.*; class Main{ // Sorts an array of stringsstatic void selectionSort(String arr[],int n){ // One by one move boundary of unsorted subarray for(int i = 0; i < n - 1; i++) { // Find the minimum element in unsorted array int min_index = i; String minStr = arr[i]; for(int j = i + 1; j < n; j++) { /*compareTo() will return a -ve value, if string1 (arr[j]) is smaller than string2 (minStr)*/ // If arr[j] is smaller than minStr if(arr[j].compareTo(minStr) < 0) { // Make arr[j] as minStr and update min_idx minStr = arr[j]; min_index = j; } } // Swapping the minimum element // found with the first element. if(min_index != i) { String temp = arr[min_index]; arr[min_index] = arr[i]; arr[i] = temp; } }} // Driver codepublic static void main(String args[]){ String arr[] = {\"GeeksforGeeks\", \"Practice.GeeksforGeeks\", \"GeeksQuiz\"}; int n = arr.length; System.out.println(\"Given array is\"); // Printing the array before sorting for(int i = 0; i < n; i++) { System.out.println(i+\": \"+arr[i]); } System.out.println(); selectionSort(arr, n); System.out.println(\"Sorted array is\"); // Printing the array after sorting for(int i = 0; i < n; i++) { System.out.println(i+\": \"+arr[i]); }}} /*This code is contributed by rajesh999*/",
"e": 5089,
"s": 3424,
"text": null
},
{
"code": "# Python program to implement Selection Sort for# array of strings # Function defined for sorting the array of stringsdef Selection(arr,n): # One by one move boundary of unsorted subarray for i in range(n): min_index = i min_str = arr[i] # Find the minimum element in unsorted subarray for j in range(i+1,n): # If min_str is greater than arr[j] if min_str>arr[j]: # Make arr[j] as min_str and update min_index as j min_str = arr[j] min_index = j # Swap the found minimum element with the first element if min_index != i: # Store the first element in temp temp = arr[i] # Place the min element at the first position arr[i] = arr[min_index] # place the element in temp at min_index arr[min_index] = temp # Return the sorted array return arr arr = [\"GeeksforGeeks\", \"Practice.GeeksforGeeks\", \"GeeksQuiz\"] print(\"Given array is\")for i in range(len(arr)): print(i,\":\",arr[i]) print(\"\\nSorted array is\")for i in range(len(Selection(arr,len(arr)))): print(i,\":\",Selection(arr,len(arr))[i]) # This code is contributed by Manish KC# profile: mkumarchaudhary06",
"e": 6456,
"s": 5089,
"text": null
},
{
"code": "// C# program to implement selection sort// on array of stringsusing System; class GFG{ // Sorts an array of stringsstatic void selectionSort(string[] arr, int n){ // One by one move boundary of // unsorted subarray for(int i = 0; i < n - 1; i++) { // Find the minimum element in // unsorted array int min_index = i; string minStr = arr[i]; for(int j = i + 1; j < n; j++) { /*compareTo() will return a -ve value, if string1 (arr[j]) is smaller than string2 (minStr)*/ // If arr[j] is smaller than minStr if (arr[j].CompareTo(minStr) != 0) { // Make arr[j] as minStr and // update min_idx minStr = arr[j]; min_index = j; } } // Swapping the minimum element // found with the first element. if (min_index != i) { string temp = arr[min_index]; arr[min_index] = arr[i]; arr[i] = temp; } }} // Driver Codestatic void Main(){ string[] arr = { \"GeeksforGeeks\", \"Practice.GeeksforGeeks\", \"GeeksQuiz\" }; int n = arr.Length; Console.WriteLine(\"Given array is\"); // Printing the array before sorting for(int i = 0; i < n; i++) { Console.WriteLine(i + \": \" + arr[i]); } Console.WriteLine(); selectionSort(arr, n); Console.WriteLine(\"Sorted array is\"); // Printing the array after sorting for(int i = 0; i < n; i++) { Console.WriteLine(i + \": \" + arr[i]); }}} // This code is contributed by divyesh072019",
"e": 8224,
"s": 6456,
"text": null
},
{
"code": "<script> // Javascript program to implement selection sort on array of strings // Sorts an array of strings function selectionSort(arr, n) { // One by one move boundary of // unsorted subarray for(let i = 0; i < n - 1; i++) { // Find the minimum element in // unsorted array let min_index = i; let minStr = arr[i]; for(let j = i + 1; j < n; j++) { /*compareTo() will return a -ve value, if string1 (arr[j]) is smaller than string2 (minStr)*/ // If arr[j] is smaller than minStr if ((arr[j]).localeCompare(minStr) === -1) { // Make arr[j] as minStr and // update min_idx minStr = arr[j]; min_index = j; } } // Swapping the minimum element // found with the first element. if (min_index != i) { let temp = arr[min_index]; arr[min_index] = arr[i]; arr[i] = temp; } } } let arr = [ \"GeeksforGeeks\", \"Practice.GeeksforGeeks\", \"GeeksQuiz\" ]; let n = arr.length; document.write(\"Given array is\" + \"</br>\"); // Printing the array before sorting for(let i = 0; i < n; i++) { document.write(i + \": \" + arr[i] + \"</br>\"); } document.write(\"</br>\"); selectionSort(arr, n); document.write(\"Sorted array is\" + \"</br>\"); // Printing the array after sorting for(let i = 0; i < n; i++) { document.write(i + \": \" + arr[i] + \"</br>\"); } // This code is contributed by vaibhavrabadiya117.</script>",
"e": 10058,
"s": 8224,
"text": null
},
{
"code": null,
"e": 10202,
"s": 10058,
"text": "Given array is\n0: GeeksforGeeks\n1: Practice.GeeksforGeeks\n2: GeeksQuiz\n\nSorted array is\n0: GeeksQuiz\n1: GeeksforGeeks\n2: Practice.GeeksforGeeks"
},
{
"code": null,
"e": 10351,
"s": 10202,
"text": "Time Complexity: O(n2), where n represents the size of the character array.Auxiliary Space: O(100), no extra space is required, so it is a constant."
},
{
"code": null,
"e": 10647,
"s": 10351,
"text": "This article is contributed by Nikhil Rawat. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 10774,
"s": 10649,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 10790,
"s": 10776,
"text": "rathbhupendra"
},
{
"code": null,
"e": 10808,
"s": 10790,
"text": "mkumarchaudhary06"
},
{
"code": null,
"e": 10818,
"s": 10808,
"text": "rajesh999"
},
{
"code": null,
"e": 10832,
"s": 10818,
"text": "divyesh072019"
},
{
"code": null,
"e": 10851,
"s": 10832,
"text": "vaibhavrabadiya117"
},
{
"code": null,
"e": 10866,
"s": 10851,
"text": "sourabhbgp1994"
},
{
"code": null,
"e": 10882,
"s": 10866,
"text": "tamanna17122007"
},
{
"code": null,
"e": 10890,
"s": 10882,
"text": "Sorting"
},
{
"code": null,
"e": 10898,
"s": 10890,
"text": "Sorting"
},
{
"code": null,
"e": 10996,
"s": 10898,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11027,
"s": 10996,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 11063,
"s": 11027,
"text": "Longest Common Prefix using Sorting"
},
{
"code": null,
"e": 11104,
"s": 11063,
"text": "Sort a nearly sorted (or K sorted) array"
},
{
"code": null,
"e": 11136,
"s": 11104,
"text": "Segregate 0s and 1s in an array"
},
{
"code": null,
"e": 11152,
"s": 11136,
"text": "Sorting in Java"
},
{
"code": null,
"e": 11201,
"s": 11152,
"text": "Find whether an array is subset of another array"
},
{
"code": null,
"e": 11226,
"s": 11201,
"text": "Quick Sort vs Merge Sort"
},
{
"code": null,
"e": 11248,
"s": 11226,
"text": "Quickselect Algorithm"
},
{
"code": null,
"e": 11280,
"s": 11248,
"text": "Stability in sorting algorithms"
}
] |
OAuth2 Authentication with Spring and Github
|
29 Dec, 2020
Open Authorization or OAuth is an industry level protocol used for authorization. It allows third-party services to exchange your information without the user having to give his password. This is possible as it uses authorization tokens to prove an identity between consumers and service providers. OAuth2 is an upgrade over OAuth and it inculcates more security in itself. But before moving any forward let’s understand the working and use of OAuth in detail.
Example –
Suppose we have a service ‘A’ and ‘B’. A user U is using both the services ‘A’ and ‘B’ and hence it can communicate with both the services. Now if service ‘A’ wants to access the contents of service ‘B’, then we need a third party meddler to authenticate that service ‘A’ is safe and can access service ‘B’. This meddling is then done by the user itself.
Talking from a developer aspect, suppose we are building an application X. We already know that a user uses a safe and secure platform like Facebook, Instagram, Github, etc. As such, instead of building our own sign in and login services, we can use the services of Facebook to make the user login into our application.
When our application prompts the Facebook server, the server returns a key that is used by us to verify the authenticity of the user, each time when he/she tries to log in to our platform. The whole idea of OAuth is basically based on the fact that the third-party application is safe and secure, and we trust our services on them.
How to Use OAuth2 in project :
Now Spring as a framework provides the feature of OAuth to the developer via its various Maven and Gradle dependencies. To use the OAuth2 in your project, follow the steps below:-
Create a new project(Spring Starter) with spring web, spring-security dependency, and oauth2 auto-configure dependency.Head to the default class. Add the annotation @EnableOAuth2Sso. This allows us to Enable Oauth in our application.Now, when an Oauth call is made, we need to tell the Client(which is a service and here Github) to look somewhere in order to know what applications can be used to make the OAuth calls. As such, we configure our “application. Properties” file to “applications.yml”.We also need various permissions from applications in order to use their security in our app. Here as we use Github, head to this page.Select “New OAuth App” and then the “Register a new OAuth application” page is presented. Enter an app name and description. Then, enter your app’s home page, which should be http://localhost:8080, in this case. Finally, indicate the Authorization callback URL which is basically the URL of the path, the user should land on after authenticated with GitHub.Now, the app which we have created will give us Client ID and Client secret. Copy these fields.Now, come back to your Spring application and open applications.yml. This file needs to be modified as below. Copy the data in yml file and it’s ready to go.
Create a new project(Spring Starter) with spring web, spring-security dependency, and oauth2 auto-configure dependency.
Head to the default class. Add the annotation @EnableOAuth2Sso. This allows us to Enable Oauth in our application.
Now, when an Oauth call is made, we need to tell the Client(which is a service and here Github) to look somewhere in order to know what applications can be used to make the OAuth calls. As such, we configure our “application. Properties” file to “applications.yml”.
We also need various permissions from applications in order to use their security in our app. Here as we use Github, head to this page.
Select “New OAuth App” and then the “Register a new OAuth application” page is presented. Enter an app name and description. Then, enter your app’s home page, which should be http://localhost:8080, in this case. Finally, indicate the Authorization callback URL which is basically the URL of the path, the user should land on after authenticated with GitHub.
Now, the app which we have created will give us Client ID and Client secret. Copy these fields.
Now, come back to your Spring application and open applications.yml. This file needs to be modified as below. Copy the data in yml file and it’s ready to go.
Let’s see the given below applications.yml as follows.
Security:
oauth2:
client:
clientId: your-id
clientSecret: your-secret
accessTokenUri: https://github.com/login/oauth/access_token
userAuthorizationUri: https://github.com/login/oauth/authorize
clientAuthenticationScheme: form
resource:
user-info-uri: https://api.github.com/user
prefer-token-info: false
Descriptions of applications.yml file :
All the information issued above is used by the Github authorization to identify the details. We can turn “prefer-token-info” to true if we wish to use it for any further purpose.
ClienAuthenticationScheme is set to form here as in this very example, as Github will be using a form to enter all user details. Moreover, all the above details are for Github’s internal use, and we don’t need to worry about the same.
Note — Since the applications file is yml file hence the code has to be structured as above.
Also, when we run our above application on localhost, we’ll be displaying some text to see if our OAuth is working or not, so we build a simple API and add:-
Java
@SpringBootApplication@EnableOAuth2Sso@RestController // Main class name DemoApplicationpublic class DemoApplication { // API @GetMapping("/") public String message(Principal principal) { return "hi "+principal.getName(); } public static void main(String[] args) { // DemoApplication is the default class. SpringApplication.run(DemoApplication.class, args); } }
Program Descriptions :
The DemoApplication is the default class.
The principal Object will take in the user details and display “hi” username when the Github auth is successfully passed.
Now run your Spring application and open localhost 8080 and see the GitHub auth work yourself!.
Java-Spring
Technical Scripter 2020
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 515,
"s": 54,
"text": "Open Authorization or OAuth is an industry level protocol used for authorization. It allows third-party services to exchange your information without the user having to give his password. This is possible as it uses authorization tokens to prove an identity between consumers and service providers. OAuth2 is an upgrade over OAuth and it inculcates more security in itself. But before moving any forward let’s understand the working and use of OAuth in detail."
},
{
"code": null,
"e": 525,
"s": 515,
"text": "Example –"
},
{
"code": null,
"e": 880,
"s": 525,
"text": "Suppose we have a service ‘A’ and ‘B’. A user U is using both the services ‘A’ and ‘B’ and hence it can communicate with both the services. Now if service ‘A’ wants to access the contents of service ‘B’, then we need a third party meddler to authenticate that service ‘A’ is safe and can access service ‘B’. This meddling is then done by the user itself."
},
{
"code": null,
"e": 1202,
"s": 880,
"text": "Talking from a developer aspect, suppose we are building an application X. We already know that a user uses a safe and secure platform like Facebook, Instagram, Github, etc. As such, instead of building our own sign in and login services, we can use the services of Facebook to make the user login into our application. "
},
{
"code": null,
"e": 1535,
"s": 1202,
"text": "When our application prompts the Facebook server, the server returns a key that is used by us to verify the authenticity of the user, each time when he/she tries to log in to our platform. The whole idea of OAuth is basically based on the fact that the third-party application is safe and secure, and we trust our services on them. "
},
{
"code": null,
"e": 1566,
"s": 1535,
"text": "How to Use OAuth2 in project :"
},
{
"code": null,
"e": 1747,
"s": 1566,
"text": "Now Spring as a framework provides the feature of OAuth to the developer via its various Maven and Gradle dependencies. To use the OAuth2 in your project, follow the steps below:- "
},
{
"code": null,
"e": 2990,
"s": 1747,
"text": "Create a new project(Spring Starter) with spring web, spring-security dependency, and oauth2 auto-configure dependency.Head to the default class. Add the annotation @EnableOAuth2Sso. This allows us to Enable Oauth in our application.Now, when an Oauth call is made, we need to tell the Client(which is a service and here Github) to look somewhere in order to know what applications can be used to make the OAuth calls. As such, we configure our “application. Properties” file to “applications.yml”.We also need various permissions from applications in order to use their security in our app. Here as we use Github, head to this page.Select “New OAuth App” and then the “Register a new OAuth application” page is presented. Enter an app name and description. Then, enter your app’s home page, which should be http://localhost:8080, in this case. Finally, indicate the Authorization callback URL which is basically the URL of the path, the user should land on after authenticated with GitHub.Now, the app which we have created will give us Client ID and Client secret. Copy these fields.Now, come back to your Spring application and open applications.yml. This file needs to be modified as below. Copy the data in yml file and it’s ready to go."
},
{
"code": null,
"e": 3110,
"s": 2990,
"text": "Create a new project(Spring Starter) with spring web, spring-security dependency, and oauth2 auto-configure dependency."
},
{
"code": null,
"e": 3225,
"s": 3110,
"text": "Head to the default class. Add the annotation @EnableOAuth2Sso. This allows us to Enable Oauth in our application."
},
{
"code": null,
"e": 3491,
"s": 3225,
"text": "Now, when an Oauth call is made, we need to tell the Client(which is a service and here Github) to look somewhere in order to know what applications can be used to make the OAuth calls. As such, we configure our “application. Properties” file to “applications.yml”."
},
{
"code": null,
"e": 3627,
"s": 3491,
"text": "We also need various permissions from applications in order to use their security in our app. Here as we use Github, head to this page."
},
{
"code": null,
"e": 3985,
"s": 3627,
"text": "Select “New OAuth App” and then the “Register a new OAuth application” page is presented. Enter an app name and description. Then, enter your app’s home page, which should be http://localhost:8080, in this case. Finally, indicate the Authorization callback URL which is basically the URL of the path, the user should land on after authenticated with GitHub."
},
{
"code": null,
"e": 4081,
"s": 3985,
"text": "Now, the app which we have created will give us Client ID and Client secret. Copy these fields."
},
{
"code": null,
"e": 4239,
"s": 4081,
"text": "Now, come back to your Spring application and open applications.yml. This file needs to be modified as below. Copy the data in yml file and it’s ready to go."
},
{
"code": null,
"e": 4297,
"s": 4239,
"text": " Let’s see the given below applications.yml as follows. "
},
{
"code": null,
"e": 4698,
"s": 4297,
"text": "Security:\n oauth2:\n client:\n clientId: your-id\n clientSecret: your-secret\n accessTokenUri: https://github.com/login/oauth/access_token\n userAuthorizationUri: https://github.com/login/oauth/authorize\n clientAuthenticationScheme: form\n resource:\n user-info-uri: https://api.github.com/user\n prefer-token-info: false"
},
{
"code": null,
"e": 4739,
"s": 4698,
"text": "Descriptions of applications.yml file : "
},
{
"code": null,
"e": 4919,
"s": 4739,
"text": "All the information issued above is used by the Github authorization to identify the details. We can turn “prefer-token-info” to true if we wish to use it for any further purpose."
},
{
"code": null,
"e": 5154,
"s": 4919,
"text": "ClienAuthenticationScheme is set to form here as in this very example, as Github will be using a form to enter all user details. Moreover, all the above details are for Github’s internal use, and we don’t need to worry about the same."
},
{
"code": null,
"e": 5247,
"s": 5154,
"text": "Note — Since the applications file is yml file hence the code has to be structured as above."
},
{
"code": null,
"e": 5406,
"s": 5247,
"text": "Also, when we run our above application on localhost, we’ll be displaying some text to see if our OAuth is working or not, so we build a simple API and add:- "
},
{
"code": null,
"e": 5411,
"s": 5406,
"text": "Java"
},
{
"code": "@SpringBootApplication@EnableOAuth2Sso@RestController // Main class name DemoApplicationpublic class DemoApplication { // API @GetMapping(\"/\") public String message(Principal principal) { return \"hi \"+principal.getName(); } public static void main(String[] args) { // DemoApplication is the default class. SpringApplication.run(DemoApplication.class, args); } }",
"e": 5833,
"s": 5411,
"text": null
},
{
"code": null,
"e": 5856,
"s": 5833,
"text": "Program Descriptions :"
},
{
"code": null,
"e": 5898,
"s": 5856,
"text": "The DemoApplication is the default class."
},
{
"code": null,
"e": 6020,
"s": 5898,
"text": "The principal Object will take in the user details and display “hi” username when the Github auth is successfully passed."
},
{
"code": null,
"e": 6117,
"s": 6020,
"text": "Now run your Spring application and open localhost 8080 and see the GitHub auth work yourself!. "
},
{
"code": null,
"e": 6129,
"s": 6117,
"text": "Java-Spring"
},
{
"code": null,
"e": 6153,
"s": 6129,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 6158,
"s": 6153,
"text": "Java"
},
{
"code": null,
"e": 6177,
"s": 6158,
"text": "Technical Scripter"
},
{
"code": null,
"e": 6182,
"s": 6177,
"text": "Java"
}
] |
Swap the elements between any two given quadrants of a Matrix
|
22 Jun, 2021
Given a matrix, mat[][] of size N * M, where N and M is always even, and two integers X and Y, the task is to swap all the elements of the quadrant X quadrant with all the corresponding elements of quadrant Y of the given matrix.
Note: The top-left, top-right, bottom-left, and bottom-right quadrants are numbered 1, 2, 3, and 4 respectively.Examples:
Input: mat[][] = {{99, 10, 11, 12, 13, 14, 15, 16}, {17, 18, 19, 20, 21, 22, 23, 24}, {25, 26, 27, 28, 29, 30, 31, 32}, {33, 34, 35, 36, 37, 38, 39, 40}, {41, 42, 43, 44, 45, 46, 47, 48}, {49, 50, 51, 52, 53, 54, 55, 56}}, X = 1, Y = 4 Output: {{37, 38, 39, 40, 13, 14, 15, 16}, { 45, 46, 47, 48, 21, 22, 23, 24}, { 53, 54, 55, 56, 29, 30, 31, 32}, {33, 34, 35, 36, 99, 10, 11, 12}, {41, 42, 43, 44, 17, 18, 19, 20}, {49, 50, 51, 52, 25, 26, 27, 28}} Explanation: Given Matrix:
Swap the 1st quadrant of the matrix with 4th quadrant of the matrix:
Input: mat[][] = {{1, 2}, {3, 4}}, X = 1, Y = 4 Output: {{4, 2}, {3, 1}}
Approach: The idea is to iterate over the X quadrant of the matrix and swap its elements with the corresponding elements of the Y quadrant. To get the starting positions of any quadrant when a matrix mat[][] of size N*M below is the condition for the same:
Quadrant 1: The starting position of the quadrant is (0, 0).
Quadrant 2: The starting position of the quadrant is (0, M/2).
Quadrant 3: The starting position of the quadrant is (N/2, 0).
Quadrant 4: The starting position of the quadrant is (N/2, M/2).
Follow the steps below to solve the problem:
Iterate over the X and Y quadrants of the matrix simultaneously from their starting positions.Now, swap the elements of X quadrant with the corresponding indexed elements of Y quadrant.Print all elements of the matrix mat[][] after performing all the swap operations.
Iterate over the X and Y quadrants of the matrix simultaneously from their starting positions.
Now, swap the elements of X quadrant with the corresponding indexed elements of Y quadrant.
Print all elements of the matrix mat[][] after performing all the swap operations.
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;#define N 6#define M 6 // Function to iterate over the X// quadrant and swap its element// with Y quadrantvoid swap(int mat[N][M], int startx_X, int starty_X, int startx_Y, int starty_Y){ int row = 0; int col = 0; // Iterate over X quadrant for (int i = startx_X;; i++) { col = 0; for (int j = startx_X;; j++) { // Swap operations int temp = mat[i][j]; mat[i][j] = mat[startx_Y + row][starty_Y + col]; mat[startx_Y + row][starty_Y + col] = temp; col++; if (col >= M / 2) break; } row++; if (row >= N / 2) break; }} // Function to print the matrixvoid printMat(int mat[N][M]){ // Iterate over the rows for (int i = 0; i < N; i++) { // Iterate over the cols for (int j = 0; j < M; j++) { cout << mat[i][j] << " "; } cout << endl; }} // Function to swap the elements// of the two given quadrantsstatic void swapQuadOfMatrix(int mat[N][M], int X, int Y){ // Swapping the coordinates on // basis of the value of X and Y // For Swapping 1st and 2nd Quadrant if (X == 1 && Y == 2) { swap(mat, 0, 0, 0, M / 2); } // For Swapping 1st and 3rd Quadrant else if (X == 1 && Y == 3) { swap(mat, 0, 0, N / 2, 0); } // For Swapping 1st and 4th Quadrant else if (X == 1 && Y == 4) { swap(mat, 0, 0, N / 2, M / 2); } // For Swapping 2nd and 3rd Quadrant else if (X == 2 && Y == 3) { swap(mat, 0, M / 2, N / 2, 0); } // For Swapping 2nd and 4th Quadrant else if (X == 2 && Y == 4) { swap(mat, 0, M / 2, N / 2, M / 2); } // For Swapping 3rd and 4th Quadrant else if (X == 3 && Y == 4) { swap(mat, N / 2, 0, N / 2, M / 2); } // Print the resultant matrix printMat(mat);} // Driver Codeint main(){ // Given matrix int mat[][M] = {{1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18}, {19, 20, 21, 22, 23, 24}, {25, 26, 27, 28, 29, 30}, {31, 32, 33, 34, 35, 36}}; // Given quadrants int X = 1, Y = 4; // Function Call swapQuadOfMatrix(mat, X, Y);} // This code is contributed by shikhasingrajput
// Java program for the above approach public class Main { // Function to iterate over the X // quadrant and swap its element // with Y quadrant static void swap( int N, int M, int mat[][], int startx_X, int starty_X, int startx_Y, int starty_Y) { int row = 0; int col = 0; // Iterate over X quadrant for (int i = startx_X;; i++) { col = 0; for (int j = startx_X;; j++) { // Swap operations int temp = mat[i][j]; mat[i][j] = mat[startx_Y + row][starty_Y + col]; mat[startx_Y + row][starty_Y + col] = temp; col++; if (col >= M / 2) break; } row++; if (row >= N / 2) break; } } // Function to swap the elements // of the two given quadrants static void swapQuadOfMatrix( int N, int M, int mat[][], int X, int Y) { // Swapping the coordinates on // basis of the value of X and Y // For Swapping 1st and 2nd Quadrant if (X == 1 && Y == 2) { swap(N, M, mat, 0, 0, 0, M / 2); } // For Swapping 1st and 3rd Quadrant else if (X == 1 && Y == 3) { swap(N, M, mat, 0, 0, N / 2, 0); } // For Swapping 1st and 4th Quadrant else if (X == 1 && Y == 4) { swap(N, M, mat, 0, 0, N / 2, M / 2); } // For Swapping 2nd and 3rd Quadrant else if (X == 2 && Y == 3) { swap(N, M, mat, 0, M / 2, N / 2, 0); } // For Swapping 2nd and 4th Quadrant else if (X == 2 && Y == 4) { swap(N, M, mat, 0, M / 2, N / 2, M / 2); } // For Swapping 3rd and 4th Quadrant else if (X == 3 && Y == 4) { swap(N, M, mat, N / 2, 0, N / 2, M / 2); } // Print the resultant matrix printMat(N, M, mat); } // Function to print the matrix static void printMat(int N, int M, int mat[][]) { // Iterate over the rows for (int i = 0; i < N; i++) { // Iterate over the cols for (int j = 0; j < M; j++) { System.out.print( mat[i][j] + " "); } System.out.println(); } } // Driver Code public static void main(String[] args) { // Given matrix int N = 6, M = 6; int[][] mat = { { 1, 2, 3, 4, 5, 6 }, { 7, 8, 9, 10, 11, 12 }, { 13, 14, 15, 16, 17, 18 }, { 19, 20, 21, 22, 23, 24 }, { 25, 26, 27, 28, 29, 30 }, { 31, 32, 33, 34, 35, 36 } }; // Given quadrants int X = 1, Y = 4; // Function Call swapQuadOfMatrix(N, M, mat, X, Y); }}
# Python3 program for# the above approachN, M = 6, 6 # Function to iterate over# the X quadrant and swap# its element with Y quadrantdef swap(mat, startx_X, starty_X, startx_Y, starty_Y): row,col = 0, 0 # Iterate over X quadrant i = startx_X while(bool(True)): col = 0 j = startx_X while(bool(True)): # Swap operations temp = mat[i][j] mat[i][j] = mat[startx_Y + row][starty_Y + col] mat[startx_Y + row][starty_Y + col] = temp col += 1 if col >= M // 2: break j += 1 row += 1 if row >= N // 2: break i += 1 # Function to print the# matrixdef printMat(mat): # Iterate over the rows for i in range(N): # Iterate over the cols for j in range(M): print(mat[i][j], end = " ") print() # Function to swap the# elements of the two# given quadrantsdef swapQuadOfMatrix(mat, X, Y): # Swapping the coordinates # on basis of the value of # X and Y # For Swapping 1st and # 2nd Quadrant if (X == 1 and Y == 2): swap(mat, 0, 0, 0, M // 2) # For Swapping 1st and # 3rd Quadrant elif (X == 1 and Y == 3): swap(mat, 0, 0, N // 2, 0) # For Swapping 1st and # 4th Quadrant elif (X == 1 and Y == 4): swap(mat, 0, 0, N // 2, M // 2) # For Swapping 2nd and # 3rd Quadrant elif (X == 2 and Y == 3): swap(mat, 0, M // 2, N // 2, 0) # For Swapping 2nd and # 4th Quadrant elif (X == 2 and Y == 4): swap(mat, 0, M // 2, N // 2, M // 2) # For Swapping 3rd and # 4th Quadrant elif (X == 3 and Y == 4): swap(mat, N // 2, 0, N // 2, M // 2) # Print the resultant # matrix printMat(mat) # Driver code# Given matrixmat = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24], [25, 26, 27, 28, 29, 30], [31, 32, 33, 34, 35, 36]] # Given quadrantsX, Y = 1, 4 # Function CallswapQuadOfMatrix(mat, X, Y) # This code is contributed by divyeshrabadiya07
// C# program for// the above approachusing System;class GFG{ // Function to iterate over the X// quadrant and swap its element// with Y quadrantstatic void swap(int N, int M, int [,]mat, int startx_X, int starty_X, int startx_Y, int starty_Y){ int row = 0; int col = 0; // Iterate over X quadrant for (int i = startx_X;; i++) { col = 0; for (int j = startx_X;; j++) { // Swap operations int temp = mat[i, j]; mat[i, j] = mat[startx_Y + row, starty_Y + col]; mat[startx_Y + row, starty_Y + col] = temp; col++; if (col >= M / 2) break; } row++; if (row >= N / 2) break; }} // Function to swap the elements// of the two given quadrantsstatic void swapQuadOfMatrix(int N, int M, int [,]mat, int X, int Y){ // Swapping the coordinates on // basis of the value of X and Y // For Swapping 1st and 2nd Quadrant if (X == 1 && Y == 2) { swap(N, M, mat, 0, 0, 0, M / 2); } // For Swapping 1st and 3rd Quadrant else if (X == 1 && Y == 3) { swap(N, M, mat, 0, 0, N / 2, 0); } // For Swapping 1st and 4th Quadrant else if (X == 1 && Y == 4) { swap(N, M, mat, 0, 0, N / 2, M / 2); } // For Swapping 2nd and 3rd Quadrant else if (X == 2 && Y == 3) { swap(N, M, mat, 0, M / 2, N / 2, 0); } // For Swapping 2nd and 4th Quadrant else if (X == 2 && Y == 4) { swap(N, M, mat, 0, M / 2, N / 2, M / 2); } // For Swapping 3rd and 4th Quadrant else if (X == 3 && Y == 4) { swap(N, M, mat, N / 2, 0, N / 2, M / 2); } // Print the resultant matrix printMat(N, M, mat);} // Function to print the matrixstatic void printMat(int N, int M, int [,]mat){ // Iterate over the rows for (int i = 0; i < N; i++) { // Iterate over the cols for (int j = 0; j < M; j++) { Console.Write(mat[i, j] + " "); } Console.WriteLine(); }} // Driver Codepublic static void Main(String[] args){ // Given matrix int N = 6, M = 6; int[,] mat = {{1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18}, {19, 20, 21, 22, 23, 24}, {25, 26, 27, 28, 29, 30}, {31, 32, 33, 34, 35, 36}}; // Given quadrants int X = 1, Y = 4; // Function Call swapQuadOfMatrix(N, M, mat, X, Y);}} // This code is contributed by gauravrajput1
<script>// javascript program for the// above approach // Function to iterate over the X // quadrant and swap its element // with Y quadrant function swap( N, M, mat, startx_X, starty_X, startx_Y, starty_Y) { let row = 0; let col = 0; // Iterate over X quadrant for (let i = startx_X;; i++) { col = 0; for (let j = startx_X;; j++) { // Swap operations let temp = mat[i][j]; mat[i][j] = mat[startx_Y + row][starty_Y + col]; mat[startx_Y + row][starty_Y + col] = temp; col++; if (col >= M / 2) break; } row++; if (row >= N / 2) break; } } // Function to swap the elements // of the two given quadrants function swapQuadOfMatrix( N, M, mat, X, Y) { // Swapping the coordinates on // basis of the value of X and Y // For Swapping 1st and 2nd Quadrant if (X == 1 && Y == 2) { swap(N, M, mat, 0, 0, 0, M / 2); } // For Swapping 1st and 3rd Quadrant else if (X == 1 && Y == 3) { swap(N, M, mat, 0, 0, N / 2, 0); } // For Swapping 1st and 4th Quadrant else if (X == 1 && Y == 4) { swap(N, M, mat, 0, 0, N / 2, M / 2); } // For Swapping 2nd and 3rd Quadrant else if (X == 2 && Y == 3) { swap(N, M, mat, 0, M / 2, N / 2, 0); } // For Swapping 2nd and 4th Quadrant else if (X == 2 && Y == 4) { swap(N, M, mat, 0, M / 2, N / 2, M / 2); } // For Swapping 3rd and 4th Quadrant else if (X == 3 && Y == 4) { swap(N, M, mat, N / 2, 0, N / 2, M / 2); } // Print the resultant matrix prletMat(N, M, mat); } // Function to print the matrix function prletMat(N, M, mat) { // Iterate over the rows for (let i = 0; i < N; i++) { // Iterate over the cols for (let j = 0; j < M; j++) { document.write( mat[i][j] + " "); } document.write("<br/>"); } } // Driver Code // Given matrix let N = 6, M = 6; let mat = [[ 1, 2, 3, 4, 5, 6 ], [ 7, 8, 9, 10, 11, 12 ], [ 13, 14, 15, 16, 17, 18 ], [ 19, 20, 21, 22, 23, 24 ], [ 25, 26, 27, 28, 29, 30 ], [ 31, 32, 33, 34, 35, 36 ]]; // Given quadrants let X = 1, Y = 4; // Function Call swapQuadOfMatrix(N, M, mat, X, Y); // This code is contributed by avijitmondal1998.</script>
22 23 24 4 5 6
28 29 30 10 11 12
34 35 36 16 17 18
19 20 21 1 2 3
25 26 27 7 8 9
31 32 33 13 14 15
Time Complexity: O(N2) Auxiliary Space: O(1)
GauravRajput1
shikhasingrajput
divyeshrabadiya07
avijitmondal1998
khushboogoyal499
Greedy
Matrix
School Programming
Greedy
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 284,
"s": 54,
"text": "Given a matrix, mat[][] of size N * M, where N and M is always even, and two integers X and Y, the task is to swap all the elements of the quadrant X quadrant with all the corresponding elements of quadrant Y of the given matrix."
},
{
"code": null,
"e": 408,
"s": 284,
"text": "Note: The top-left, top-right, bottom-left, and bottom-right quadrants are numbered 1, 2, 3, and 4 respectively.Examples: "
},
{
"code": null,
"e": 888,
"s": 408,
"text": "Input: mat[][] = {{99, 10, 11, 12, 13, 14, 15, 16}, {17, 18, 19, 20, 21, 22, 23, 24}, {25, 26, 27, 28, 29, 30, 31, 32}, {33, 34, 35, 36, 37, 38, 39, 40}, {41, 42, 43, 44, 45, 46, 47, 48}, {49, 50, 51, 52, 53, 54, 55, 56}}, X = 1, Y = 4 Output: {{37, 38, 39, 40, 13, 14, 15, 16}, { 45, 46, 47, 48, 21, 22, 23, 24}, { 53, 54, 55, 56, 29, 30, 31, 32}, {33, 34, 35, 36, 99, 10, 11, 12}, {41, 42, 43, 44, 17, 18, 19, 20}, {49, 50, 51, 52, 25, 26, 27, 28}} Explanation: Given Matrix: "
},
{
"code": null,
"e": 959,
"s": 888,
"text": "Swap the 1st quadrant of the matrix with 4th quadrant of the matrix: "
},
{
"code": null,
"e": 1036,
"s": 961,
"text": "Input: mat[][] = {{1, 2}, {3, 4}}, X = 1, Y = 4 Output: {{4, 2}, {3, 1}} "
},
{
"code": null,
"e": 1295,
"s": 1036,
"text": "Approach: The idea is to iterate over the X quadrant of the matrix and swap its elements with the corresponding elements of the Y quadrant. To get the starting positions of any quadrant when a matrix mat[][] of size N*M below is the condition for the same: "
},
{
"code": null,
"e": 1356,
"s": 1295,
"text": "Quadrant 1: The starting position of the quadrant is (0, 0)."
},
{
"code": null,
"e": 1419,
"s": 1356,
"text": "Quadrant 2: The starting position of the quadrant is (0, M/2)."
},
{
"code": null,
"e": 1482,
"s": 1419,
"text": "Quadrant 3: The starting position of the quadrant is (N/2, 0)."
},
{
"code": null,
"e": 1547,
"s": 1482,
"text": "Quadrant 4: The starting position of the quadrant is (N/2, M/2)."
},
{
"code": null,
"e": 1594,
"s": 1547,
"text": "Follow the steps below to solve the problem: "
},
{
"code": null,
"e": 1862,
"s": 1594,
"text": "Iterate over the X and Y quadrants of the matrix simultaneously from their starting positions.Now, swap the elements of X quadrant with the corresponding indexed elements of Y quadrant.Print all elements of the matrix mat[][] after performing all the swap operations."
},
{
"code": null,
"e": 1957,
"s": 1862,
"text": "Iterate over the X and Y quadrants of the matrix simultaneously from their starting positions."
},
{
"code": null,
"e": 2049,
"s": 1957,
"text": "Now, swap the elements of X quadrant with the corresponding indexed elements of Y quadrant."
},
{
"code": null,
"e": 2132,
"s": 2049,
"text": "Print all elements of the matrix mat[][] after performing all the swap operations."
},
{
"code": null,
"e": 2184,
"s": 2132,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 2188,
"s": 2184,
"text": "C++"
},
{
"code": null,
"e": 2193,
"s": 2188,
"text": "Java"
},
{
"code": null,
"e": 2201,
"s": 2193,
"text": "Python3"
},
{
"code": null,
"e": 2204,
"s": 2201,
"text": "C#"
},
{
"code": null,
"e": 2215,
"s": 2204,
"text": "Javascript"
},
{
"code": "// C++ program for// the above approach#include<bits/stdc++.h>using namespace std;#define N 6#define M 6 // Function to iterate over the X// quadrant and swap its element// with Y quadrantvoid swap(int mat[N][M], int startx_X, int starty_X, int startx_Y, int starty_Y){ int row = 0; int col = 0; // Iterate over X quadrant for (int i = startx_X;; i++) { col = 0; for (int j = startx_X;; j++) { // Swap operations int temp = mat[i][j]; mat[i][j] = mat[startx_Y + row][starty_Y + col]; mat[startx_Y + row][starty_Y + col] = temp; col++; if (col >= M / 2) break; } row++; if (row >= N / 2) break; }} // Function to print the matrixvoid printMat(int mat[N][M]){ // Iterate over the rows for (int i = 0; i < N; i++) { // Iterate over the cols for (int j = 0; j < M; j++) { cout << mat[i][j] << \" \"; } cout << endl; }} // Function to swap the elements// of the two given quadrantsstatic void swapQuadOfMatrix(int mat[N][M], int X, int Y){ // Swapping the coordinates on // basis of the value of X and Y // For Swapping 1st and 2nd Quadrant if (X == 1 && Y == 2) { swap(mat, 0, 0, 0, M / 2); } // For Swapping 1st and 3rd Quadrant else if (X == 1 && Y == 3) { swap(mat, 0, 0, N / 2, 0); } // For Swapping 1st and 4th Quadrant else if (X == 1 && Y == 4) { swap(mat, 0, 0, N / 2, M / 2); } // For Swapping 2nd and 3rd Quadrant else if (X == 2 && Y == 3) { swap(mat, 0, M / 2, N / 2, 0); } // For Swapping 2nd and 4th Quadrant else if (X == 2 && Y == 4) { swap(mat, 0, M / 2, N / 2, M / 2); } // For Swapping 3rd and 4th Quadrant else if (X == 3 && Y == 4) { swap(mat, N / 2, 0, N / 2, M / 2); } // Print the resultant matrix printMat(mat);} // Driver Codeint main(){ // Given matrix int mat[][M] = {{1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18}, {19, 20, 21, 22, 23, 24}, {25, 26, 27, 28, 29, 30}, {31, 32, 33, 34, 35, 36}}; // Given quadrants int X = 1, Y = 4; // Function Call swapQuadOfMatrix(mat, X, Y);} // This code is contributed by shikhasingrajput",
"e": 4472,
"s": 2215,
"text": null
},
{
"code": "// Java program for the above approach public class Main { // Function to iterate over the X // quadrant and swap its element // with Y quadrant static void swap( int N, int M, int mat[][], int startx_X, int starty_X, int startx_Y, int starty_Y) { int row = 0; int col = 0; // Iterate over X quadrant for (int i = startx_X;; i++) { col = 0; for (int j = startx_X;; j++) { // Swap operations int temp = mat[i][j]; mat[i][j] = mat[startx_Y + row][starty_Y + col]; mat[startx_Y + row][starty_Y + col] = temp; col++; if (col >= M / 2) break; } row++; if (row >= N / 2) break; } } // Function to swap the elements // of the two given quadrants static void swapQuadOfMatrix( int N, int M, int mat[][], int X, int Y) { // Swapping the coordinates on // basis of the value of X and Y // For Swapping 1st and 2nd Quadrant if (X == 1 && Y == 2) { swap(N, M, mat, 0, 0, 0, M / 2); } // For Swapping 1st and 3rd Quadrant else if (X == 1 && Y == 3) { swap(N, M, mat, 0, 0, N / 2, 0); } // For Swapping 1st and 4th Quadrant else if (X == 1 && Y == 4) { swap(N, M, mat, 0, 0, N / 2, M / 2); } // For Swapping 2nd and 3rd Quadrant else if (X == 2 && Y == 3) { swap(N, M, mat, 0, M / 2, N / 2, 0); } // For Swapping 2nd and 4th Quadrant else if (X == 2 && Y == 4) { swap(N, M, mat, 0, M / 2, N / 2, M / 2); } // For Swapping 3rd and 4th Quadrant else if (X == 3 && Y == 4) { swap(N, M, mat, N / 2, 0, N / 2, M / 2); } // Print the resultant matrix printMat(N, M, mat); } // Function to print the matrix static void printMat(int N, int M, int mat[][]) { // Iterate over the rows for (int i = 0; i < N; i++) { // Iterate over the cols for (int j = 0; j < M; j++) { System.out.print( mat[i][j] + \" \"); } System.out.println(); } } // Driver Code public static void main(String[] args) { // Given matrix int N = 6, M = 6; int[][] mat = { { 1, 2, 3, 4, 5, 6 }, { 7, 8, 9, 10, 11, 12 }, { 13, 14, 15, 16, 17, 18 }, { 19, 20, 21, 22, 23, 24 }, { 25, 26, 27, 28, 29, 30 }, { 31, 32, 33, 34, 35, 36 } }; // Given quadrants int X = 1, Y = 4; // Function Call swapQuadOfMatrix(N, M, mat, X, Y); }}",
"e": 7444,
"s": 4472,
"text": null
},
{
"code": "# Python3 program for# the above approachN, M = 6, 6 # Function to iterate over# the X quadrant and swap# its element with Y quadrantdef swap(mat, startx_X, starty_X, startx_Y, starty_Y): row,col = 0, 0 # Iterate over X quadrant i = startx_X while(bool(True)): col = 0 j = startx_X while(bool(True)): # Swap operations temp = mat[i][j] mat[i][j] = mat[startx_Y + row][starty_Y + col] mat[startx_Y + row][starty_Y + col] = temp col += 1 if col >= M // 2: break j += 1 row += 1 if row >= N // 2: break i += 1 # Function to print the# matrixdef printMat(mat): # Iterate over the rows for i in range(N): # Iterate over the cols for j in range(M): print(mat[i][j], end = \" \") print() # Function to swap the# elements of the two# given quadrantsdef swapQuadOfMatrix(mat, X, Y): # Swapping the coordinates # on basis of the value of # X and Y # For Swapping 1st and # 2nd Quadrant if (X == 1 and Y == 2): swap(mat, 0, 0, 0, M // 2) # For Swapping 1st and # 3rd Quadrant elif (X == 1 and Y == 3): swap(mat, 0, 0, N // 2, 0) # For Swapping 1st and # 4th Quadrant elif (X == 1 and Y == 4): swap(mat, 0, 0, N // 2, M // 2) # For Swapping 2nd and # 3rd Quadrant elif (X == 2 and Y == 3): swap(mat, 0, M // 2, N // 2, 0) # For Swapping 2nd and # 4th Quadrant elif (X == 2 and Y == 4): swap(mat, 0, M // 2, N // 2, M // 2) # For Swapping 3rd and # 4th Quadrant elif (X == 3 and Y == 4): swap(mat, N // 2, 0, N // 2, M // 2) # Print the resultant # matrix printMat(mat) # Driver code# Given matrixmat = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24], [25, 26, 27, 28, 29, 30], [31, 32, 33, 34, 35, 36]] # Given quadrantsX, Y = 1, 4 # Function CallswapQuadOfMatrix(mat, X, Y) # This code is contributed by divyeshrabadiya07",
"e": 9821,
"s": 7444,
"text": null
},
{
"code": "// C# program for// the above approachusing System;class GFG{ // Function to iterate over the X// quadrant and swap its element// with Y quadrantstatic void swap(int N, int M, int [,]mat, int startx_X, int starty_X, int startx_Y, int starty_Y){ int row = 0; int col = 0; // Iterate over X quadrant for (int i = startx_X;; i++) { col = 0; for (int j = startx_X;; j++) { // Swap operations int temp = mat[i, j]; mat[i, j] = mat[startx_Y + row, starty_Y + col]; mat[startx_Y + row, starty_Y + col] = temp; col++; if (col >= M / 2) break; } row++; if (row >= N / 2) break; }} // Function to swap the elements// of the two given quadrantsstatic void swapQuadOfMatrix(int N, int M, int [,]mat, int X, int Y){ // Swapping the coordinates on // basis of the value of X and Y // For Swapping 1st and 2nd Quadrant if (X == 1 && Y == 2) { swap(N, M, mat, 0, 0, 0, M / 2); } // For Swapping 1st and 3rd Quadrant else if (X == 1 && Y == 3) { swap(N, M, mat, 0, 0, N / 2, 0); } // For Swapping 1st and 4th Quadrant else if (X == 1 && Y == 4) { swap(N, M, mat, 0, 0, N / 2, M / 2); } // For Swapping 2nd and 3rd Quadrant else if (X == 2 && Y == 3) { swap(N, M, mat, 0, M / 2, N / 2, 0); } // For Swapping 2nd and 4th Quadrant else if (X == 2 && Y == 4) { swap(N, M, mat, 0, M / 2, N / 2, M / 2); } // For Swapping 3rd and 4th Quadrant else if (X == 3 && Y == 4) { swap(N, M, mat, N / 2, 0, N / 2, M / 2); } // Print the resultant matrix printMat(N, M, mat);} // Function to print the matrixstatic void printMat(int N, int M, int [,]mat){ // Iterate over the rows for (int i = 0; i < N; i++) { // Iterate over the cols for (int j = 0; j < M; j++) { Console.Write(mat[i, j] + \" \"); } Console.WriteLine(); }} // Driver Codepublic static void Main(String[] args){ // Given matrix int N = 6, M = 6; int[,] mat = {{1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18}, {19, 20, 21, 22, 23, 24}, {25, 26, 27, 28, 29, 30}, {31, 32, 33, 34, 35, 36}}; // Given quadrants int X = 1, Y = 4; // Function Call swapQuadOfMatrix(N, M, mat, X, Y);}} // This code is contributed by gauravrajput1",
"e": 12259,
"s": 9821,
"text": null
},
{
"code": "<script>// javascript program for the// above approach // Function to iterate over the X // quadrant and swap its element // with Y quadrant function swap( N, M, mat, startx_X, starty_X, startx_Y, starty_Y) { let row = 0; let col = 0; // Iterate over X quadrant for (let i = startx_X;; i++) { col = 0; for (let j = startx_X;; j++) { // Swap operations let temp = mat[i][j]; mat[i][j] = mat[startx_Y + row][starty_Y + col]; mat[startx_Y + row][starty_Y + col] = temp; col++; if (col >= M / 2) break; } row++; if (row >= N / 2) break; } } // Function to swap the elements // of the two given quadrants function swapQuadOfMatrix( N, M, mat, X, Y) { // Swapping the coordinates on // basis of the value of X and Y // For Swapping 1st and 2nd Quadrant if (X == 1 && Y == 2) { swap(N, M, mat, 0, 0, 0, M / 2); } // For Swapping 1st and 3rd Quadrant else if (X == 1 && Y == 3) { swap(N, M, mat, 0, 0, N / 2, 0); } // For Swapping 1st and 4th Quadrant else if (X == 1 && Y == 4) { swap(N, M, mat, 0, 0, N / 2, M / 2); } // For Swapping 2nd and 3rd Quadrant else if (X == 2 && Y == 3) { swap(N, M, mat, 0, M / 2, N / 2, 0); } // For Swapping 2nd and 4th Quadrant else if (X == 2 && Y == 4) { swap(N, M, mat, 0, M / 2, N / 2, M / 2); } // For Swapping 3rd and 4th Quadrant else if (X == 3 && Y == 4) { swap(N, M, mat, N / 2, 0, N / 2, M / 2); } // Print the resultant matrix prletMat(N, M, mat); } // Function to print the matrix function prletMat(N, M, mat) { // Iterate over the rows for (let i = 0; i < N; i++) { // Iterate over the cols for (let j = 0; j < M; j++) { document.write( mat[i][j] + \" \"); } document.write(\"<br/>\"); } } // Driver Code // Given matrix let N = 6, M = 6; let mat = [[ 1, 2, 3, 4, 5, 6 ], [ 7, 8, 9, 10, 11, 12 ], [ 13, 14, 15, 16, 17, 18 ], [ 19, 20, 21, 22, 23, 24 ], [ 25, 26, 27, 28, 29, 30 ], [ 31, 32, 33, 34, 35, 36 ]]; // Given quadrants let X = 1, Y = 4; // Function Call swapQuadOfMatrix(N, M, mat, X, Y); // This code is contributed by avijitmondal1998.</script>",
"e": 15133,
"s": 12259,
"text": null
},
{
"code": null,
"e": 15237,
"s": 15133,
"text": "22 23 24 4 5 6 \n28 29 30 10 11 12 \n34 35 36 16 17 18 \n19 20 21 1 2 3 \n25 26 27 7 8 9 \n31 32 33 13 14 15"
},
{
"code": null,
"e": 15285,
"s": 15239,
"text": "Time Complexity: O(N2) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 15299,
"s": 15285,
"text": "GauravRajput1"
},
{
"code": null,
"e": 15316,
"s": 15299,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 15334,
"s": 15316,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 15351,
"s": 15334,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 15368,
"s": 15351,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 15375,
"s": 15368,
"text": "Greedy"
},
{
"code": null,
"e": 15382,
"s": 15375,
"text": "Matrix"
},
{
"code": null,
"e": 15401,
"s": 15382,
"text": "School Programming"
},
{
"code": null,
"e": 15408,
"s": 15401,
"text": "Greedy"
},
{
"code": null,
"e": 15415,
"s": 15408,
"text": "Matrix"
}
] |
NuxtJS Directory Structure
|
13 Dec, 2021
In this article, we are going to learn about the directory structure of NuxtJs. Nuxt.js is a free and open-source web application framework based on Vue.js, Node.js, Webpack, and Babel.js. Nuxt is inspired by Next.js, which is a framework of similar purpose, based on React.js.
Create NuxtJS Application:
Step 1: You can create a new NuxtJs project using the below command:
npx create-nuxt-app gfg
Step 2: Now navigate to your app using the following command:
cd gfg
Project Structure: It will look like this.
There are 7 main sub directories in NuxtJs:
Components: In this directory, we can store all the components that we are going to use in our main app. Unlike NextJs or ReactJs we don’t have to manually import the components in our pages in NuxtJs. NuxtJs will automatically scan and import your components into your pages.
Components: In this directory, we can store all the components that we are going to use in our main app. Unlike NextJs or ReactJs we don’t have to manually import the components in our pages in NuxtJs. NuxtJs will automatically scan and import your components into your pages.
Pages: In this directory, we can create pages for our NuxtJs app. You just have to create a new .vue file inside the page’s directory to create a new page. After that NuxtJs will automatically scan the pages and create the router for the app. You can also create nested pages by creating new folders inside the pages directory.
Pages: In this directory, we can create pages for our NuxtJs app. You just have to create a new .vue file inside the page’s directory to create a new page. After that NuxtJs will automatically scan the pages and create the router for the app. You can also create nested pages by creating new folders inside the pages directory.
Assets: In this directory, we can store different types of assets that we are going to use in our app like images, fonts, audio files, logo, and styles.Note: If this directory does not exist in your app then you can create it by simply adding a folder with the name ‘assets’.
Assets: In this directory, we can store different types of assets that we are going to use in our app like images, fonts, audio files, logo, and styles.
Note: If this directory does not exist in your app then you can create it by simply adding a folder with the name ‘assets’.
Plugins: In this directory, we can add the plugins that we are going to use in our NuxtJs app. After installing the plugins we have to create a new file for that plugin inside our Plugins directory.
Plugins: In this directory, we can add the plugins that we are going to use in our NuxtJs app. After installing the plugins we have to create a new file for that plugin inside our Plugins directory.
Static: In this directory, we will store the static files that are not going to change like robot.txt, sitemaps, or favicons.
Static: In this directory, we will store the static files that are not going to change like robot.txt, sitemaps, or favicons.
nuxt.config.js: This is the configuration file for your NuxtJs app. You can add new modules here by creating a plugins section. You can also override the default settings of your NuxtJs file using this nuxt.config.js file.
nuxt.config.js: This is the configuration file for your NuxtJs app. You can add new modules here by creating a plugins section. You can also override the default settings of your NuxtJs file using this nuxt.config.js file.
packages.json: This file contains all the dependencies of your NuxtJs app. You can also see the commands to run or build the application inside this file with the name and version of your NuxtJs app.
packages.json: This file contains all the dependencies of your NuxtJs app. You can also see the commands to run or build the application inside this file with the name and version of your NuxtJs app.
Example: In this example, let’s create a new page. For this, we have to create a new file with the name gfg.vue inside our pages directory. Add the below content in the file:
gfg.vue
<template> <div> <h3>This is a simple NuxtJs Page.</h3> </div></template>
Run the app: Run the app using the below command in the terminal.
npm run dev
Output:
Reference:https://nuxtjs.org/docs/get-started/directory-structure/
Nuxt.js
Vue.JS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
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": 28,
"s": 0,
"text": "\n13 Dec, 2021"
},
{
"code": null,
"e": 306,
"s": 28,
"text": "In this article, we are going to learn about the directory structure of NuxtJs. Nuxt.js is a free and open-source web application framework based on Vue.js, Node.js, Webpack, and Babel.js. Nuxt is inspired by Next.js, which is a framework of similar purpose, based on React.js."
},
{
"code": null,
"e": 333,
"s": 306,
"text": "Create NuxtJS Application:"
},
{
"code": null,
"e": 402,
"s": 333,
"text": "Step 1: You can create a new NuxtJs project using the below command:"
},
{
"code": null,
"e": 426,
"s": 402,
"text": "npx create-nuxt-app gfg"
},
{
"code": null,
"e": 490,
"s": 428,
"text": "Step 2: Now navigate to your app using the following command:"
},
{
"code": null,
"e": 497,
"s": 490,
"text": "cd gfg"
},
{
"code": null,
"e": 540,
"s": 497,
"text": "Project Structure: It will look like this."
},
{
"code": null,
"e": 584,
"s": 540,
"text": "There are 7 main sub directories in NuxtJs:"
},
{
"code": null,
"e": 861,
"s": 584,
"text": "Components: In this directory, we can store all the components that we are going to use in our main app. Unlike NextJs or ReactJs we don’t have to manually import the components in our pages in NuxtJs. NuxtJs will automatically scan and import your components into your pages."
},
{
"code": null,
"e": 1138,
"s": 861,
"text": "Components: In this directory, we can store all the components that we are going to use in our main app. Unlike NextJs or ReactJs we don’t have to manually import the components in our pages in NuxtJs. NuxtJs will automatically scan and import your components into your pages."
},
{
"code": null,
"e": 1466,
"s": 1138,
"text": "Pages: In this directory, we can create pages for our NuxtJs app. You just have to create a new .vue file inside the page’s directory to create a new page. After that NuxtJs will automatically scan the pages and create the router for the app. You can also create nested pages by creating new folders inside the pages directory."
},
{
"code": null,
"e": 1794,
"s": 1466,
"text": "Pages: In this directory, we can create pages for our NuxtJs app. You just have to create a new .vue file inside the page’s directory to create a new page. After that NuxtJs will automatically scan the pages and create the router for the app. You can also create nested pages by creating new folders inside the pages directory."
},
{
"code": null,
"e": 2070,
"s": 1794,
"text": "Assets: In this directory, we can store different types of assets that we are going to use in our app like images, fonts, audio files, logo, and styles.Note: If this directory does not exist in your app then you can create it by simply adding a folder with the name ‘assets’."
},
{
"code": null,
"e": 2223,
"s": 2070,
"text": "Assets: In this directory, we can store different types of assets that we are going to use in our app like images, fonts, audio files, logo, and styles."
},
{
"code": null,
"e": 2347,
"s": 2223,
"text": "Note: If this directory does not exist in your app then you can create it by simply adding a folder with the name ‘assets’."
},
{
"code": null,
"e": 2546,
"s": 2347,
"text": "Plugins: In this directory, we can add the plugins that we are going to use in our NuxtJs app. After installing the plugins we have to create a new file for that plugin inside our Plugins directory."
},
{
"code": null,
"e": 2745,
"s": 2546,
"text": "Plugins: In this directory, we can add the plugins that we are going to use in our NuxtJs app. After installing the plugins we have to create a new file for that plugin inside our Plugins directory."
},
{
"code": null,
"e": 2871,
"s": 2745,
"text": "Static: In this directory, we will store the static files that are not going to change like robot.txt, sitemaps, or favicons."
},
{
"code": null,
"e": 2997,
"s": 2871,
"text": "Static: In this directory, we will store the static files that are not going to change like robot.txt, sitemaps, or favicons."
},
{
"code": null,
"e": 3220,
"s": 2997,
"text": "nuxt.config.js: This is the configuration file for your NuxtJs app. You can add new modules here by creating a plugins section. You can also override the default settings of your NuxtJs file using this nuxt.config.js file."
},
{
"code": null,
"e": 3443,
"s": 3220,
"text": "nuxt.config.js: This is the configuration file for your NuxtJs app. You can add new modules here by creating a plugins section. You can also override the default settings of your NuxtJs file using this nuxt.config.js file."
},
{
"code": null,
"e": 3643,
"s": 3443,
"text": "packages.json: This file contains all the dependencies of your NuxtJs app. You can also see the commands to run or build the application inside this file with the name and version of your NuxtJs app."
},
{
"code": null,
"e": 3843,
"s": 3643,
"text": "packages.json: This file contains all the dependencies of your NuxtJs app. You can also see the commands to run or build the application inside this file with the name and version of your NuxtJs app."
},
{
"code": null,
"e": 4018,
"s": 3843,
"text": "Example: In this example, let’s create a new page. For this, we have to create a new file with the name gfg.vue inside our pages directory. Add the below content in the file:"
},
{
"code": null,
"e": 4026,
"s": 4018,
"text": "gfg.vue"
},
{
"code": "<template> <div> <h3>This is a simple NuxtJs Page.</h3> </div></template>",
"e": 4106,
"s": 4026,
"text": null
},
{
"code": null,
"e": 4172,
"s": 4106,
"text": "Run the app: Run the app using the below command in the terminal."
},
{
"code": null,
"e": 4184,
"s": 4172,
"text": "npm run dev"
},
{
"code": null,
"e": 4192,
"s": 4184,
"text": "Output:"
},
{
"code": null,
"e": 4259,
"s": 4192,
"text": "Reference:https://nuxtjs.org/docs/get-started/directory-structure/"
},
{
"code": null,
"e": 4267,
"s": 4259,
"text": "Nuxt.js"
},
{
"code": null,
"e": 4274,
"s": 4267,
"text": "Vue.JS"
},
{
"code": null,
"e": 4285,
"s": 4274,
"text": "JavaScript"
},
{
"code": null,
"e": 4302,
"s": 4285,
"text": "Web Technologies"
},
{
"code": null,
"e": 4400,
"s": 4302,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4461,
"s": 4400,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4501,
"s": 4461,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4542,
"s": 4501,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4584,
"s": 4542,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 4606,
"s": 4584,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 4668,
"s": 4606,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4701,
"s": 4668,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4762,
"s": 4701,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4812,
"s": 4762,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
PHP | Namespace
|
04 Oct, 2021
Like C++, PHP Namespaces are the way of encapsulating items so that same names can be reused without name conflicts.
It can be seen as an abstract concept in many places. It allows redeclaring the same functions/classes/interfaces/constant functions in the separate namespace without getting the fatal error.
A namespace is a hierarchically labeled code block holding a regular PHP code.
A namespace can contain valid PHP code.
Namespace affects following types of code: classes (including abstracts and traits), interfaces, functions, and constants.
Namespaces are declared using the namespace keyword.
A namespace must be declared the namespace at the top of the file before any other code – with one exception: the declare keyword.
php
<?phpnamespace MyNamespaceName { // Regular PHP code function hello() { echo 'Hello I am Running from a namespace!'; }}?>
If namespace is declared globally, then declare it without any name.
php
<?phpnamespace { // Global space!}?>
Multiple namespaces can be declared within a single PHP code.
php
<?phpnamespace MyNamespace1 { } namespace MyNamespace2 { } namespace { }?>
A namespace is used to avoid conflicting definitions and introduce more flexibility and organization in the code base. Just like directories, namespace can contain a hierarchy know as subnamespaces. PHP uses the backslash as its namespace separator.Example:
php
<?phpnamespace MyNamespaceName;function hello() { echo 'Hello I am Running from a namespace!'; } // Resolves to MyNamespaceName\hellohello(); // Explicitly resolves to MyNamespaceName\hellonamespace\hello();?>
Aliasing in Namespaces
Importing is achieved by using the ‘use’ keyword. Optionally, It can specify a custom alias with the ‘as’ keyword. Example:
php
<?phpnamespace MyNamespaceName; require 'project/database/connection.php'; use Project\Database\Connection as Connection; $connection = new Connection(); use Project\Database as Database; $connection = new Database\Connection();?>
It is possible to dynamically call namespaced code, dynamic importing is not supported.
php
<?phpnamespace OtherProject; $title = 'geeks'; // This is valid PHPrequire 'project/blog/title/' . $title . '.php'; // This is notuse Project\Blog\title\$title;?>
Reference : http://php.net/manual/en/language.namespaces.php
saurabh1990aror
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Oct, 2021"
},
{
"code": null,
"e": 169,
"s": 52,
"text": "Like C++, PHP Namespaces are the way of encapsulating items so that same names can be reused without name conflicts."
},
{
"code": null,
"e": 361,
"s": 169,
"text": "It can be seen as an abstract concept in many places. It allows redeclaring the same functions/classes/interfaces/constant functions in the separate namespace without getting the fatal error."
},
{
"code": null,
"e": 440,
"s": 361,
"text": "A namespace is a hierarchically labeled code block holding a regular PHP code."
},
{
"code": null,
"e": 480,
"s": 440,
"text": "A namespace can contain valid PHP code."
},
{
"code": null,
"e": 603,
"s": 480,
"text": "Namespace affects following types of code: classes (including abstracts and traits), interfaces, functions, and constants."
},
{
"code": null,
"e": 656,
"s": 603,
"text": "Namespaces are declared using the namespace keyword."
},
{
"code": null,
"e": 789,
"s": 656,
"text": "A namespace must be declared the namespace at the top of the file before any other code – with one exception: the declare keyword. "
},
{
"code": null,
"e": 793,
"s": 789,
"text": "php"
},
{
"code": "<?phpnamespace MyNamespaceName { // Regular PHP code function hello() { echo 'Hello I am Running from a namespace!'; }}?>",
"e": 936,
"s": 793,
"text": null
},
{
"code": null,
"e": 1007,
"s": 936,
"text": "If namespace is declared globally, then declare it without any name. "
},
{
"code": null,
"e": 1011,
"s": 1007,
"text": "php"
},
{
"code": "<?phpnamespace { // Global space!}?>",
"e": 1053,
"s": 1011,
"text": null
},
{
"code": null,
"e": 1117,
"s": 1053,
"text": "Multiple namespaces can be declared within a single PHP code. "
},
{
"code": null,
"e": 1121,
"s": 1117,
"text": "php"
},
{
"code": "<?phpnamespace MyNamespace1 { } namespace MyNamespace2 { } namespace { }?>",
"e": 1203,
"s": 1121,
"text": null
},
{
"code": null,
"e": 1463,
"s": 1203,
"text": "A namespace is used to avoid conflicting definitions and introduce more flexibility and organization in the code base. Just like directories, namespace can contain a hierarchy know as subnamespaces. PHP uses the backslash as its namespace separator.Example: "
},
{
"code": null,
"e": 1467,
"s": 1463,
"text": "php"
},
{
"code": "<?phpnamespace MyNamespaceName;function hello() { echo 'Hello I am Running from a namespace!'; } // Resolves to MyNamespaceName\\hellohello(); // Explicitly resolves to MyNamespaceName\\hellonamespace\\hello();?>",
"e": 1692,
"s": 1467,
"text": null
},
{
"code": null,
"e": 1715,
"s": 1692,
"text": "Aliasing in Namespaces"
},
{
"code": null,
"e": 1841,
"s": 1715,
"text": "Importing is achieved by using the ‘use’ keyword. Optionally, It can specify a custom alias with the ‘as’ keyword. Example: "
},
{
"code": null,
"e": 1845,
"s": 1841,
"text": "php"
},
{
"code": "<?phpnamespace MyNamespaceName; require 'project/database/connection.php'; use Project\\Database\\Connection as Connection; $connection = new Connection(); use Project\\Database as Database; $connection = new Database\\Connection();?>",
"e": 2086,
"s": 1845,
"text": null
},
{
"code": null,
"e": 2176,
"s": 2086,
"text": "It is possible to dynamically call namespaced code, dynamic importing is not supported. "
},
{
"code": null,
"e": 2180,
"s": 2176,
"text": "php"
},
{
"code": "<?phpnamespace OtherProject; $title = 'geeks'; // This is valid PHPrequire 'project/blog/title/' . $title . '.php'; // This is notuse Project\\Blog\\title\\$title;?>",
"e": 2349,
"s": 2180,
"text": null
},
{
"code": null,
"e": 2411,
"s": 2349,
"text": "Reference : http://php.net/manual/en/language.namespaces.php "
},
{
"code": null,
"e": 2427,
"s": 2411,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 2444,
"s": 2427,
"text": "Web Technologies"
}
] |
Executing Shell Commands with Python
|
01 Oct, 2020
Prerequisite: Some basic shell commands
In programming, the shell is a software interface for accessing the functionality of the operating system. Shells in the operating system use either a CLI (Command Line Interface) or a GUI (Graphical User Interface) based on the functionality and basic operation of the device.
The os module in Python includes functionality to communicate with the operating system. The os module is one of the standard utility modules of Python. This Python module offers a convenient way to use operating system-dependent features, shell commands can be executed using the system() method in the os module.
Below are some examples to execute shell commands using Python:
Example 1:
Python3
# Importing required moduleimport os # Using system() method to # execute shell commandsos.system('echo "Geeks 4 Geeks"')
Output:
Example 2:
Python3
# Importing required moduleimport os # Using system() method to execute# shell commandsos.system('pwd')
Output:
Example 3:
Python3
# Importing required moduleimport os # Using system() method to execute# shell commandsos.system('ls')
Output:
Example 4:
Python3
# Importing required moduleimport os # Using system() method to execute# shell commandsos.system('cat')
Output:
Example 5:
Python3
# Importing required moduleimport os # Using system() method to execute# shell commandsos.system('telnet towel.blinkenlights.nl')
Output:
python-os-module
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 68,
"s": 28,
"text": "Prerequisite: Some basic shell commands"
},
{
"code": null,
"e": 346,
"s": 68,
"text": "In programming, the shell is a software interface for accessing the functionality of the operating system. Shells in the operating system use either a CLI (Command Line Interface) or a GUI (Graphical User Interface) based on the functionality and basic operation of the device."
},
{
"code": null,
"e": 661,
"s": 346,
"text": "The os module in Python includes functionality to communicate with the operating system. The os module is one of the standard utility modules of Python. This Python module offers a convenient way to use operating system-dependent features, shell commands can be executed using the system() method in the os module."
},
{
"code": null,
"e": 725,
"s": 661,
"text": "Below are some examples to execute shell commands using Python:"
},
{
"code": null,
"e": 736,
"s": 725,
"text": "Example 1:"
},
{
"code": null,
"e": 744,
"s": 736,
"text": "Python3"
},
{
"code": "# Importing required moduleimport os # Using system() method to # execute shell commandsos.system('echo \"Geeks 4 Geeks\"')",
"e": 867,
"s": 744,
"text": null
},
{
"code": null,
"e": 875,
"s": 867,
"text": "Output:"
},
{
"code": null,
"e": 887,
"s": 875,
"text": "Example 2: "
},
{
"code": null,
"e": 895,
"s": 887,
"text": "Python3"
},
{
"code": "# Importing required moduleimport os # Using system() method to execute# shell commandsos.system('pwd')",
"e": 1000,
"s": 895,
"text": null
},
{
"code": null,
"e": 1009,
"s": 1000,
"text": "Output: "
},
{
"code": null,
"e": 1021,
"s": 1009,
"text": "Example 3: "
},
{
"code": null,
"e": 1029,
"s": 1021,
"text": "Python3"
},
{
"code": "# Importing required moduleimport os # Using system() method to execute# shell commandsos.system('ls')",
"e": 1133,
"s": 1029,
"text": null
},
{
"code": null,
"e": 1142,
"s": 1133,
"text": "Output: "
},
{
"code": null,
"e": 1154,
"s": 1142,
"text": "Example 4: "
},
{
"code": null,
"e": 1162,
"s": 1154,
"text": "Python3"
},
{
"code": "# Importing required moduleimport os # Using system() method to execute# shell commandsos.system('cat')",
"e": 1267,
"s": 1162,
"text": null
},
{
"code": null,
"e": 1276,
"s": 1267,
"text": "Output: "
},
{
"code": null,
"e": 1288,
"s": 1276,
"text": "Example 5: "
},
{
"code": null,
"e": 1296,
"s": 1288,
"text": "Python3"
},
{
"code": "# Importing required moduleimport os # Using system() method to execute# shell commandsos.system('telnet towel.blinkenlights.nl')",
"e": 1427,
"s": 1296,
"text": null
},
{
"code": null,
"e": 1437,
"s": 1427,
"text": "Output: "
},
{
"code": null,
"e": 1456,
"s": 1439,
"text": "python-os-module"
},
{
"code": null,
"e": 1471,
"s": 1456,
"text": "python-utility"
},
{
"code": null,
"e": 1478,
"s": 1471,
"text": "Python"
},
{
"code": null,
"e": 1576,
"s": 1478,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1618,
"s": 1576,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1640,
"s": 1618,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1675,
"s": 1640,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1701,
"s": 1675,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1733,
"s": 1701,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1762,
"s": 1733,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1789,
"s": 1762,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1819,
"s": 1789,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 1840,
"s": 1819,
"text": "Python OOPs Concepts"
}
] |
numpy.expand_dims
|
This function expands the array by inserting a new axis at the specified position. Two parameters are required by this function.
numpy.expand_dims(arr, axis)
Where,
arr
Input array
axis
Position where new axis to be inserted
import numpy as np
x = np.array(([1,2],[3,4]))
print 'Array x:'
print x
print '\n'
y = np.expand_dims(x, axis = 0)
print 'Array y:'
print y
print '\n'
print 'The shape of X and Y array:'
print x.shape, y.shape
print '\n'
# insert axis at position 1
y = np.expand_dims(x, axis = 1)
print 'Array Y after inserting axis at position 1:'
print y
print '\n'
print 'x.ndim and y.ndim:'
print x.ndim,y.ndim
print '\n'
print 'x.shape and y.shape:'
print x.shape, y.shape
The output of the above program would be as follows −
Array x:
[[1 2]
[3 4]]
Array y:
[[[1 2]
[3 4]]]
The shape of X and Y array:
(2, 2) (1, 2, 2)
Array Y after inserting axis at position 1:
[[[1 2]]
[[3 4]]]
x.ndim and y.ndim:
2 3
x.shape and y.shape:
(2, 2) (2, 1, 2)
|
[
{
"code": null,
"e": 2506,
"s": 2377,
"text": "This function expands the array by inserting a new axis at the specified position. Two parameters are required by this function."
},
{
"code": null,
"e": 2536,
"s": 2506,
"text": "numpy.expand_dims(arr, axis)\n"
},
{
"code": null,
"e": 2543,
"s": 2536,
"text": "Where,"
},
{
"code": null,
"e": 2547,
"s": 2543,
"text": "arr"
},
{
"code": null,
"e": 2559,
"s": 2547,
"text": "Input array"
},
{
"code": null,
"e": 2564,
"s": 2559,
"text": "axis"
},
{
"code": null,
"e": 2603,
"s": 2564,
"text": "Position where new axis to be inserted"
},
{
"code": null,
"e": 3095,
"s": 2603,
"text": "import numpy as np \nx = np.array(([1,2],[3,4])) \n\nprint 'Array x:' \nprint x \nprint '\\n' \ny = np.expand_dims(x, axis = 0) \n\nprint 'Array y:' \nprint y \nprint '\\n'\n\nprint 'The shape of X and Y array:' \nprint x.shape, y.shape \nprint '\\n' \n# insert axis at position 1 \ny = np.expand_dims(x, axis = 1) \n\nprint 'Array Y after inserting axis at position 1:' \nprint y \nprint '\\n' \n\nprint 'x.ndim and y.ndim:' \nprint x.ndim,y.ndim \nprint '\\n' \n\nprint 'x.shape and y.shape:' \nprint x.shape, y.shape"
},
{
"code": null,
"e": 3149,
"s": 3095,
"text": "The output of the above program would be as follows −"
}
] |
Python | Pandas Series.dt.quarter
|
20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.quarter attribute return the quarter of the date in the underlying datetime based data in the given series object.
Syntax: Series.dt.quarter
Parameter : None
Returns : numpy array
Example #1: Use Series.dt.quarter attribute to return the quarter of the date in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetime sr = pd.to_datetime(sr) # Print the seriesprint(sr)
Output :
Now we will use Series.dt.quarter attribute to return the quarter of the date in the datetime based data in the given series object.
# return the quarter of the dateresult = sr.dt.quarter # print the resultprint(result)
Output :As we can see in the output, the Series.dt.quarter attribute has successfully accessed and returned the quarter of the date in the underlying data of the given series object. Example #2 : Use Series.dt.quarter attribute to return the quarter of the date in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12', periods = 5, freq = 'M')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr)
Output :
Now we will use Series.dt.quarter attribute to return the quarter of the date in the datetime based data in the given series object.
# return the quarter of the dateresult = sr.dt.quarter # print the resultprint(result)
Output :As we can see in the output, the Series.dt.quarter attribute has successfully accessed and returned the quarter of the date in the underlying data of the given series object.
Python pandas-series-datetime
Python-pandas
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
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Mar, 2019"
},
{
"code": null,
"e": 264,
"s": 28,
"text": "Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.quarter attribute return the quarter of the date in the underlying datetime based data in the given series object."
},
{
"code": null,
"e": 290,
"s": 264,
"text": "Syntax: Series.dt.quarter"
},
{
"code": null,
"e": 307,
"s": 290,
"text": "Parameter : None"
},
{
"code": null,
"e": 329,
"s": 307,
"text": "Returns : numpy array"
},
{
"code": null,
"e": 458,
"s": 329,
"text": "Example #1: Use Series.dt.quarter attribute to return the quarter of the date in the underlying data of the given Series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetime sr = pd.to_datetime(sr) # Print the seriesprint(sr)",
"e": 852,
"s": 458,
"text": null
},
{
"code": null,
"e": 861,
"s": 852,
"text": "Output :"
},
{
"code": null,
"e": 994,
"s": 861,
"text": "Now we will use Series.dt.quarter attribute to return the quarter of the date in the datetime based data in the given series object."
},
{
"code": "# return the quarter of the dateresult = sr.dt.quarter # print the resultprint(result)",
"e": 1082,
"s": 994,
"text": null
},
{
"code": null,
"e": 1395,
"s": 1082,
"text": "Output :As we can see in the output, the Series.dt.quarter attribute has successfully accessed and returned the quarter of the date in the underlying data of the given series object. Example #2 : Use Series.dt.quarter attribute to return the quarter of the date in the underlying data of the given Series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12', periods = 5, freq = 'M')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr)",
"e": 1692,
"s": 1395,
"text": null
},
{
"code": null,
"e": 1701,
"s": 1692,
"text": "Output :"
},
{
"code": null,
"e": 1834,
"s": 1701,
"text": "Now we will use Series.dt.quarter attribute to return the quarter of the date in the datetime based data in the given series object."
},
{
"code": "# return the quarter of the dateresult = sr.dt.quarter # print the resultprint(result)",
"e": 1922,
"s": 1834,
"text": null
},
{
"code": null,
"e": 2105,
"s": 1922,
"text": "Output :As we can see in the output, the Series.dt.quarter attribute has successfully accessed and returned the quarter of the date in the underlying data of the given series object."
},
{
"code": null,
"e": 2135,
"s": 2105,
"text": "Python pandas-series-datetime"
},
{
"code": null,
"e": 2149,
"s": 2135,
"text": "Python-pandas"
},
{
"code": null,
"e": 2156,
"s": 2149,
"text": "Python"
},
{
"code": null,
"e": 2254,
"s": 2156,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2272,
"s": 2254,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2314,
"s": 2272,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2336,
"s": 2314,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2371,
"s": 2336,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2397,
"s": 2371,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2429,
"s": 2397,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2458,
"s": 2429,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2485,
"s": 2458,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2515,
"s": 2485,
"text": "Iterate over a list in Python"
}
] |
Node.js Promise Chaining
|
08 Oct, 2021
Promise chaining: Promise chaining is a syntax that allows you to chain together multiple asynchronous tasks in a specific order. This is great for complex code where one asynchronous task needs to be performed after the completion of a different asynchronous task.
To demonstrate promise chaining, the following function will be used to simulate an asynchronous task. In reality, it’s just adding up a couple of numbers, waiting two seconds, and fulfilling the promise with the sum.
Filename: index.js
const add = (a, b) => { return new Promise((resolve, reject) => { setTimeout(() => { if (a < 0 || b < 0) { return reject('Numbers must be non-negative') } resolve(a + b) }, 2000) })} add(1, 2).then((sum) => { console.log(sum) // Print 3 return add(sum, 4)}).then((sum2) => { console.log(sum2) // Print 7 }).catch((e) => { console.log(e) });
Step to run the program:
Run index.js file using below command:node index.js
node index.js
With the dummy asynchronous function defined, promise chaining can be used to call add twice. The code below adds up 1 and 2 for a total of 3. It then uses the sum value 3 as the input for another call to add. The second call to add adds up 3 and 4 for a total of 7.
Promise chaining occurs when the callback function returns a promise. It allows you to chain on another then call which will run when the second promise is fulfilled. Catch can still be called to handle any errors that might occur along the way.
Node.js-Basics
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 294,
"s": 28,
"text": "Promise chaining: Promise chaining is a syntax that allows you to chain together multiple asynchronous tasks in a specific order. This is great for complex code where one asynchronous task needs to be performed after the completion of a different asynchronous task."
},
{
"code": null,
"e": 512,
"s": 294,
"text": "To demonstrate promise chaining, the following function will be used to simulate an asynchronous task. In reality, it’s just adding up a couple of numbers, waiting two seconds, and fulfilling the promise with the sum."
},
{
"code": null,
"e": 531,
"s": 512,
"text": "Filename: index.js"
},
{
"code": "const add = (a, b) => { return new Promise((resolve, reject) => { setTimeout(() => { if (a < 0 || b < 0) { return reject('Numbers must be non-negative') } resolve(a + b) }, 2000) })} add(1, 2).then((sum) => { console.log(sum) // Print 3 return add(sum, 4)}).then((sum2) => { console.log(sum2) // Print 7 }).catch((e) => { console.log(e) });",
"e": 1021,
"s": 531,
"text": null
},
{
"code": null,
"e": 1046,
"s": 1021,
"text": "Step to run the program:"
},
{
"code": null,
"e": 1098,
"s": 1046,
"text": "Run index.js file using below command:node index.js"
},
{
"code": null,
"e": 1112,
"s": 1098,
"text": "node index.js"
},
{
"code": null,
"e": 1379,
"s": 1112,
"text": "With the dummy asynchronous function defined, promise chaining can be used to call add twice. The code below adds up 1 and 2 for a total of 3. It then uses the sum value 3 as the input for another call to add. The second call to add adds up 3 and 4 for a total of 7."
},
{
"code": null,
"e": 1625,
"s": 1379,
"text": "Promise chaining occurs when the callback function returns a promise. It allows you to chain on another then call which will run when the second promise is fulfilled. Catch can still be called to handle any errors that might occur along the way."
},
{
"code": null,
"e": 1640,
"s": 1625,
"text": "Node.js-Basics"
},
{
"code": null,
"e": 1648,
"s": 1640,
"text": "Node.js"
},
{
"code": null,
"e": 1665,
"s": 1648,
"text": "Web Technologies"
}
] |
Java Script | setTimeout() & setInterval() Method
|
10 Jun, 2022
SetTimeout and SetInterval are the only native function in javaScript that is used to run code asynchronously , it means allow the function to executed immediately , there is no need to wait for current execution completion , it will for further to execute.
setTimeout() method The setTimeout() method executes a function, after waiting a specified number of milliseconds.
Syntax:
window.setTimeout(function, milliseconds);
Parameter: There are two parameter that accepted by this method
function : first parameter is a function to be executed
milliseconds : indicates the number of milliseconds before execution takes place.
For example, we want an alert box to pop up, 2 seconds after the user presses the click me button.
Example:
javascript
<!DOCTYPE html><html> <head> <title> HTML | DOM Window setTimeout() method </title></head> <body> <button onclick="setTimeout(gfg, 2000);"> Press me </button> <script> function gfg() { alert('Welcome to GeeksforGeeks'); } </script> </body> </html>
Output: As soon as the user presses the “press me” button, then after a pause of 2 seconds this message alert box will pop up.
setInterval() Method The setInterval() method repeats a given function at every given time-interval.
Syntax:
window.setInterval(function, milliseconds);
Parameter: There are two parameter that accepted by this method
function : first parameter is the function to be executed
milliseconds :indicates the length of the time-interval between each execution.
Example:
javascript
<!DOCTYPE html><html> <head> <title> HTML | DOM Window setTimeout() method </title></head> <body> <p>I will say hi many times</p> <p id="GFG"></p> <script> var myVar = setInterval(myTimer, 1000); function myTimer() { document.getElementById("GFG").innerHTML += "<p>Hi</p>"; } </script> </body></html>
Output: After every second a new “hi” message will be displayed.
Then:
Supported Browser: The browser supported by setTimeout() & setInterval() Method are listed nelow:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
surbhikumaridav
javascript-functions
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
Roadmap to Learn JavaScript For Beginners
How to get character array from string in JavaScript?
How do you run JavaScript script through the Terminal?
JavaScript | console.log() with Examples
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n10 Jun, 2022"
},
{
"code": null,
"e": 311,
"s": 53,
"text": "SetTimeout and SetInterval are the only native function in javaScript that is used to run code asynchronously , it means allow the function to executed immediately , there is no need to wait for current execution completion , it will for further to execute."
},
{
"code": null,
"e": 427,
"s": 311,
"text": "setTimeout() method The setTimeout() method executes a function, after waiting a specified number of milliseconds. "
},
{
"code": null,
"e": 435,
"s": 427,
"text": "Syntax:"
},
{
"code": null,
"e": 478,
"s": 435,
"text": "window.setTimeout(function, milliseconds);"
},
{
"code": null,
"e": 542,
"s": 478,
"text": "Parameter: There are two parameter that accepted by this method"
},
{
"code": null,
"e": 598,
"s": 542,
"text": "function : first parameter is a function to be executed"
},
{
"code": null,
"e": 680,
"s": 598,
"text": "milliseconds : indicates the number of milliseconds before execution takes place."
},
{
"code": null,
"e": 780,
"s": 680,
"text": "For example, we want an alert box to pop up, 2 seconds after the user presses the click me button. "
},
{
"code": null,
"e": 790,
"s": 780,
"text": "Example: "
},
{
"code": null,
"e": 801,
"s": 790,
"text": "javascript"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML | DOM Window setTimeout() method </title></head> <body> <button onclick=\"setTimeout(gfg, 2000);\"> Press me </button> <script> function gfg() { alert('Welcome to GeeksforGeeks'); } </script> </body> </html>",
"e": 1105,
"s": 801,
"text": null
},
{
"code": null,
"e": 1232,
"s": 1105,
"text": "Output: As soon as the user presses the “press me” button, then after a pause of 2 seconds this message alert box will pop up."
},
{
"code": null,
"e": 1337,
"s": 1235,
"text": "setInterval() Method The setInterval() method repeats a given function at every given time-interval. "
},
{
"code": null,
"e": 1345,
"s": 1337,
"text": "Syntax:"
},
{
"code": null,
"e": 1389,
"s": 1345,
"text": "window.setInterval(function, milliseconds);"
},
{
"code": null,
"e": 1453,
"s": 1389,
"text": "Parameter: There are two parameter that accepted by this method"
},
{
"code": null,
"e": 1511,
"s": 1453,
"text": "function : first parameter is the function to be executed"
},
{
"code": null,
"e": 1591,
"s": 1511,
"text": "milliseconds :indicates the length of the time-interval between each execution."
},
{
"code": null,
"e": 1601,
"s": 1591,
"text": "Example: "
},
{
"code": null,
"e": 1612,
"s": 1601,
"text": "javascript"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML | DOM Window setTimeout() method </title></head> <body> <p>I will say hi many times</p> <p id=\"GFG\"></p> <script> var myVar = setInterval(myTimer, 1000); function myTimer() { document.getElementById(\"GFG\").innerHTML += \"<p>Hi</p>\"; } </script> </body></html>",
"e": 2017,
"s": 1612,
"text": null
},
{
"code": null,
"e": 2082,
"s": 2017,
"text": "Output: After every second a new “hi” message will be displayed."
},
{
"code": null,
"e": 2091,
"s": 2085,
"text": "Then:"
},
{
"code": null,
"e": 2192,
"s": 2094,
"text": "Supported Browser: The browser supported by setTimeout() & setInterval() Method are listed nelow:"
},
{
"code": null,
"e": 2206,
"s": 2192,
"text": "Google Chrome"
},
{
"code": null,
"e": 2224,
"s": 2206,
"text": "Internet Explorer"
},
{
"code": null,
"e": 2232,
"s": 2224,
"text": "Firefox"
},
{
"code": null,
"e": 2238,
"s": 2232,
"text": "Opera"
},
{
"code": null,
"e": 2245,
"s": 2238,
"text": "Safari"
},
{
"code": null,
"e": 2261,
"s": 2245,
"text": "surbhikumaridav"
},
{
"code": null,
"e": 2282,
"s": 2261,
"text": "javascript-functions"
},
{
"code": null,
"e": 2293,
"s": 2282,
"text": "JavaScript"
},
{
"code": null,
"e": 2391,
"s": 2293,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2452,
"s": 2391,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2524,
"s": 2452,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2564,
"s": 2524,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2616,
"s": 2564,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 2657,
"s": 2616,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2703,
"s": 2657,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 2745,
"s": 2703,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2799,
"s": 2745,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 2854,
"s": 2799,
"text": "How do you run JavaScript script through the Terminal?"
}
] |
Python – sys.stdout.flush()
|
21 Apr, 2020
A data buffer is a region of physical memory storage used to temporarily store data while it is being moved from one place to another. The data is stored in a buffer as it is retrieved from an input device or just before it is sent to an output device or when moving data between processes within a computer. Python’s standard out is buffered. This means that it collects some data before it is written to standard out and when the buffer gets filled, then it is written on the terminal or any other output stream.
Let’s look at the code below :
# Python3 program demonstrating working # of flush during output import sysimport time for i in range(10): print(i) time.sleep(1)
Output:
0
1
2
3
4
5
6
7
8
9
When the above program is executed, then the numbers from 0 to 9 are printed after every second on a new line, i.e., the output is automatically flushed out. This is because, by default end parameter of print statement is set to ‘\n’ which flushes the output.
Now let’s look at the code below :
# Python3 program demonstrating working # of flush during output import sysimport time for i in range(10): print(i, end =' ') time.sleep(1)
Output:
0 1 2 3 4 5 6 7 8 9
When the above program is executed, then there is no output for the first 9 seconds, then at the 10th, all the 10 numbers from 0 to 9 appear simultaneously in a line separated by spaces. This is because the output is buffered and it is not flushed by any means.
Now, look at the code below :
# Python3 program demonstrating working # of flush during output and usage of# sys.stdout.flush() function import sysimport time for i in range(10): print(i, end =' ') sys.stdout.flush() time.sleep(1)
Output:
0 1 2 3 4 5 6 7 8 9
When the above program is executed, the numbers from 0 to 9 are printed every second on the same line separated by spaces. This is because calling sys.stdout.flush() forces it to “flush” the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so. The sys module provides functions and variables used to manipulate different parts of the Python runtime environment. It lets us access system-specific parameters and functions.
Another way of achieving the same functionality as above is setting the flush parameter of the print statement to true.
# Python3 program demonstrating working # of flush during output and usage of# flush parameter of print statement import sysimport time for i in range(10): print(i, end =' ', flush = True) time.sleep(1)
Output:
0 1 2 3 4 5 6 7 8 9
Python-sys
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 567,
"s": 52,
"text": "A data buffer is a region of physical memory storage used to temporarily store data while it is being moved from one place to another. The data is stored in a buffer as it is retrieved from an input device or just before it is sent to an output device or when moving data between processes within a computer. Python’s standard out is buffered. This means that it collects some data before it is written to standard out and when the buffer gets filled, then it is written on the terminal or any other output stream."
},
{
"code": null,
"e": 598,
"s": 567,
"text": "Let’s look at the code below :"
},
{
"code": "# Python3 program demonstrating working # of flush during output import sysimport time for i in range(10): print(i) time.sleep(1)",
"e": 738,
"s": 598,
"text": null
},
{
"code": null,
"e": 746,
"s": 738,
"text": "Output:"
},
{
"code": null,
"e": 766,
"s": 746,
"text": "0\n1\n2\n3\n4\n5\n6\n7\n8\n9"
},
{
"code": null,
"e": 1026,
"s": 766,
"text": "When the above program is executed, then the numbers from 0 to 9 are printed after every second on a new line, i.e., the output is automatically flushed out. This is because, by default end parameter of print statement is set to ‘\\n’ which flushes the output."
},
{
"code": null,
"e": 1061,
"s": 1026,
"text": "Now let’s look at the code below :"
},
{
"code": "# Python3 program demonstrating working # of flush during output import sysimport time for i in range(10): print(i, end =' ') time.sleep(1)",
"e": 1209,
"s": 1061,
"text": null
},
{
"code": null,
"e": 1217,
"s": 1209,
"text": "Output:"
},
{
"code": null,
"e": 1237,
"s": 1217,
"text": "0 1 2 3 4 5 6 7 8 9"
},
{
"code": null,
"e": 1499,
"s": 1237,
"text": "When the above program is executed, then there is no output for the first 9 seconds, then at the 10th, all the 10 numbers from 0 to 9 appear simultaneously in a line separated by spaces. This is because the output is buffered and it is not flushed by any means."
},
{
"code": null,
"e": 1529,
"s": 1499,
"text": "Now, look at the code below :"
},
{
"code": "# Python3 program demonstrating working # of flush during output and usage of# sys.stdout.flush() function import sysimport time for i in range(10): print(i, end =' ') sys.stdout.flush() time.sleep(1)",
"e": 1741,
"s": 1529,
"text": null
},
{
"code": null,
"e": 1749,
"s": 1741,
"text": "Output:"
},
{
"code": null,
"e": 1769,
"s": 1749,
"text": "0 1 2 3 4 5 6 7 8 9"
},
{
"code": null,
"e": 2263,
"s": 1769,
"text": "When the above program is executed, the numbers from 0 to 9 are printed every second on the same line separated by spaces. This is because calling sys.stdout.flush() forces it to “flush” the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so. The sys module provides functions and variables used to manipulate different parts of the Python runtime environment. It lets us access system-specific parameters and functions."
},
{
"code": null,
"e": 2383,
"s": 2263,
"text": "Another way of achieving the same functionality as above is setting the flush parameter of the print statement to true."
},
{
"code": "# Python3 program demonstrating working # of flush during output and usage of# flush parameter of print statement import sysimport time for i in range(10): print(i, end =' ', flush = True) time.sleep(1)",
"e": 2594,
"s": 2383,
"text": null
},
{
"code": null,
"e": 2602,
"s": 2594,
"text": "Output:"
},
{
"code": null,
"e": 2623,
"s": 2602,
"text": "0 1 2 3 4 5 6 7 8 9 "
},
{
"code": null,
"e": 2634,
"s": 2623,
"text": "Python-sys"
},
{
"code": null,
"e": 2649,
"s": 2634,
"text": "python-utility"
},
{
"code": null,
"e": 2656,
"s": 2649,
"text": "Python"
}
] |
Find Nth term (A matrix exponentiation example)
|
27 May, 2021
We are given a recursive function that describes Nth terms in the form of other terms. In this article, we have taken specific examples. Now you are given n, and you have to find out nth term using the above formula.
Examples:
Input : n = 2
Output : 5
Input : n = 3
Output :13
Prerequisite : Basic Approach: This problem can be solved by simply just iterating over the n terms. Every time you find a term, using this term find the next one, and so on. But the time complexity of this problem is of order O(n).
Optimized Approach All such problems where a term is a function of other terms in a linear fashion. Then these can be solved using the Matrix (Please refer: Matrix Exponentiation ). First, we make a transformation matrix and then just use matrix exponentiation to find the Nth term.
Step by Step method includes:
Step 1. Determine k the number of terms on which T(i) depends. For our example, T(i) depends on two terms. So, k = 2
Step 2. Determine initial values As in this article T0=1, T1=1 are given.
Step 3. Determine TM, the transformation matrix. This is the most important step in solving recurrence relations. In this step, we have to make the matrix of dimension k*k. Such that T(i)=TM*(initial value vector)
Here initial value vector is the vector that contains an initial value. We name this vector as initial.
Below is the program to implement the above approach.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find n-th term of a recursive// function using matrix exponentiation.#include <bits/stdc++.h>using namespace std;#define MOD 1000000009 #define ll long long int ll power(ll n){ if (n <= 1) return 1; // This power function returns first row of // {Transformation Matrix}^n-1*Initial Vector n--; // This is an identity matrix. ll res[2][2] = { 1, 0, 0, 1 }; // this is Transformation matrix. ll tMat[2][2] = { 2, 3, 1, 0 }; // Matrix exponentiation to calculate power of {tMat}^n-1 // store res in "res" matrix. while (n) { if (n & 1) { ll tmp[2][2]; tmp[0][0] = (res[0][0] * tMat[0][0] + res[0][1] * tMat[1][0]) % MOD; tmp[0][1] = (res[0][0] * tMat[0][1] + res[0][1] * tMat[1][1]) % MOD; tmp[1][0] = (res[1][0] * tMat[0][0] + res[1][1] * tMat[1][0]) % MOD; tmp[1][1] = (res[1][0] * tMat[0][1] + res[1][1] * tMat[1][1]) % MOD; res[0][0] = tmp[0][0]; res[0][1] = tmp[0][1]; res[1][0] = tmp[1][0]; res[1][1] = tmp[1][1]; } n = n / 2; ll tmp[2][2]; tmp[0][0] = (tMat[0][0] * tMat[0][0] + tMat[0][1] * tMat[1][0]) % MOD; tmp[0][1] = (tMat[0][0] * tMat[0][1] + tMat[0][1] * tMat[1][1]) % MOD; tmp[1][0] = (tMat[1][0] * tMat[0][0] + tMat[1][1] * tMat[1][0]) % MOD; tmp[1][1] = (tMat[1][0] * tMat[0][1] + tMat[1][1] * tMat[1][1]) % MOD; tMat[0][0] = tmp[0][0]; tMat[0][1] = tmp[0][1]; tMat[1][0] = tmp[1][0]; tMat[1][1] = tmp[1][1]; } // res store {Transformation matrix}^n-1 // hence will be first row of res*Initial Vector. return (res[0][0] * 1 + res[0][1] * 1) % MOD;} // Driver codeint main(){ ll n = 3; cout << power(n); return 0;}
// Java program to find n-th term of a recursive// function using matrix exponentiation.class GfG { static int MAX = 100; static int MOD = 1000000009; static int power(int n) { if (n <= 1) { return 1; } // This power function returns first row of // {Transformation Matrix}^n-1*Initial Vector n--; // This is an identity matrix. int res[][] = { { 1, 0 }, { 0, 1 } }; // this is Transformation matrix. int tMat[][] = { { 2, 3 }, { 1, 0 } }; // Matrix exponentiation to calculate power of {tMat}^n-1 // store res in "res" matrix. while (n > 0) { if (n % 2 == 1) { int tmp[][] = new int[2][2]; tmp[0][0] = (res[0][0] * tMat[0][0] + res[0][1] * tMat[1][0]) % MOD; tmp[0][1] = (res[0][0] * tMat[0][1] + res[0][1] * tMat[1][1]) % MOD; tmp[1][0] = (res[1][0] * tMat[0][0] + res[1][1] * tMat[1][0]) % MOD; tmp[1][1] = (res[1][0] * tMat[0][1] + res[1][1] * tMat[1][1]) % MOD; res[0][0] = tmp[0][0]; res[0][1] = tmp[0][1]; res[1][0] = tmp[1][0]; res[1][1] = tmp[1][1]; } n = n / 2; int tmp[][] = new int[2][2]; tmp[0][0] = (tMat[0][0] * tMat[0][0] + tMat[0][1] * tMat[1][0]) % MOD; tmp[0][1] = (tMat[0][0] * tMat[0][1] + tMat[0][1] * tMat[1][1]) % MOD; tmp[1][0] = (tMat[1][0] * tMat[0][0] + tMat[1][1] * tMat[1][0]) % MOD; tmp[1][1] = (tMat[1][0] * tMat[0][1] + tMat[1][1] * tMat[1][1]) % MOD; tMat[0][0] = tmp[0][0]; tMat[0][1] = tmp[0][1]; tMat[1][0] = tmp[1][0]; tMat[1][1] = tmp[1][1]; } // res store {Transformation matrix}^n-1 // hence wiint be first row of res*Initial Vector. return (res[0][0] * 1 + res[0][1] * 1) % MOD; } // Driver code public static void main(String[] args) { int n = 3; System.out.println(power(n)); }} // This code contributed by Rajput-Ji
# Python3 program to find n-th term of a recursive# function using matrix exponentiation.MOD = 1000000009; def power(n): if (n <= 1): return 1; # This power function returns first row of # {Transformation Matrix}^n-1 * Initial Vector n-= 1; # This is an identity matrix. res = [[1, 0], [0, 1]]; # this is Transformation matrix. tMat = [[2, 3], [1, 0]]; # Matrix exponentiation to calculate # power of {tMat}^n-1 store res in "res" matrix. while (n): if (n & 1): tmp = [[0 for x in range(2)] for y in range(2)]; tmp[0][0] = (res[0][0] * tMat[0][0] + res[0][1] * tMat[1][0]) % MOD; tmp[0][1] = (res[0][0] * tMat[0][1] + res[0][1] * tMat[1][1]) % MOD; tmp[1][0] = (res[1][0] * tMat[0][0] + res[1][1] * tMat[1][0]) % MOD; tmp[1][1] = (res[1][0] * tMat[0][1] + res[1][1] * tMat[1][1]) % MOD; res[0][0] = tmp[0][0]; res[0][1] = tmp[0][1]; res[1][0] = tmp[1][0]; res[1][1] = tmp[1][1]; n = n // 2; tmp = [[0 for x in range(2)] for y in range(2)]; tmp[0][0] = (tMat[0][0] * tMat[0][0] + tMat[0][1] * tMat[1][0]) % MOD; tmp[0][1] = (tMat[0][0] * tMat[0][1] + tMat[0][1] * tMat[1][1]) % MOD; tmp[1][0] = (tMat[1][0] * tMat[0][0] + tMat[1][1] * tMat[1][0]) % MOD; tmp[1][1] = (tMat[1][0] * tMat[0][1] + tMat[1][1] * tMat[1][1]) % MOD; tMat[0][0] = tmp[0][0]; tMat[0][1] = tmp[0][1]; tMat[1][0] = tmp[1][0]; tMat[1][1] = tmp[1][1]; # res store {Transformation matrix}^n-1 # hence will be first row of res * Initial Vector. return (res[0][0] * 1 + res[0][1] * 1) % MOD; # Driver coden = 3;print(power(n)); # This code is contributed by mits
// C# program to find n-th term of a recursive// function using matrix exponentiation.using System; class GfG { // static int MAX = 100; static int MOD = 1000000009; static int power(int n) { if (n <= 1) { return 1; } // This power function returns first row of // {Transformation Matrix}^n-1*Initial Vector n--; // This is an identity matrix. int[, ] res = { { 1, 0 }, { 0, 1 } }; // this is Transformation matrix. int[, ] tMat = { { 2, 3 }, { 1, 0 } }; // Matrix exponentiation to calculate power of {tMat}^n-1 // store res in "res" matrix. while (n > 0) { if (n % 2 == 1) { int[, ] tmp = new int[2, 2]; tmp[0, 0] = (res[0, 0] * tMat[0, 0] + res[0, 1] * tMat[1, 0]) % MOD; tmp[0, 1] = (res[0, 0] * tMat[0, 1] + res[0, 1] * tMat[1, 1]) % MOD; tmp[1, 0] = (res[1, 0] * tMat[0, 0] + res[1, 1] * tMat[1, 0]) % MOD; tmp[1, 1] = (res[1, 0] * tMat[0, 1] + res[1, 1] * tMat[1, 1]) % MOD; res[0, 0] = tmp[0, 0]; res[0, 1] = tmp[0, 1]; res[1, 0] = tmp[1, 0]; res[1, 1] = tmp[1, 1]; } n = n / 2; int[, ] tmp1 = new int[2, 2]; tmp1[0, 0] = (tMat[0, 0] * tMat[0, 0] + tMat[0, 1] * tMat[1, 0]) % MOD; tmp1[0, 1] = (tMat[0, 0] * tMat[0, 1] + tMat[0, 1] * tMat[1, 1]) % MOD; tmp1[1, 0] = (tMat[1, 0] * tMat[0, 0] + tMat[1, 1] * tMat[1, 0]) % MOD; tmp1[1, 1] = (tMat[1, 0] * tMat[0, 1] + tMat[1, 1] * tMat[1, 1]) % MOD; tMat[0, 0] = tmp1[0, 0]; tMat[0, 1] = tmp1[0, 1]; tMat[1, 0] = tmp1[1, 0]; tMat[1, 1] = tmp1[1, 1]; } // res store {Transformation matrix}^n-1 // hence wiint be first row of res*Initial Vector. return (res[0, 0] * 1 + res[0, 1] * 1) % MOD; } // Driver code public static void Main() { int n = 3; Console.WriteLine(power(n)); }} // This code contributed by mits
<?php// PHP program to find n-th term of a recursive// function using matrix exponentiation.$MOD = 1000000009; function power($n){ global $MOD; if ($n <= 1) return 1; // This power function returns first row of // {Transformation Matrix}^n-1*Initial Vector $n--; // This is an identity matrix. $res = array(array(1, 0), array(0, 1)); // this is Transformation matrix. $tMat= array(array(2, 3), array(1, 0)); // Matrix exponentiation to calculate // power of {tMat}^n-1 store res in "res" matrix. while ($n) { if ($n & 1) { $tmp = array_fill(0, 2, array_fill(0, 2, 0)); $tmp[0][0] = ($res[0][0] * $tMat[0][0] + $res[0][1] * $tMat[1][0]) % $MOD; $tmp[0][1] = ($res[0][0] * $tMat[0][1] + $res[0][1] * $tMat[1][1]) % $MOD; $tmp[1][0] = ($res[1][0] * $tMat[0][0] + $res[1][1] * $tMat[1][0]) % $MOD; $tmp[1][1] = ($res[1][0] * $tMat[0][1] + $res[1][1] * $tMat[1][1]) % $MOD; $res[0][0] = $tmp[0][0]; $res[0][1] = $tmp[0][1]; $res[1][0] = $tmp[1][0]; $res[1][1] = $tmp[1][1]; } $n = (int)($n / 2); $tmp = array_fill(0, 2, array_fill(0, 2, 0)); $tmp[0][0] = ($tMat[0][0] * $tMat[0][0] + $tMat[0][1] * $tMat[1][0]) % $MOD; $tmp[0][1] = ($tMat[0][0] * $tMat[0][1] + $tMat[0][1] * $tMat[1][1]) % $MOD; $tmp[1][0] = ($tMat[1][0] * $tMat[0][0] + $tMat[1][1] * $tMat[1][0]) % $MOD; $tmp[1][1] = ($tMat[1][0] * $tMat[0][1] + $tMat[1][1] * $tMat[1][1]) % $MOD; $tMat[0][0] = $tmp[0][0]; $tMat[0][1] = $tmp[0][1]; $tMat[1][0] = $tmp[1][0]; $tMat[1][1] = $tmp[1][1]; } // res store {Transformation matrix}^n-1 // hence will be first row of res*Initial Vector. return ($res[0][0] * 1 + $res[0][1] * 1) % $MOD;} // Driver code$n = 3;echo power($n); // This code is contributed by mits?>
<script> // Javascript program to find n-th term of a recursive// function using matrix exponentiation.var MOD = 1000000009; function power(n){ if (n <= 1) return 1; // This power function returns first row of // {Transformation Matrix}^n-1*Initial Vector n--; // This is an identity matrix. var res = [[1, 0,], [0, 1]]; // this is Transformation matrix. var tMat = [[2, 3],[1, 0]]; // Matrix exponentiation to calculate power of {tMat}^n-1 // store res in "res" matrix. while (n) { if (n & 1) { var tmp = Array.from(Array(2), ()=> Array(2)); tmp[0][0] = (res[0][0] * tMat[0][0] + res[0][1] * tMat[1][0]) % MOD; tmp[0][1] = (res[0][0] * tMat[0][1] + res[0][1] * tMat[1][1]) % MOD; tmp[1][0] = (res[1][0] * tMat[0][0] + res[1][1] * tMat[1][0]) % MOD; tmp[1][1] = (res[1][0] * tMat[0][1] + res[1][1] * tMat[1][1]) % MOD; res[0][0] = tmp[0][0]; res[0][1] = tmp[0][1]; res[1][0] = tmp[1][0]; res[1][1] = tmp[1][1]; } n = parseInt(n / 2); var tmp = Array.from(Array(2), ()=> Array(2)); tmp[0][0] = (tMat[0][0] * tMat[0][0] + tMat[0][1] * tMat[1][0]) % MOD; tmp[0][1] = (tMat[0][0] * tMat[0][1] + tMat[0][1] * tMat[1][1]) % MOD; tmp[1][0] = (tMat[1][0] * tMat[0][0] + tMat[1][1] * tMat[1][0]) % MOD; tmp[1][1] = (tMat[1][0] * tMat[0][1] + tMat[1][1] * tMat[1][1]) % MOD; tMat[0][0] = tmp[0][0]; tMat[0][1] = tmp[0][1]; tMat[1][0] = tmp[1][0]; tMat[1][1] = tmp[1][1]; } // res store {Transformation matrix}^n-1 // hence will be first row of res*Initial Vector. return (res[0][0] * 1 + res[0][1] * 1) % MOD;} // Driver codevar n = 3;document.write( power(n)); </script>
13
Time Complexity : O(Log n)The same idea is used to find n-th Fibonacci number in O(Log n)
Rajput-Ji
Mithun Kumar
rutvik_56
matrix-exponentiation
Competitive Programming
Divide and Conquer
Matrix
Recursion
Recursion
Divide and Conquer
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Most important type of Algorithms
The Ultimate Beginner's Guide For DSA
Find two numbers from their sum and XOR
Equal Sum and XOR of three Numbers
C++: Methods of code shortening in competitive programming
Merge Sort
QuickSort
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Count Inversions in an array | Set 1 (Using Merge Sort)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 May, 2021"
},
{
"code": null,
"e": 269,
"s": 52,
"text": "We are given a recursive function that describes Nth terms in the form of other terms. In this article, we have taken specific examples. Now you are given n, and you have to find out nth term using the above formula."
},
{
"code": null,
"e": 280,
"s": 269,
"text": "Examples: "
},
{
"code": null,
"e": 332,
"s": 280,
"text": "Input : n = 2\nOutput : 5\n\nInput : n = 3\nOutput :13 "
},
{
"code": null,
"e": 565,
"s": 332,
"text": "Prerequisite : Basic Approach: This problem can be solved by simply just iterating over the n terms. Every time you find a term, using this term find the next one, and so on. But the time complexity of this problem is of order O(n)."
},
{
"code": null,
"e": 850,
"s": 565,
"text": "Optimized Approach All such problems where a term is a function of other terms in a linear fashion. Then these can be solved using the Matrix (Please refer: Matrix Exponentiation ). First, we make a transformation matrix and then just use matrix exponentiation to find the Nth term. "
},
{
"code": null,
"e": 881,
"s": 850,
"text": "Step by Step method includes: "
},
{
"code": null,
"e": 998,
"s": 881,
"text": "Step 1. Determine k the number of terms on which T(i) depends. For our example, T(i) depends on two terms. So, k = 2"
},
{
"code": null,
"e": 1072,
"s": 998,
"text": "Step 2. Determine initial values As in this article T0=1, T1=1 are given."
},
{
"code": null,
"e": 1286,
"s": 1072,
"text": "Step 3. Determine TM, the transformation matrix. This is the most important step in solving recurrence relations. In this step, we have to make the matrix of dimension k*k. Such that T(i)=TM*(initial value vector)"
},
{
"code": null,
"e": 1391,
"s": 1286,
"text": "Here initial value vector is the vector that contains an initial value. We name this vector as initial. "
},
{
"code": null,
"e": 1446,
"s": 1391,
"text": "Below is the program to implement the above approach. "
},
{
"code": null,
"e": 1450,
"s": 1446,
"text": "C++"
},
{
"code": null,
"e": 1455,
"s": 1450,
"text": "Java"
},
{
"code": null,
"e": 1463,
"s": 1455,
"text": "Python3"
},
{
"code": null,
"e": 1466,
"s": 1463,
"text": "C#"
},
{
"code": null,
"e": 1470,
"s": 1466,
"text": "PHP"
},
{
"code": null,
"e": 1481,
"s": 1470,
"text": "Javascript"
},
{
"code": "// CPP program to find n-th term of a recursive// function using matrix exponentiation.#include <bits/stdc++.h>using namespace std;#define MOD 1000000009 #define ll long long int ll power(ll n){ if (n <= 1) return 1; // This power function returns first row of // {Transformation Matrix}^n-1*Initial Vector n--; // This is an identity matrix. ll res[2][2] = { 1, 0, 0, 1 }; // this is Transformation matrix. ll tMat[2][2] = { 2, 3, 1, 0 }; // Matrix exponentiation to calculate power of {tMat}^n-1 // store res in \"res\" matrix. while (n) { if (n & 1) { ll tmp[2][2]; tmp[0][0] = (res[0][0] * tMat[0][0] + res[0][1] * tMat[1][0]) % MOD; tmp[0][1] = (res[0][0] * tMat[0][1] + res[0][1] * tMat[1][1]) % MOD; tmp[1][0] = (res[1][0] * tMat[0][0] + res[1][1] * tMat[1][0]) % MOD; tmp[1][1] = (res[1][0] * tMat[0][1] + res[1][1] * tMat[1][1]) % MOD; res[0][0] = tmp[0][0]; res[0][1] = tmp[0][1]; res[1][0] = tmp[1][0]; res[1][1] = tmp[1][1]; } n = n / 2; ll tmp[2][2]; tmp[0][0] = (tMat[0][0] * tMat[0][0] + tMat[0][1] * tMat[1][0]) % MOD; tmp[0][1] = (tMat[0][0] * tMat[0][1] + tMat[0][1] * tMat[1][1]) % MOD; tmp[1][0] = (tMat[1][0] * tMat[0][0] + tMat[1][1] * tMat[1][0]) % MOD; tmp[1][1] = (tMat[1][0] * tMat[0][1] + tMat[1][1] * tMat[1][1]) % MOD; tMat[0][0] = tmp[0][0]; tMat[0][1] = tmp[0][1]; tMat[1][0] = tmp[1][0]; tMat[1][1] = tmp[1][1]; } // res store {Transformation matrix}^n-1 // hence will be first row of res*Initial Vector. return (res[0][0] * 1 + res[0][1] * 1) % MOD;} // Driver codeint main(){ ll n = 3; cout << power(n); return 0;}",
"e": 3278,
"s": 1481,
"text": null
},
{
"code": "// Java program to find n-th term of a recursive// function using matrix exponentiation.class GfG { static int MAX = 100; static int MOD = 1000000009; static int power(int n) { if (n <= 1) { return 1; } // This power function returns first row of // {Transformation Matrix}^n-1*Initial Vector n--; // This is an identity matrix. int res[][] = { { 1, 0 }, { 0, 1 } }; // this is Transformation matrix. int tMat[][] = { { 2, 3 }, { 1, 0 } }; // Matrix exponentiation to calculate power of {tMat}^n-1 // store res in \"res\" matrix. while (n > 0) { if (n % 2 == 1) { int tmp[][] = new int[2][2]; tmp[0][0] = (res[0][0] * tMat[0][0] + res[0][1] * tMat[1][0]) % MOD; tmp[0][1] = (res[0][0] * tMat[0][1] + res[0][1] * tMat[1][1]) % MOD; tmp[1][0] = (res[1][0] * tMat[0][0] + res[1][1] * tMat[1][0]) % MOD; tmp[1][1] = (res[1][0] * tMat[0][1] + res[1][1] * tMat[1][1]) % MOD; res[0][0] = tmp[0][0]; res[0][1] = tmp[0][1]; res[1][0] = tmp[1][0]; res[1][1] = tmp[1][1]; } n = n / 2; int tmp[][] = new int[2][2]; tmp[0][0] = (tMat[0][0] * tMat[0][0] + tMat[0][1] * tMat[1][0]) % MOD; tmp[0][1] = (tMat[0][0] * tMat[0][1] + tMat[0][1] * tMat[1][1]) % MOD; tmp[1][0] = (tMat[1][0] * tMat[0][0] + tMat[1][1] * tMat[1][0]) % MOD; tmp[1][1] = (tMat[1][0] * tMat[0][1] + tMat[1][1] * tMat[1][1]) % MOD; tMat[0][0] = tmp[0][0]; tMat[0][1] = tmp[0][1]; tMat[1][0] = tmp[1][0]; tMat[1][1] = tmp[1][1]; } // res store {Transformation matrix}^n-1 // hence wiint be first row of res*Initial Vector. return (res[0][0] * 1 + res[0][1] * 1) % MOD; } // Driver code public static void main(String[] args) { int n = 3; System.out.println(power(n)); }} // This code contributed by Rajput-Ji",
"e": 5787,
"s": 3278,
"text": null
},
{
"code": "# Python3 program to find n-th term of a recursive# function using matrix exponentiation.MOD = 1000000009; def power(n): if (n <= 1): return 1; # This power function returns first row of # {Transformation Matrix}^n-1 * Initial Vector n-= 1; # This is an identity matrix. res = [[1, 0], [0, 1]]; # this is Transformation matrix. tMat = [[2, 3], [1, 0]]; # Matrix exponentiation to calculate # power of {tMat}^n-1 store res in \"res\" matrix. while (n): if (n & 1): tmp = [[0 for x in range(2)] for y in range(2)]; tmp[0][0] = (res[0][0] * tMat[0][0] + res[0][1] * tMat[1][0]) % MOD; tmp[0][1] = (res[0][0] * tMat[0][1] + res[0][1] * tMat[1][1]) % MOD; tmp[1][0] = (res[1][0] * tMat[0][0] + res[1][1] * tMat[1][0]) % MOD; tmp[1][1] = (res[1][0] * tMat[0][1] + res[1][1] * tMat[1][1]) % MOD; res[0][0] = tmp[0][0]; res[0][1] = tmp[0][1]; res[1][0] = tmp[1][0]; res[1][1] = tmp[1][1]; n = n // 2; tmp = [[0 for x in range(2)] for y in range(2)]; tmp[0][0] = (tMat[0][0] * tMat[0][0] + tMat[0][1] * tMat[1][0]) % MOD; tmp[0][1] = (tMat[0][0] * tMat[0][1] + tMat[0][1] * tMat[1][1]) % MOD; tmp[1][0] = (tMat[1][0] * tMat[0][0] + tMat[1][1] * tMat[1][0]) % MOD; tmp[1][1] = (tMat[1][0] * tMat[0][1] + tMat[1][1] * tMat[1][1]) % MOD; tMat[0][0] = tmp[0][0]; tMat[0][1] = tmp[0][1]; tMat[1][0] = tmp[1][0]; tMat[1][1] = tmp[1][1]; # res store {Transformation matrix}^n-1 # hence will be first row of res * Initial Vector. return (res[0][0] * 1 + res[0][1] * 1) % MOD; # Driver coden = 3;print(power(n)); # This code is contributed by mits",
"e": 7722,
"s": 5787,
"text": null
},
{
"code": "// C# program to find n-th term of a recursive// function using matrix exponentiation.using System; class GfG { // static int MAX = 100; static int MOD = 1000000009; static int power(int n) { if (n <= 1) { return 1; } // This power function returns first row of // {Transformation Matrix}^n-1*Initial Vector n--; // This is an identity matrix. int[, ] res = { { 1, 0 }, { 0, 1 } }; // this is Transformation matrix. int[, ] tMat = { { 2, 3 }, { 1, 0 } }; // Matrix exponentiation to calculate power of {tMat}^n-1 // store res in \"res\" matrix. while (n > 0) { if (n % 2 == 1) { int[, ] tmp = new int[2, 2]; tmp[0, 0] = (res[0, 0] * tMat[0, 0] + res[0, 1] * tMat[1, 0]) % MOD; tmp[0, 1] = (res[0, 0] * tMat[0, 1] + res[0, 1] * tMat[1, 1]) % MOD; tmp[1, 0] = (res[1, 0] * tMat[0, 0] + res[1, 1] * tMat[1, 0]) % MOD; tmp[1, 1] = (res[1, 0] * tMat[0, 1] + res[1, 1] * tMat[1, 1]) % MOD; res[0, 0] = tmp[0, 0]; res[0, 1] = tmp[0, 1]; res[1, 0] = tmp[1, 0]; res[1, 1] = tmp[1, 1]; } n = n / 2; int[, ] tmp1 = new int[2, 2]; tmp1[0, 0] = (tMat[0, 0] * tMat[0, 0] + tMat[0, 1] * tMat[1, 0]) % MOD; tmp1[0, 1] = (tMat[0, 0] * tMat[0, 1] + tMat[0, 1] * tMat[1, 1]) % MOD; tmp1[1, 0] = (tMat[1, 0] * tMat[0, 0] + tMat[1, 1] * tMat[1, 0]) % MOD; tmp1[1, 1] = (tMat[1, 0] * tMat[0, 1] + tMat[1, 1] * tMat[1, 1]) % MOD; tMat[0, 0] = tmp1[0, 0]; tMat[0, 1] = tmp1[0, 1]; tMat[1, 0] = tmp1[1, 0]; tMat[1, 1] = tmp1[1, 1]; } // res store {Transformation matrix}^n-1 // hence wiint be first row of res*Initial Vector. return (res[0, 0] * 1 + res[0, 1] * 1) % MOD; } // Driver code public static void Main() { int n = 3; Console.WriteLine(power(n)); }} // This code contributed by mits",
"e": 10244,
"s": 7722,
"text": null
},
{
"code": "<?php// PHP program to find n-th term of a recursive// function using matrix exponentiation.$MOD = 1000000009; function power($n){ global $MOD; if ($n <= 1) return 1; // This power function returns first row of // {Transformation Matrix}^n-1*Initial Vector $n--; // This is an identity matrix. $res = array(array(1, 0), array(0, 1)); // this is Transformation matrix. $tMat= array(array(2, 3), array(1, 0)); // Matrix exponentiation to calculate // power of {tMat}^n-1 store res in \"res\" matrix. while ($n) { if ($n & 1) { $tmp = array_fill(0, 2, array_fill(0, 2, 0)); $tmp[0][0] = ($res[0][0] * $tMat[0][0] + $res[0][1] * $tMat[1][0]) % $MOD; $tmp[0][1] = ($res[0][0] * $tMat[0][1] + $res[0][1] * $tMat[1][1]) % $MOD; $tmp[1][0] = ($res[1][0] * $tMat[0][0] + $res[1][1] * $tMat[1][0]) % $MOD; $tmp[1][1] = ($res[1][0] * $tMat[0][1] + $res[1][1] * $tMat[1][1]) % $MOD; $res[0][0] = $tmp[0][0]; $res[0][1] = $tmp[0][1]; $res[1][0] = $tmp[1][0]; $res[1][1] = $tmp[1][1]; } $n = (int)($n / 2); $tmp = array_fill(0, 2, array_fill(0, 2, 0)); $tmp[0][0] = ($tMat[0][0] * $tMat[0][0] + $tMat[0][1] * $tMat[1][0]) % $MOD; $tmp[0][1] = ($tMat[0][0] * $tMat[0][1] + $tMat[0][1] * $tMat[1][1]) % $MOD; $tmp[1][0] = ($tMat[1][0] * $tMat[0][0] + $tMat[1][1] * $tMat[1][0]) % $MOD; $tmp[1][1] = ($tMat[1][0] * $tMat[0][1] + $tMat[1][1] * $tMat[1][1]) % $MOD; $tMat[0][0] = $tmp[0][0]; $tMat[0][1] = $tmp[0][1]; $tMat[1][0] = $tmp[1][0]; $tMat[1][1] = $tmp[1][1]; } // res store {Transformation matrix}^n-1 // hence will be first row of res*Initial Vector. return ($res[0][0] * 1 + $res[0][1] * 1) % $MOD;} // Driver code$n = 3;echo power($n); // This code is contributed by mits?>",
"e": 12352,
"s": 10244,
"text": null
},
{
"code": "<script> // Javascript program to find n-th term of a recursive// function using matrix exponentiation.var MOD = 1000000009; function power(n){ if (n <= 1) return 1; // This power function returns first row of // {Transformation Matrix}^n-1*Initial Vector n--; // This is an identity matrix. var res = [[1, 0,], [0, 1]]; // this is Transformation matrix. var tMat = [[2, 3],[1, 0]]; // Matrix exponentiation to calculate power of {tMat}^n-1 // store res in \"res\" matrix. while (n) { if (n & 1) { var tmp = Array.from(Array(2), ()=> Array(2)); tmp[0][0] = (res[0][0] * tMat[0][0] + res[0][1] * tMat[1][0]) % MOD; tmp[0][1] = (res[0][0] * tMat[0][1] + res[0][1] * tMat[1][1]) % MOD; tmp[1][0] = (res[1][0] * tMat[0][0] + res[1][1] * tMat[1][0]) % MOD; tmp[1][1] = (res[1][0] * tMat[0][1] + res[1][1] * tMat[1][1]) % MOD; res[0][0] = tmp[0][0]; res[0][1] = tmp[0][1]; res[1][0] = tmp[1][0]; res[1][1] = tmp[1][1]; } n = parseInt(n / 2); var tmp = Array.from(Array(2), ()=> Array(2)); tmp[0][0] = (tMat[0][0] * tMat[0][0] + tMat[0][1] * tMat[1][0]) % MOD; tmp[0][1] = (tMat[0][0] * tMat[0][1] + tMat[0][1] * tMat[1][1]) % MOD; tmp[1][0] = (tMat[1][0] * tMat[0][0] + tMat[1][1] * tMat[1][0]) % MOD; tmp[1][1] = (tMat[1][0] * tMat[0][1] + tMat[1][1] * tMat[1][1]) % MOD; tMat[0][0] = tmp[0][0]; tMat[0][1] = tmp[0][1]; tMat[1][0] = tmp[1][0]; tMat[1][1] = tmp[1][1]; } // res store {Transformation matrix}^n-1 // hence will be first row of res*Initial Vector. return (res[0][0] * 1 + res[0][1] * 1) % MOD;} // Driver codevar n = 3;document.write( power(n)); </script>",
"e": 14155,
"s": 12352,
"text": null
},
{
"code": null,
"e": 14158,
"s": 14155,
"text": "13"
},
{
"code": null,
"e": 14251,
"s": 14160,
"text": "Time Complexity : O(Log n)The same idea is used to find n-th Fibonacci number in O(Log n) "
},
{
"code": null,
"e": 14261,
"s": 14251,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 14274,
"s": 14261,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 14284,
"s": 14274,
"text": "rutvik_56"
},
{
"code": null,
"e": 14306,
"s": 14284,
"text": "matrix-exponentiation"
},
{
"code": null,
"e": 14330,
"s": 14306,
"text": "Competitive Programming"
},
{
"code": null,
"e": 14349,
"s": 14330,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 14356,
"s": 14349,
"text": "Matrix"
},
{
"code": null,
"e": 14366,
"s": 14356,
"text": "Recursion"
},
{
"code": null,
"e": 14376,
"s": 14366,
"text": "Recursion"
},
{
"code": null,
"e": 14395,
"s": 14376,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 14402,
"s": 14395,
"text": "Matrix"
},
{
"code": null,
"e": 14500,
"s": 14402,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14534,
"s": 14500,
"text": "Most important type of Algorithms"
},
{
"code": null,
"e": 14572,
"s": 14534,
"text": "The Ultimate Beginner's Guide For DSA"
},
{
"code": null,
"e": 14612,
"s": 14572,
"text": "Find two numbers from their sum and XOR"
},
{
"code": null,
"e": 14647,
"s": 14612,
"text": "Equal Sum and XOR of three Numbers"
},
{
"code": null,
"e": 14706,
"s": 14647,
"text": "C++: Methods of code shortening in competitive programming"
},
{
"code": null,
"e": 14717,
"s": 14706,
"text": "Merge Sort"
},
{
"code": null,
"e": 14727,
"s": 14717,
"text": "QuickSort"
},
{
"code": null,
"e": 14741,
"s": 14727,
"text": "Binary Search"
},
{
"code": null,
"e": 14809,
"s": 14741,
"text": "Maximum and minimum of an array using minimum number of comparisons"
}
] |
What is export default in JavaScript ?
|
20 Jun, 2022
The export statement is used when creating JavaScript modules to export objects, functions, variables from the module so they can be used by other programs with the help of the import statements. There are two types of exports. One is Named Exports and other is Default Exports. Named Exports: Named exports are useful to export several values. During the import, it is mandatory to use the same name of the corresponding object.
javascript
// Exporting individual featuresexport var name1 = ..., name2 = ..., ..., nameN; // also let, const // Export listexport { name1, name2, ..., nameN }; //Exporting everything at onceexport { object, number, x, y, boolean, string } // Renaming exportsexport { variable1 as name1, variable2 as name2, ..., nameN }; // export features declared earlierexport { myFunction, myVariable };
Example:
javascript
//file math.jsfunction square(x) { return x * x;}function cube(x) { return x * x * x;}export { square, cube }; //while importing square function in test.jsimport { square, cube } from './math;console.log(square(8)) //64console.log(cube(8)) //512
Output:
64
512
Default Exports: Default exports are useful to export only a single object, function, variable. During the import, we can use any name to import.
javascript
// file module.jsvar x=4;export default x; // test.js// while importing x in test.jsimport y from './module';// note that y is used import x instead of// import x, because x was default exportconsole.log(y); // output will be 4
Output
4
Another example of Default Exports with function
javascript
// file math.jsexport default function square(x) { return x * x;} //while importing square function in test.jsimport square from './math;console.log(square(8)) //64
Output:
64
Using Named and Default Exports at the same time: It is possible to use Named and Default exports in the same file. It means both will be imported in the same file. Example:
javascript
//module.jsvar x=2;const y=4;function fun() { return "This a default export."}function square(x) { return x * x;}export { fun as default, x, y, square };
While importing this module.js we can use any name for fun because it is a default export and curly braces for other named exports.
javascript
//test.js fileimport anyname, { x, y, square} from './module.js';console.log(anyname()); //This is a default export.console.log(x); //2
Output
This is a default export.
2
dasjet
JavaScript-Misc
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 Jun, 2022"
},
{
"code": null,
"e": 483,
"s": 52,
"text": "The export statement is used when creating JavaScript modules to export objects, functions, variables from the module so they can be used by other programs with the help of the import statements. There are two types of exports. One is Named Exports and other is Default Exports. Named Exports: Named exports are useful to export several values. During the import, it is mandatory to use the same name of the corresponding object. "
},
{
"code": null,
"e": 494,
"s": 483,
"text": "javascript"
},
{
"code": "// Exporting individual featuresexport var name1 = ..., name2 = ..., ..., nameN; // also let, const // Export listexport { name1, name2, ..., nameN }; //Exporting everything at onceexport { object, number, x, y, boolean, string } // Renaming exportsexport { variable1 as name1, variable2 as name2, ..., nameN }; // export features declared earlierexport { myFunction, myVariable };",
"e": 876,
"s": 494,
"text": null
},
{
"code": null,
"e": 886,
"s": 876,
"text": "Example: "
},
{
"code": null,
"e": 897,
"s": 886,
"text": "javascript"
},
{
"code": "//file math.jsfunction square(x) { return x * x;}function cube(x) { return x * x * x;}export { square, cube }; //while importing square function in test.jsimport { square, cube } from './math;console.log(square(8)) //64console.log(cube(8)) //512",
"e": 1147,
"s": 897,
"text": null
},
{
"code": null,
"e": 1155,
"s": 1147,
"text": "Output:"
},
{
"code": null,
"e": 1162,
"s": 1155,
"text": "64\n512"
},
{
"code": null,
"e": 1309,
"s": 1162,
"text": "Default Exports: Default exports are useful to export only a single object, function, variable. During the import, we can use any name to import. "
},
{
"code": null,
"e": 1320,
"s": 1309,
"text": "javascript"
},
{
"code": "// file module.jsvar x=4;export default x; // test.js// while importing x in test.jsimport y from './module';// note that y is used import x instead of// import x, because x was default exportconsole.log(y); // output will be 4",
"e": 1554,
"s": 1320,
"text": null
},
{
"code": null,
"e": 1561,
"s": 1554,
"text": "Output"
},
{
"code": null,
"e": 1563,
"s": 1561,
"text": "4"
},
{
"code": null,
"e": 1613,
"s": 1563,
"text": "Another example of Default Exports with function "
},
{
"code": null,
"e": 1624,
"s": 1613,
"text": "javascript"
},
{
"code": "// file math.jsexport default function square(x) { return x * x;} //while importing square function in test.jsimport square from './math;console.log(square(8)) //64",
"e": 1790,
"s": 1624,
"text": null
},
{
"code": null,
"e": 1798,
"s": 1790,
"text": "Output:"
},
{
"code": null,
"e": 1801,
"s": 1798,
"text": "64"
},
{
"code": null,
"e": 1976,
"s": 1801,
"text": "Using Named and Default Exports at the same time: It is possible to use Named and Default exports in the same file. It means both will be imported in the same file. Example: "
},
{
"code": null,
"e": 1987,
"s": 1976,
"text": "javascript"
},
{
"code": "//module.jsvar x=2;const y=4;function fun() { return \"This a default export.\"}function square(x) { return x * x;}export { fun as default, x, y, square };",
"e": 2144,
"s": 1987,
"text": null
},
{
"code": null,
"e": 2277,
"s": 2144,
"text": "While importing this module.js we can use any name for fun because it is a default export and curly braces for other named exports. "
},
{
"code": null,
"e": 2288,
"s": 2277,
"text": "javascript"
},
{
"code": "//test.js fileimport anyname, { x, y, square} from './module.js';console.log(anyname()); //This is a default export.console.log(x); //2",
"e": 2424,
"s": 2288,
"text": null
},
{
"code": null,
"e": 2431,
"s": 2424,
"text": "Output"
},
{
"code": null,
"e": 2459,
"s": 2431,
"text": "This is a default export.\n2"
},
{
"code": null,
"e": 2466,
"s": 2459,
"text": "dasjet"
},
{
"code": null,
"e": 2482,
"s": 2466,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2489,
"s": 2482,
"text": "Picked"
},
{
"code": null,
"e": 2500,
"s": 2489,
"text": "JavaScript"
},
{
"code": null,
"e": 2517,
"s": 2500,
"text": "Web Technologies"
},
{
"code": null,
"e": 2615,
"s": 2517,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2676,
"s": 2615,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2748,
"s": 2676,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2788,
"s": 2748,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2829,
"s": 2788,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2871,
"s": 2829,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2904,
"s": 2871,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2966,
"s": 2904,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3027,
"s": 2966,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3077,
"s": 3027,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
PostgreSQL – Difference between CHAR, VARCHAR and TEXT
|
30 Sep, 2021
Now that we are familiar with the concept of character data types CHAR, VARCHAR, and TEXT respectively in PostgreSQL, this article will focus on highlighting the key difference between them.
What is CHAR data type? This data type is used to store characters of limited length. It is represented as char(n) or character(n) in PostgreSQL, where n represents the limit of the length of the characters. If n is not specified it defaults to char(1) or character(1).
What is VARCHAR data type? This data type is used to store characters of limited length. It is represented as varchar(n) in PostgreSQL, where n represents the limit of the length of the characters. If n is not specified it defaults to varchar which has unlimited length.
What is TEXT data type? This data type is used to store characters of unlimited length. It is represented as text in PostgreSQL. The performance of the varchar (without n) and text are the same.
The below table provides with the major difference between CHAR, VARCHAR, and TEXT:
Example:
Let’s create a new table(say, character_tests) for the demonstration using the below commands:
CREATE TABLE character_tests (
id serial PRIMARY KEY,
x CHAR (1),
y VARCHAR (10),
z TEXT
);
Now let’s insert a new row into the char_test table using the below command:
INSERT INTO character_tests (x, y, z)
VALUES
(
'Geeks',
'This is a test for varchar',
'This is a very long text for the PostgreSQL text column'
);
At this stage PostgreSQL will raise an error as the data type of the x column is char(1) and we tried to insert a string with three characters into this column as shown below:
ERROR: value too long for type character(1)
So, now let’s fix it.
INSERT INTO character_tests (x, y, z)
VALUES
(
'G',
'This is a test for varchar',
'This is a very long text for the PostgreSQL text column'
);
Now, we will get the same error for the y column as the number of characters entered is greater than 10 as shown below:
ERROR: value too long for type character(10)
Let’s fix it too.
INSERT INTO character_tests (x, y, z)
VALUES
(
'Y',
'varchar(n)',
'This is a very long text for the PostgreSQL text column'
);
Now that we have managed to successfully assign the values to the character data type, check it by running the below command:
SELECT * FROM character_tests;
Output:
Akanksha_Rai
kashishsoda
postgreSQL-dataTypes
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - REPLACE Function
PostgreSQL - INSERT
PostgreSQL - DROP INDEX
PostgreSQL - TIME Data Type
PostgreSQL - ROW_NUMBER Function
PostgreSQL - CREATE SCHEMA
PostgreSQL - EXISTS Operator
PostgreSQL - SELECT
PostgreSQL - LEFT JOIN
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 220,
"s": 28,
"text": "Now that we are familiar with the concept of character data types CHAR, VARCHAR, and TEXT respectively in PostgreSQL, this article will focus on highlighting the key difference between them. "
},
{
"code": null,
"e": 491,
"s": 220,
"text": "What is CHAR data type? This data type is used to store characters of limited length. It is represented as char(n) or character(n) in PostgreSQL, where n represents the limit of the length of the characters. If n is not specified it defaults to char(1) or character(1). "
},
{
"code": null,
"e": 763,
"s": 491,
"text": "What is VARCHAR data type? This data type is used to store characters of limited length. It is represented as varchar(n) in PostgreSQL, where n represents the limit of the length of the characters. If n is not specified it defaults to varchar which has unlimited length. "
},
{
"code": null,
"e": 959,
"s": 763,
"text": "What is TEXT data type? This data type is used to store characters of unlimited length. It is represented as text in PostgreSQL. The performance of the varchar (without n) and text are the same. "
},
{
"code": null,
"e": 1044,
"s": 959,
"text": "The below table provides with the major difference between CHAR, VARCHAR, and TEXT: "
},
{
"code": null,
"e": 1054,
"s": 1044,
"text": "Example: "
},
{
"code": null,
"e": 1151,
"s": 1054,
"text": "Let’s create a new table(say, character_tests) for the demonstration using the below commands: "
},
{
"code": null,
"e": 1259,
"s": 1151,
"text": "CREATE TABLE character_tests (\n id serial PRIMARY KEY,\n x CHAR (1),\n y VARCHAR (10),\n z TEXT\n);"
},
{
"code": null,
"e": 1338,
"s": 1259,
"text": "Now let’s insert a new row into the char_test table using the below command: "
},
{
"code": null,
"e": 1517,
"s": 1338,
"text": "INSERT INTO character_tests (x, y, z)\nVALUES\n (\n 'Geeks',\n 'This is a test for varchar',\n 'This is a very long text for the PostgreSQL text column'\n );"
},
{
"code": null,
"e": 1695,
"s": 1517,
"text": "At this stage PostgreSQL will raise an error as the data type of the x column is char(1) and we tried to insert a string with three characters into this column as shown below: "
},
{
"code": null,
"e": 1740,
"s": 1695,
"text": "ERROR: value too long for type character(1)"
},
{
"code": null,
"e": 1764,
"s": 1740,
"text": "So, now let’s fix it. "
},
{
"code": null,
"e": 1939,
"s": 1764,
"text": "INSERT INTO character_tests (x, y, z)\nVALUES\n (\n 'G',\n 'This is a test for varchar',\n 'This is a very long text for the PostgreSQL text column'\n );"
},
{
"code": null,
"e": 2061,
"s": 1939,
"text": "Now, we will get the same error for the y column as the number of characters entered is greater than 10 as shown below: "
},
{
"code": null,
"e": 2107,
"s": 2061,
"text": "ERROR: value too long for type character(10)"
},
{
"code": null,
"e": 2127,
"s": 2107,
"text": "Let’s fix it too. "
},
{
"code": null,
"e": 2286,
"s": 2127,
"text": "INSERT INTO character_tests (x, y, z)\nVALUES\n (\n 'Y',\n 'varchar(n)',\n 'This is a very long text for the PostgreSQL text column'\n );"
},
{
"code": null,
"e": 2413,
"s": 2286,
"text": "Now that we have managed to successfully assign the values to the character data type, check it by running the below command: "
},
{
"code": null,
"e": 2444,
"s": 2413,
"text": "SELECT * FROM character_tests;"
},
{
"code": null,
"e": 2454,
"s": 2444,
"text": "Output: "
},
{
"code": null,
"e": 2469,
"s": 2456,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 2481,
"s": 2469,
"text": "kashishsoda"
},
{
"code": null,
"e": 2502,
"s": 2481,
"text": "postgreSQL-dataTypes"
},
{
"code": null,
"e": 2513,
"s": 2502,
"text": "PostgreSQL"
},
{
"code": null,
"e": 2611,
"s": 2513,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2649,
"s": 2611,
"text": "PostgreSQL - LIMIT with OFFSET clause"
},
{
"code": null,
"e": 2679,
"s": 2649,
"text": "PostgreSQL - REPLACE Function"
},
{
"code": null,
"e": 2699,
"s": 2679,
"text": "PostgreSQL - INSERT"
},
{
"code": null,
"e": 2723,
"s": 2699,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 2751,
"s": 2723,
"text": "PostgreSQL - TIME Data Type"
},
{
"code": null,
"e": 2784,
"s": 2751,
"text": "PostgreSQL - ROW_NUMBER Function"
},
{
"code": null,
"e": 2811,
"s": 2784,
"text": "PostgreSQL - CREATE SCHEMA"
},
{
"code": null,
"e": 2840,
"s": 2811,
"text": "PostgreSQL - EXISTS Operator"
},
{
"code": null,
"e": 2860,
"s": 2840,
"text": "PostgreSQL - SELECT"
}
] |
C Programming Mock Test
|
This section presents you various set of Mock Tests related to C Programming Framework. You can download these sample mock tests at your local machine and solve offline at your convenience. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself.
Q 1 - What is the output of the following code snippet?
#include<stdio.h>
main()
{
int const a = 5;
a++;
printf(“%d”,a);
}
A - 5
B - 6
C - Runtime error
D - Compile error
Compile error - constant variable cannot be modified.
main()
{
int const a = 5;
a++;
printf(“%d”,a);
}
Q 2 - What is the output of the following code snippet?
#include<stdio.h>
main()
{
const int a = 5;
a++;
printf("%d", a);
}
A - 5
B - 6
C - Runtime error
D - Compile error
Compile error - constant variable cannot be modified.
main()
{
const int a = 5;
a++;
printf("%d", a);
}
Q 3 - What is the output of the below code snippet?
#include<stdio.h>
main()
{
char s[]="hello", t[]="hello";
if(s==t){
printf("eqaul strings");
}
}
A - Equal strings
B - Unequal strings
C - No output
D - Compilation error
No output, as we are comparing both base addresses and they are not same.
Q 4 - What is the output of the below code snippet?
#include<stdio.h>
main()
{
int a = 5, b = 3, c = 4;
printf("a = %d, b = %d\n", a, b, c);
}
A - a=5, b=3
B - a=5, b=3, c=0
C - a=5, b=3, 0
D - compile error
a=5,b=3 , as there are only two format specifiers for printing.
Q 5 - What is the output of the below code snippet?
#include<stdio.h>
main()
{
int a = 1;
float b = 1.3;
double c;
c = a + b;
printf("%.2lf", c);
}
A - 2.30
B - 2.3
C - Compile error
D - 2.0
2.30, addition is valid and after decimal with is specified for 2 places.
Q 6 - What is the outpout of the following program?
#include<stdio.h>
main()
{
enum { india, is=7, GREAT };
printf("%d %d", india, GREAT);
}
A - 0 1.
B - 0 2
C - 0 8
D - Compile error
0 8, enums gives the sequence starting with 0. If assigned with a value the sequence continues from the assigned value.
Q 7 - What is the output of the following code snippet?
#include<stdio.h>
main()
{
char c = 'A'+255;
printf("%c", c);
}
A - A
B - B
C - Overflow error at runtime
D - Compile error
A, the range of ASCII values for the ASCII characters is 0-255. Hence the addition operation circulates back to ‘A’
Q 8 - What is the output of the following code snippet?
#include<stdio.h>
main()
{
short unsigned int i = 0;
printf("%u\n", i--);
}
A - 0
B - Compile error
C - 65535
D - 32767
0, with post decrement operator value of the variable will be considered as the expression’s value and later gets decremented.
Q 9 - What is the output of the below code snippet?
#include<stdio.h>
main()
{
unsigned x = 5, y=&x, *p = y+0;
printf("%u",*p);
}
A - Address of x
B - Address of y
C - Address of p
D - 5
5, as p holds the address of x which is y+0
Q 10 - What is your comment on the below C statement?
signed int *p=(int*)malloc(sizeof(unsigned int));
A - Improper type casting
B - Would throw Runtime error
C - Memory will be allocated but cannot hold an int value in the memory
D - No issue with statement
Option (d), as the size of int and unsigned is same, no problem in allocating memory.
Q 11 - What is the output of the following code snippet?
#include<stdio.h>
main()
{
int x = 5;
if(x==5)
{
if(x==5) break;
printf("Hello");
}
printf("Hi");
}
A - Compile error
B - Hi
C - HelloHi
D - Hello
compile error, keyword break can appear only within loop/switch statement.
Q 12 - What is the output of the following code snippet?
#include<stdio.h>
main()
{
int x = 5;
if(x=5)
{
if(x=5) break;
printf("Hello");
}
printf("Hi");
}
A - Compile error
B - Hi
C - HelloHi
D - Compiler warning
compile error, keyword break can appear only within loop/switch statement.
Q 13 - What is the output of the following code snippet?
#include<stdio.h>
main()
{
int x = 5;
if(x=5)
{
if(x=5) printf("Hello");
}
printf("Hi");
}
A - HelloHi
B - Hi
C - Hello
D - Compiler error
HelloHi, both the if statement’s expression evaluates to be true.
Q 14 - What is the output of the below code snippet?
#include<stdio.h>
main()
{
for(;;)printf("Hello");
}
A - Infinite loop
B - Prints “Hello” once.
C - No output
D - Compile error
infinite loop, with second expression of ‘for’ being absent it is considered as true by default.
Q 15 - What is the output of the below code snippet?
#include<stdio.h>
main()
{
for()printf("Hello");
}
A - Infinite loop
B - Prints “Hello” once.
C - No output
D - Compile error
Compiler error, semi colons need to appear though the expressions are optional for the ‘for’ loop.
Q 16 - What is the output of the below code snippet?
#include<stdio.h>
main()
{
for(1;2;3)
printf("Hello");
}
A - Infinite loop
B - Prints “Hello” once.
C - No output
D - Compile error
infinite loop, as the second expression is non-0, hence the condition is always true.
Q 17 - int x=~1; What is the value of 'x'?
A - 1
B - -1
C - 2
D - -2
-2, the one’s compliment of 1 is 1110 (binary) which is equivalent to two’s compliment of 2, ie -2.
Q 18 - What is the output of the following program?
#include<stdio.h>
void f()
{
static int i;
++i;
printf("%d", i);
}
main()
{
f();
f();
f();
}
A - 1 1 1
B - 0 0 0
C - 3 2 1
D - 1 2 3
1 2 3, A static local variables retains its value between the function calls and the default value is 0.
Q 19 - What is the output of the following code snippet?
#include<stdio.h>
main()
{
int *p = 15;
printf("%d",*p);
}
A - 15
B - Garbage value
C - Runtime error
D - Compiler error
Runtime error, as the pointer variable is not holding proper address, writing/reading the data from the same raises runtime error.
Q 20 - What is the output of the following program?
#include<stdio.h>
main()
{
register int x = 5;
int *p;
p=&x;
x++;
printf("%d",*p);
}
A - Compile error
B - 5
C - 6
D - Garbage value
Compile error, we cannot take the address of a register variable.
Q 21 - What is the output of the following program?
#include<stdio.h>
main()
{
int x = 65, *p = &x;
void *q=p;
char *r=q;
printf("%c",*r);
}
A - Garbage character.
B - A
C - 65
D - Compile error
A, void pointer is a generic pointer and can hold any variable’s address. ASCII character for the value 65 is ‘A’
Q 22 - What is the output of the following program?
#include<stdio.h>
void f()
{
printf(“Hello\n”);
}
main()
{
;
}
A - No output
B - Error, as the function is not called.
C - Error, as the function is defined without its declaration
D -Error, as the main() function is left empty
No output, apart from the option (a) rest of the comments against the options are invalid.
Q 23 - What is the output of the following program?
#include<stdio.h>
main()
{
printf("\");
}
A - \
B - \"
C - "
D - Compile error
Compile error, Format string of printf is not terminated.
Q 24 - What is the output of the following program?
#include<stdio.h>
{
int x = 1;
switch(x)
{
default: printf("Hello");
case 1: printf("hi"); break;
}
}
A - Hello
B - Hi
C - HelloHi
D - Compile error
Hi, control reaches default-case after comparing the rest of case constants.
Q 25 - What is the output of the following program?
#include<stdio.h>
main()
{
struct { int x;} var = {5}, *p = &var;
printf("%d %d %d",var.x,p->x,(*p).x);
}
A - 5 5 5
B - 5 5 garbage value
C - 5 5 0
D - Compile error
5 5 5, the two possible ways of accessing structure elements using pointer is by using -> (arrow operator) OR *.
Q 26 - What is the output of the following program?
#include<stdio.h>
void swap(int m, int n)
{
int x = m;
m = n;
n = x;
}
main()
{
int x=5, y=3;
swap(x,y);
printf("%d %d", x, y);
}
A - 3 5
B - 5 3
C - 5 5
D - Compile error
5 3, call by value mechanism can’t alter actual arguments.
#include <stdio.h>
void swap(int m, int n)
{
int x = m;
m = n;
n = x;
}
main()
{
int x=5, y=3;
swap(x,y);
printf("%d %d", x, y);
}
Q 27 - What will be printed for the below statement?
#include<stdio.h>
main()
{
printf("%d",strcmp("strcmp()","strcmp()"));
}
A - 0
B - 1
C - -1
D - Invalid use of strcmp() function
0, strcmp return 0 if both the strings are equal
Q 28 - What is the following program doing?
#include<stdio.h>
main()
{
FILE *stream=fopen("a.txt",'r');
}
A - Trying to open “a.txt” in read mode
B - Trying to open “a.txt” in write mode.
C - “stream” is an invalid identifier
D - Compile error
Compile error, second argument for fopen is invalid, should be a string.
Q 29 - What is the output of the following program?
#include<stdio.h>
main()
{
int r, x = 2;
float y = 5;
r = y%x;
printf("%d", r);
}
A - 1
B - 0
C - 2
D - Compile error
Compile Error, It is invalid that either of the operands for the modulus operator (%) is a real number.
Q 30 - Which operator is used to continue the definition of macro in the next line?
A - #
B - ##
C - $
D - \
\, the first two are stringize and token pasting operators respectively. There is no such operator called $.
Q 31 - What is the size of the following union definition?
#include<stdio.h>
union abc {
char a,b,c,d,e,f,g,h;
int i;
}abc;
main()
{
printf( "%d", sizeof( abc ));
}
A - 1
B - 2
C - 4
D - 8
union size is biggest element size of it. All the elements of the union share common memory.
Q 32 - What is the size of ‘int’?
A - 2
B - 4
C - 8
D - Compiler dependent
The size of ‘int’ depends upon the complier i.e. whether it is a 16 bit or 32 bit.
Q 33 - The type name/reserved word ‘short’ is ___
A - short long
B - short char
C - short float
D - short int
short is used as an alternative of short int.
Q 34 - What is the value of ‘y’ for the following code snippet?
#include<stdio.h>
main()
{
int x = 1;
float y = x>>2;
printf( "%f", y );
}
A - 4
B - 0.5
C - 0
D - 1
0, data bits are lost for the above shift operation hence the value is 0.
Q 35 - What is the output of the following program?
#include<stdio.h>
main()
{
float t = 2;
switch(t)
{
case 2: printf("Hi");
default: printf("Hello");
}
}
A - Hi
B - HiHello
C - Hello
D - Error
Error, switch expression can’t be float value.
Q 36 - What is the output of the following program?
#include<stdio.h>
main()
{
int i = 1;
while(++i <= 5)
printf("%d ",i++);
}
A - 1 3 5
B - 2 4
C - 2 4 6
D - 2
2 4, at while first incremented and later compared and in printf printed first and incremented later
Q 37 - What is the output of the following program?
#include<stdio.h>
main()
{
int i = 1;
while( i++<=5 )
printf("%d ",i++);
}
A - 1 3 5
B - 2 4
C - 2 4 6
D - 2
2 4 6, at while first compared and later incremented and in printf printed first and incremented later.
Q 38 - What is the output of the following program?
#include<stdio.h>
main()
{
int i = 1;
while(i++<=5);
printf("%d ",i++);
}
A - 4
B - 6
C - 2 6
D - 2 4
6, there is an empty statement following ‘while’.
Q 39 - What is the output of the following program?
#include<stdio.h>
main()
{
int x = 1;
do
printf("%d ", x);
while(x++<=1);
}
A - 1
B - 1 2
C - No output
D - Compile error
1 2, do..while is an entry control loop. As the expression x++ is post form loop continues for 2nd time also.
Q 40 - What is the output of the following program?
#include<stdio.h>
main()
{
int a[] = {1,2}, *p = a;
printf("%d", p[1]);
}
A - 1
B - 2
C - Compile error
D - Runtime error
2, as ‘p’ holds the base address then we can access array using ‘p’ just like with ‘a’
Q 41 - What is the output of the following program?
#include<stdio.h>
main()
{
int a[3] = {2,1};
printf("%d", a[a[1]]);
}
A - 0
B - 1
C - 2
D - 3
1, The inner indirection evaluates to 1, and the value at index 1 for outer indirection is 1.
Q 42 - What is the output of the following program?
#include<stdio.h>
main()
{
int a[3] = {2,,1};
printf("%d", a[a[0]]);
}
A - 0
B - 1
C - 2
D - Compile error
Compile error, invalid syntax in initializing the array.
Q 43 - What is the output of the following program?
#include<stdio.h>
main()
{
int a[] = {2,1};
printf("%d", *a);
}
A - 0
B - 1
C - 2
D - Compile error.
2, as ‘a’ refers to base address.
Q 44 - What is the output of the following program?
#include<stdio.h>
main()
{
int i = 1;
Charminar:
printf("%d ",i++);
if(i==3) break;
if(i<=5) goto Charminar;
}
A - 1 2
B - 1 2 3
C - 1 2 4 5
D - Compile error
Compile error, wrong place for ‘break’ to appear.
Q 45 - What is the output of the following program?
#include<stdio.h>
main()
{
int i = 13, j = 60;
i ^= j;
j ^= i;
i ^= j;
printf("%d %d", i, j);
}
A - 73 73
B - 60 13
C - 13 60
D - 60 60
60 13, its swapping.
Q 46 - What is the output of the following program?
#include<stdio.h>
main()
{
union abc {
int x;
char ch;
}var;
var.ch = 'A';
printf("%d", var.x);
}
A - A
B - Garbage value
C - 65
D - 97
65, as the union variables share common memory for all its elements, x gets ‘A’ whose ASCII value is 65 and is printed.
Q 47 - Identify the incorrect file opening mode from the following.
A - r
B - w
C - x
D - a
x, there is no such mode called “x”.
Q 48 - Function fopen() with the mode "r+" tries to open the file for __
A - reading and writing
B - reading and adding new content
C - only for reading
D - it works only for directories
Option (a), the file should exist and opens for both reading & writing.
Q 49 - Identify the invalid constant used in fseek() function as ‘whence’ reference.
A - SEEK_SET
B - SEEK_CUR
C - SEEK_BEG
D - SEEK_END
SEEK_BEG, all the rest are valid constants defined in ‘stdio.h’
Q 50 - First operating system designed using C programming language.
A - DOS
B - Windows
C - UNIX
D - Mac
UNIX. C actually invented to write an operation system called UNIX. By 1973 the entire UNIX OS is designed using C.
|
[
{
"code": null,
"e": 2511,
"s": 2218,
"text": "This section presents you various set of Mock Tests related to C Programming Framework. You can download these sample mock tests at your local machine and solve offline at your convenience. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself."
},
{
"code": null,
"e": 2567,
"s": 2511,
"text": "Q 1 - What is the output of the following code snippet?"
},
{
"code": null,
"e": 2654,
"s": 2567,
"text": "#include<stdio.h>\n\nmain() \n{ \n int const a = 5; \n \n a++; \n printf(“%d”,a); \n} "
},
{
"code": null,
"e": 2660,
"s": 2654,
"text": "A - 5"
},
{
"code": null,
"e": 2666,
"s": 2660,
"text": "B - 6"
},
{
"code": null,
"e": 2684,
"s": 2666,
"text": "C - Runtime error"
},
{
"code": null,
"e": 2702,
"s": 2684,
"text": "D - Compile error"
},
{
"code": null,
"e": 2756,
"s": 2702,
"text": "Compile error - constant variable cannot be modified."
},
{
"code": null,
"e": 2824,
"s": 2756,
"text": "main() \n{ \n int const a = 5; \n \n a++; \n printf(“%d”,a); \n} "
},
{
"code": null,
"e": 2880,
"s": 2824,
"text": "Q 2 - What is the output of the following code snippet?"
},
{
"code": null,
"e": 2967,
"s": 2880,
"text": "#include<stdio.h>\n\nmain() \n{ \n const int a = 5; \n \n a++; \n printf(\"%d\", a); \n}"
},
{
"code": null,
"e": 2973,
"s": 2967,
"text": "A - 5"
},
{
"code": null,
"e": 2979,
"s": 2973,
"text": "B - 6"
},
{
"code": null,
"e": 2997,
"s": 2979,
"text": "C - Runtime error"
},
{
"code": null,
"e": 3015,
"s": 2997,
"text": "D - Compile error"
},
{
"code": null,
"e": 3069,
"s": 3015,
"text": "Compile error - constant variable cannot be modified."
},
{
"code": null,
"e": 3137,
"s": 3069,
"text": "main() \n{ \n const int a = 5; \n \n a++; \n printf(\"%d\", a); \n}"
},
{
"code": null,
"e": 3189,
"s": 3137,
"text": "Q 3 - What is the output of the below code snippet?"
},
{
"code": null,
"e": 3304,
"s": 3189,
"text": "#include<stdio.h>\n\nmain() \n{ \n char s[]=\"hello\", t[]=\"hello\";\n \n if(s==t){\n\t printf(\"eqaul strings\");\n\t}\n}"
},
{
"code": null,
"e": 3322,
"s": 3304,
"text": "A - Equal strings"
},
{
"code": null,
"e": 3342,
"s": 3322,
"text": "B - Unequal strings"
},
{
"code": null,
"e": 3356,
"s": 3342,
"text": "C - No output"
},
{
"code": null,
"e": 3378,
"s": 3356,
"text": "D - Compilation error"
},
{
"code": null,
"e": 3452,
"s": 3378,
"text": "No output, as we are comparing both base addresses and they are not same."
},
{
"code": null,
"e": 3504,
"s": 3452,
"text": "Q 4 - What is the output of the below code snippet?"
},
{
"code": null,
"e": 3609,
"s": 3504,
"text": "#include<stdio.h>\n\nmain() \n{ \n int a = 5, b = 3, c = 4; \n \n printf(\"a = %d, b = %d\\n\", a, b, c);\n}"
},
{
"code": null,
"e": 3622,
"s": 3609,
"text": "A - a=5, b=3"
},
{
"code": null,
"e": 3640,
"s": 3622,
"text": "B - a=5, b=3, c=0"
},
{
"code": null,
"e": 3656,
"s": 3640,
"text": "C - a=5, b=3, 0"
},
{
"code": null,
"e": 3674,
"s": 3656,
"text": "D - compile error"
},
{
"code": null,
"e": 3739,
"s": 3674,
"text": " a=5,b=3 , as there are only two format specifiers for printing."
},
{
"code": null,
"e": 3791,
"s": 3739,
"text": "Q 5 - What is the output of the below code snippet?"
},
{
"code": null,
"e": 3912,
"s": 3791,
"text": "#include<stdio.h>\n\nmain() \n{ \n int a = 1; \n float b = 1.3; \n double c;\n \n c = a + b; \n printf(\"%.2lf\", c);\n}"
},
{
"code": null,
"e": 3921,
"s": 3912,
"text": "A - 2.30"
},
{
"code": null,
"e": 3929,
"s": 3921,
"text": "B - 2.3"
},
{
"code": null,
"e": 3947,
"s": 3929,
"text": "C - Compile error"
},
{
"code": null,
"e": 3955,
"s": 3947,
"text": "D - 2.0"
},
{
"code": null,
"e": 4030,
"s": 3955,
"text": " 2.30, addition is valid and after decimal with is specified for 2 places."
},
{
"code": null,
"e": 4082,
"s": 4030,
"text": "Q 6 - What is the outpout of the following program?"
},
{
"code": null,
"e": 4186,
"s": 4082,
"text": "#include<stdio.h>\n\nmain() \n{\n enum { india, is=7, GREAT };\n\n printf(\"%d %d\", india, GREAT);\n}"
},
{
"code": null,
"e": 4195,
"s": 4186,
"text": "A - 0 1."
},
{
"code": null,
"e": 4203,
"s": 4195,
"text": "B - 0 2"
},
{
"code": null,
"e": 4211,
"s": 4203,
"text": "C - 0 8"
},
{
"code": null,
"e": 4229,
"s": 4211,
"text": "D - Compile error"
},
{
"code": null,
"e": 4349,
"s": 4229,
"text": "0 8, enums gives the sequence starting with 0. If assigned with a value the sequence continues from the assigned value."
},
{
"code": null,
"e": 4405,
"s": 4349,
"text": "Q 7 - What is the output of the following code snippet?"
},
{
"code": null,
"e": 4483,
"s": 4405,
"text": "#include<stdio.h>\n\nmain() \n{\n char c = 'A'+255;\n \n printf(\"%c\", c);\n}"
},
{
"code": null,
"e": 4489,
"s": 4483,
"text": "A - A"
},
{
"code": null,
"e": 4495,
"s": 4489,
"text": "B - B"
},
{
"code": null,
"e": 4525,
"s": 4495,
"text": "C - Overflow error at runtime"
},
{
"code": null,
"e": 4543,
"s": 4525,
"text": "D - Compile error"
},
{
"code": null,
"e": 4659,
"s": 4543,
"text": "A, the range of ASCII values for the ASCII characters is 0-255. Hence the addition operation circulates back to ‘A’"
},
{
"code": null,
"e": 4715,
"s": 4659,
"text": "Q 8 - What is the output of the following code snippet?"
},
{
"code": null,
"e": 4804,
"s": 4715,
"text": "#include<stdio.h>\n\nmain() \n{\n short unsigned int i = 0; \n \n printf(\"%u\\n\", i--);\n}"
},
{
"code": null,
"e": 4810,
"s": 4804,
"text": "A - 0"
},
{
"code": null,
"e": 4828,
"s": 4810,
"text": "B - Compile error"
},
{
"code": null,
"e": 4838,
"s": 4828,
"text": "C - 65535"
},
{
"code": null,
"e": 4848,
"s": 4838,
"text": "D - 32767"
},
{
"code": null,
"e": 4975,
"s": 4848,
"text": "0, with post decrement operator value of the variable will be considered as the expression’s value and later gets decremented."
},
{
"code": null,
"e": 5027,
"s": 4975,
"text": "Q 9 - What is the output of the below code snippet?"
},
{
"code": null,
"e": 5115,
"s": 5027,
"text": "#include<stdio.h>\n\nmain() \n{\n unsigned x = 5, y=&x, *p = y+0; \n\n printf(\"%u\",*p);\n}"
},
{
"code": null,
"e": 5133,
"s": 5115,
"text": "A - Address of x"
},
{
"code": null,
"e": 5150,
"s": 5133,
"text": "B - Address of y"
},
{
"code": null,
"e": 5167,
"s": 5150,
"text": "C - Address of p"
},
{
"code": null,
"e": 5173,
"s": 5167,
"text": "D - 5"
},
{
"code": null,
"e": 5217,
"s": 5173,
"text": "5, as p holds the address of x which is y+0"
},
{
"code": null,
"e": 5271,
"s": 5217,
"text": "Q 10 - What is your comment on the below C statement?"
},
{
"code": null,
"e": 5324,
"s": 5271,
"text": " signed int *p=(int*)malloc(sizeof(unsigned int));"
},
{
"code": null,
"e": 5350,
"s": 5324,
"text": "A - Improper type casting"
},
{
"code": null,
"e": 5380,
"s": 5350,
"text": "B - Would throw Runtime error"
},
{
"code": null,
"e": 5452,
"s": 5380,
"text": "C - Memory will be allocated but cannot hold an int value in the memory"
},
{
"code": null,
"e": 5480,
"s": 5452,
"text": "D - No issue with statement"
},
{
"code": null,
"e": 5567,
"s": 5480,
"text": "Option (d), as the size of int and unsigned is same, no problem in allocating memory."
},
{
"code": null,
"e": 5624,
"s": 5567,
"text": "Q 11 - What is the output of the following code snippet?"
},
{
"code": null,
"e": 5761,
"s": 5624,
"text": "#include<stdio.h>\n\nmain() \n{\n int x = 5;\n \n if(x==5)\n {\t\n if(x==5) break;\n printf(\"Hello\");\n } \n printf(\"Hi\");\n}"
},
{
"code": null,
"e": 5779,
"s": 5761,
"text": "A - Compile error"
},
{
"code": null,
"e": 5786,
"s": 5779,
"text": "B - Hi"
},
{
"code": null,
"e": 5798,
"s": 5786,
"text": "C - HelloHi"
},
{
"code": null,
"e": 5808,
"s": 5798,
"text": "D - Hello"
},
{
"code": null,
"e": 5883,
"s": 5808,
"text": "compile error, keyword break can appear only within loop/switch statement."
},
{
"code": null,
"e": 5940,
"s": 5883,
"text": "Q 12 - What is the output of the following code snippet?"
},
{
"code": null,
"e": 6075,
"s": 5940,
"text": "#include<stdio.h>\n\nmain() \n{\n int x = 5;\n \n if(x=5)\n {\t\n if(x=5) break;\n printf(\"Hello\");\n } \n printf(\"Hi\");\n}"
},
{
"code": null,
"e": 6093,
"s": 6075,
"text": "A - Compile error"
},
{
"code": null,
"e": 6100,
"s": 6093,
"text": "B - Hi"
},
{
"code": null,
"e": 6112,
"s": 6100,
"text": "C - HelloHi"
},
{
"code": null,
"e": 6133,
"s": 6112,
"text": "D - Compiler warning"
},
{
"code": null,
"e": 6208,
"s": 6133,
"text": "compile error, keyword break can appear only within loop/switch statement."
},
{
"code": null,
"e": 6265,
"s": 6208,
"text": "Q 13 - What is the output of the following code snippet?"
},
{
"code": null,
"e": 6385,
"s": 6265,
"text": "#include<stdio.h>\n\nmain() \n{\n int x = 5;\n \n if(x=5)\n {\t\n if(x=5) printf(\"Hello\");\n } \n printf(\"Hi\");\n}"
},
{
"code": null,
"e": 6397,
"s": 6385,
"text": "A - HelloHi"
},
{
"code": null,
"e": 6404,
"s": 6397,
"text": "B - Hi"
},
{
"code": null,
"e": 6414,
"s": 6404,
"text": "C - Hello"
},
{
"code": null,
"e": 6433,
"s": 6414,
"text": "D - Compiler error"
},
{
"code": null,
"e": 6499,
"s": 6433,
"text": "HelloHi, both the if statement’s expression evaluates to be true."
},
{
"code": null,
"e": 6552,
"s": 6499,
"text": "Q 14 - What is the output of the below code snippet?"
},
{
"code": null,
"e": 6610,
"s": 6552,
"text": "#include<stdio.h>\n\nmain() \n{\n for(;;)printf(\"Hello\");\n}"
},
{
"code": null,
"e": 6628,
"s": 6610,
"text": "A - Infinite loop"
},
{
"code": null,
"e": 6653,
"s": 6628,
"text": "B - Prints “Hello” once."
},
{
"code": null,
"e": 6667,
"s": 6653,
"text": "C - No output"
},
{
"code": null,
"e": 6685,
"s": 6667,
"text": "D - Compile error"
},
{
"code": null,
"e": 6783,
"s": 6685,
"text": " infinite loop, with second expression of ‘for’ being absent it is considered as true by default."
},
{
"code": null,
"e": 6836,
"s": 6783,
"text": "Q 15 - What is the output of the below code snippet?"
},
{
"code": null,
"e": 6892,
"s": 6836,
"text": "#include<stdio.h>\n\nmain() \n{\n for()printf(\"Hello\");\n}"
},
{
"code": null,
"e": 6910,
"s": 6892,
"text": "A - Infinite loop"
},
{
"code": null,
"e": 6935,
"s": 6910,
"text": "B - Prints “Hello” once."
},
{
"code": null,
"e": 6949,
"s": 6935,
"text": "C - No output"
},
{
"code": null,
"e": 6967,
"s": 6949,
"text": "D - Compile error"
},
{
"code": null,
"e": 7067,
"s": 6967,
"text": "Compiler error, semi colons need to appear though the expressions are optional for the ‘for’ loop. "
},
{
"code": null,
"e": 7120,
"s": 7067,
"text": "Q 16 - What is the output of the below code snippet?"
},
{
"code": null,
"e": 7188,
"s": 7120,
"text": "#include<stdio.h>\n\nmain() \n{\n for(1;2;3)\n printf(\"Hello\");\n}"
},
{
"code": null,
"e": 7206,
"s": 7188,
"text": "A - Infinite loop"
},
{
"code": null,
"e": 7231,
"s": 7206,
"text": "B - Prints “Hello” once."
},
{
"code": null,
"e": 7245,
"s": 7231,
"text": "C - No output"
},
{
"code": null,
"e": 7263,
"s": 7245,
"text": "D - Compile error"
},
{
"code": null,
"e": 7349,
"s": 7263,
"text": "infinite loop, as the second expression is non-0, hence the condition is always true."
},
{
"code": null,
"e": 7394,
"s": 7349,
"text": "Q 17 - int x=~1; What is the value of 'x'? "
},
{
"code": null,
"e": 7400,
"s": 7394,
"text": "A - 1"
},
{
"code": null,
"e": 7407,
"s": 7400,
"text": "B - -1"
},
{
"code": null,
"e": 7413,
"s": 7407,
"text": "C - 2"
},
{
"code": null,
"e": 7420,
"s": 7413,
"text": "D - -2"
},
{
"code": null,
"e": 7521,
"s": 7420,
"text": " -2, the one’s compliment of 1 is 1110 (binary) which is equivalent to two’s compliment of 2, ie -2."
},
{
"code": null,
"e": 7574,
"s": 7521,
"text": "Q 18 - What is the output of the following program?"
},
{
"code": null,
"e": 7699,
"s": 7574,
"text": "#include<stdio.h>\n\nvoid f() \n{ \n static int i;\n \n ++i; \n printf(\"%d\", i); \n}\n\nmain()\n{ \n f(); \n f(); \n f(); \n}"
},
{
"code": null,
"e": 7709,
"s": 7699,
"text": "A - 1 1 1"
},
{
"code": null,
"e": 7719,
"s": 7709,
"text": "B - 0 0 0"
},
{
"code": null,
"e": 7729,
"s": 7719,
"text": "C - 3 2 1"
},
{
"code": null,
"e": 7739,
"s": 7729,
"text": "D - 1 2 3"
},
{
"code": null,
"e": 7844,
"s": 7739,
"text": "1 2 3, A static local variables retains its value between the function calls and the default value is 0."
},
{
"code": null,
"e": 7901,
"s": 7844,
"text": "Q 19 - What is the output of the following code snippet?"
},
{
"code": null,
"e": 7969,
"s": 7901,
"text": "#include<stdio.h>\n\nmain()\n{ \n int *p = 15; \n printf(\"%d\",*p);\n}"
},
{
"code": null,
"e": 7976,
"s": 7969,
"text": "A - 15"
},
{
"code": null,
"e": 7994,
"s": 7976,
"text": "B - Garbage value"
},
{
"code": null,
"e": 8012,
"s": 7994,
"text": "C - Runtime error"
},
{
"code": null,
"e": 8031,
"s": 8012,
"text": "D - Compiler error"
},
{
"code": null,
"e": 8162,
"s": 8031,
"text": "Runtime error, as the pointer variable is not holding proper address, writing/reading the data from the same raises runtime error."
},
{
"code": null,
"e": 8214,
"s": 8162,
"text": "Q 20 - What is the output of the following program?"
},
{
"code": null,
"e": 8322,
"s": 8214,
"text": "#include<stdio.h>\n\nmain()\n{\t\n register int x = 5;\n\n int *p;\n p=&x;\n x++;\n printf(\"%d\",*p);\n}"
},
{
"code": null,
"e": 8340,
"s": 8322,
"text": "A - Compile error"
},
{
"code": null,
"e": 8346,
"s": 8340,
"text": "B - 5"
},
{
"code": null,
"e": 8352,
"s": 8346,
"text": "C - 6"
},
{
"code": null,
"e": 8370,
"s": 8352,
"text": "D - Garbage value"
},
{
"code": null,
"e": 8436,
"s": 8370,
"text": "Compile error, we cannot take the address of a register variable."
},
{
"code": null,
"e": 8488,
"s": 8436,
"text": "Q 21 - What is the output of the following program?"
},
{
"code": null,
"e": 8594,
"s": 8488,
"text": "#include<stdio.h>\n\nmain()\n{\n int x = 65, *p = &x;\n \n void *q=p;\n char *r=q;\n printf(\"%c\",*r);\n}"
},
{
"code": null,
"e": 8617,
"s": 8594,
"text": "A - Garbage character."
},
{
"code": null,
"e": 8623,
"s": 8617,
"text": "B - A"
},
{
"code": null,
"e": 8630,
"s": 8623,
"text": "C - 65"
},
{
"code": null,
"e": 8648,
"s": 8630,
"text": "D - Compile error"
},
{
"code": null,
"e": 8762,
"s": 8648,
"text": "A, void pointer is a generic pointer and can hold any variable’s address. ASCII character for the value 65 is ‘A’"
},
{
"code": null,
"e": 8814,
"s": 8762,
"text": "Q 22 - What is the output of the following program?"
},
{
"code": null,
"e": 8885,
"s": 8814,
"text": "#include<stdio.h>\n\nvoid f() \n{\n printf(“Hello\\n”);\n}\nmain() \n{\n ;\n}"
},
{
"code": null,
"e": 8899,
"s": 8885,
"text": "A - No output"
},
{
"code": null,
"e": 8941,
"s": 8899,
"text": "B - Error, as the function is not called."
},
{
"code": null,
"e": 9003,
"s": 8941,
"text": "C - Error, as the function is defined without its declaration"
},
{
"code": null,
"e": 9050,
"s": 9003,
"text": "D -Error, as the main() function is left empty"
},
{
"code": null,
"e": 9141,
"s": 9050,
"text": "No output, apart from the option (a) rest of the comments against the options are invalid."
},
{
"code": null,
"e": 9193,
"s": 9141,
"text": "Q 23 - What is the output of the following program?"
},
{
"code": null,
"e": 9239,
"s": 9193,
"text": "#include<stdio.h>\n\nmain()\n{\n printf(\"\\\");\n}"
},
{
"code": null,
"e": 9245,
"s": 9239,
"text": "A - \\"
},
{
"code": null,
"e": 9252,
"s": 9245,
"text": "B - \\\""
},
{
"code": null,
"e": 9258,
"s": 9252,
"text": "C - \""
},
{
"code": null,
"e": 9276,
"s": 9258,
"text": "D - Compile error"
},
{
"code": null,
"e": 9334,
"s": 9276,
"text": "Compile error, Format string of printf is not terminated."
},
{
"code": null,
"e": 9386,
"s": 9334,
"text": "Q 24 - What is the output of the following program?"
},
{
"code": null,
"e": 9515,
"s": 9386,
"text": "#include<stdio.h>\n\n{ \n int x = 1;\n switch(x) \n {\n default: printf(\"Hello\");\n case 1: printf(\"hi\"); break;\n }\n}"
},
{
"code": null,
"e": 9525,
"s": 9515,
"text": "A - Hello"
},
{
"code": null,
"e": 9532,
"s": 9525,
"text": "B - Hi"
},
{
"code": null,
"e": 9544,
"s": 9532,
"text": "C - HelloHi"
},
{
"code": null,
"e": 9562,
"s": 9544,
"text": "D - Compile error"
},
{
"code": null,
"e": 9639,
"s": 9562,
"text": "Hi, control reaches default-case after comparing the rest of case constants."
},
{
"code": null,
"e": 9691,
"s": 9639,
"text": "Q 25 - What is the output of the following program?"
},
{
"code": null,
"e": 9810,
"s": 9691,
"text": "#include<stdio.h>\n\nmain()\n{ \n struct { int x;} var = {5}, *p = &var;\n \n printf(\"%d %d %d\",var.x,p->x,(*p).x); \n}"
},
{
"code": null,
"e": 9820,
"s": 9810,
"text": "A - 5 5 5"
},
{
"code": null,
"e": 9842,
"s": 9820,
"text": "B - 5 5 garbage value"
},
{
"code": null,
"e": 9852,
"s": 9842,
"text": "C - 5 5 0"
},
{
"code": null,
"e": 9870,
"s": 9852,
"text": "D - Compile error"
},
{
"code": null,
"e": 9983,
"s": 9870,
"text": "5 5 5, the two possible ways of accessing structure elements using pointer is by using -> (arrow operator) OR *."
},
{
"code": null,
"e": 10035,
"s": 9983,
"text": "Q 26 - What is the output of the following program?"
},
{
"code": null,
"e": 10189,
"s": 10035,
"text": "#include<stdio.h>\n\nvoid swap(int m, int n)\n{\n int x = m;\n \n m = n;\n n = x;\n}\nmain()\n{\n int x=5, y=3;\n\n swap(x,y);\n printf(\"%d %d\", x, y);\n}"
},
{
"code": null,
"e": 10197,
"s": 10189,
"text": "A - 3 5"
},
{
"code": null,
"e": 10205,
"s": 10197,
"text": "B - 5 3"
},
{
"code": null,
"e": 10213,
"s": 10205,
"text": "C - 5 5"
},
{
"code": null,
"e": 10231,
"s": 10213,
"text": "D - Compile error"
},
{
"code": null,
"e": 10290,
"s": 10231,
"text": "5 3, call by value mechanism can’t alter actual arguments."
},
{
"code": null,
"e": 10444,
"s": 10290,
"text": "#include <stdio.h>\nvoid swap(int m, int n)\n{\n int x = m;\n \n m = n;\n n = x;\n}\nmain()\n{\n int x=5, y=3;\n\n swap(x,y);\n printf(\"%d %d\", x, y);\n}"
},
{
"code": null,
"e": 10497,
"s": 10444,
"text": "Q 27 - What will be printed for the below statement?"
},
{
"code": null,
"e": 10574,
"s": 10497,
"text": "#include<stdio.h>\n\nmain()\n{\n printf(\"%d\",strcmp(\"strcmp()\",\"strcmp()\"));\n}"
},
{
"code": null,
"e": 10580,
"s": 10574,
"text": "A - 0"
},
{
"code": null,
"e": 10586,
"s": 10580,
"text": "B - 1"
},
{
"code": null,
"e": 10593,
"s": 10586,
"text": "C - -1"
},
{
"code": null,
"e": 10630,
"s": 10593,
"text": "D - Invalid use of strcmp() function"
},
{
"code": null,
"e": 10679,
"s": 10630,
"text": "0, strcmp return 0 if both the strings are equal"
},
{
"code": null,
"e": 10723,
"s": 10679,
"text": "Q 28 - What is the following program doing?"
},
{
"code": null,
"e": 10789,
"s": 10723,
"text": "#include<stdio.h>\n\nmain()\n{\n FILE *stream=fopen(\"a.txt\",'r');\n}"
},
{
"code": null,
"e": 10829,
"s": 10789,
"text": "A - Trying to open “a.txt” in read mode"
},
{
"code": null,
"e": 10871,
"s": 10829,
"text": "B - Trying to open “a.txt” in write mode."
},
{
"code": null,
"e": 10909,
"s": 10871,
"text": "C - “stream” is an invalid identifier"
},
{
"code": null,
"e": 10927,
"s": 10909,
"text": "D - Compile error"
},
{
"code": null,
"e": 11000,
"s": 10927,
"text": "Compile error, second argument for fopen is invalid, should be a string."
},
{
"code": null,
"e": 11052,
"s": 11000,
"text": "Q 29 - What is the output of the following program?"
},
{
"code": null,
"e": 11152,
"s": 11052,
"text": "#include<stdio.h>\n\nmain()\n{ \n int r, x = 2;\n float y = 5;\n\n r = y%x;\n printf(\"%d\", r); \n}"
},
{
"code": null,
"e": 11158,
"s": 11152,
"text": "A - 1"
},
{
"code": null,
"e": 11164,
"s": 11158,
"text": "B - 0"
},
{
"code": null,
"e": 11170,
"s": 11164,
"text": "C - 2"
},
{
"code": null,
"e": 11188,
"s": 11170,
"text": "D - Compile error"
},
{
"code": null,
"e": 11292,
"s": 11188,
"text": "Compile Error, It is invalid that either of the operands for the modulus operator (%) is a real number."
},
{
"code": null,
"e": 11376,
"s": 11292,
"text": "Q 30 - Which operator is used to continue the definition of macro in the next line?"
},
{
"code": null,
"e": 11382,
"s": 11376,
"text": "A - #"
},
{
"code": null,
"e": 11389,
"s": 11382,
"text": "B - ##"
},
{
"code": null,
"e": 11395,
"s": 11389,
"text": "C - $"
},
{
"code": null,
"e": 11401,
"s": 11395,
"text": "D - \\"
},
{
"code": null,
"e": 11510,
"s": 11401,
"text": "\\, the first two are stringize and token pasting operators respectively. There is no such operator called $."
},
{
"code": null,
"e": 11569,
"s": 11510,
"text": "Q 31 - What is the size of the following union definition?"
},
{
"code": null,
"e": 11690,
"s": 11569,
"text": "#include<stdio.h>\n\nunion abc { \n char a,b,c,d,e,f,g,h; \n int i;\n}abc;\n\nmain()\n{\n printf( \"%d\", sizeof( abc ));\n}"
},
{
"code": null,
"e": 11696,
"s": 11690,
"text": "A - 1"
},
{
"code": null,
"e": 11702,
"s": 11696,
"text": "B - 2"
},
{
"code": null,
"e": 11708,
"s": 11702,
"text": "C - 4"
},
{
"code": null,
"e": 11714,
"s": 11708,
"text": "D - 8"
},
{
"code": null,
"e": 11807,
"s": 11714,
"text": "union size is biggest element size of it. All the elements of the union share common memory."
},
{
"code": null,
"e": 11841,
"s": 11807,
"text": "Q 32 - What is the size of ‘int’?"
},
{
"code": null,
"e": 11847,
"s": 11841,
"text": "A - 2"
},
{
"code": null,
"e": 11853,
"s": 11847,
"text": "B - 4"
},
{
"code": null,
"e": 11859,
"s": 11853,
"text": "C - 8"
},
{
"code": null,
"e": 11882,
"s": 11859,
"text": "D - Compiler dependent"
},
{
"code": null,
"e": 11965,
"s": 11882,
"text": "The size of ‘int’ depends upon the complier i.e. whether it is a 16 bit or 32 bit."
},
{
"code": null,
"e": 12015,
"s": 11965,
"text": "Q 33 - The type name/reserved word ‘short’ is ___"
},
{
"code": null,
"e": 12030,
"s": 12015,
"text": "A - short long"
},
{
"code": null,
"e": 12045,
"s": 12030,
"text": "B - short char"
},
{
"code": null,
"e": 12061,
"s": 12045,
"text": "C - short float"
},
{
"code": null,
"e": 12076,
"s": 12061,
"text": "D - short int "
},
{
"code": null,
"e": 12122,
"s": 12076,
"text": "short is used as an alternative of short int."
},
{
"code": null,
"e": 12186,
"s": 12122,
"text": "Q 34 - What is the value of ‘y’ for the following code snippet?"
},
{
"code": null,
"e": 12279,
"s": 12186,
"text": "#include<stdio.h>\n\nmain()\n{\n int x = 1;\n \n float y = x>>2;\n \n printf( \"%f\", y );\n}"
},
{
"code": null,
"e": 12285,
"s": 12279,
"text": "A - 4"
},
{
"code": null,
"e": 12293,
"s": 12285,
"text": "B - 0.5"
},
{
"code": null,
"e": 12299,
"s": 12293,
"text": "C - 0"
},
{
"code": null,
"e": 12305,
"s": 12299,
"text": "D - 1"
},
{
"code": null,
"e": 12379,
"s": 12305,
"text": "0, data bits are lost for the above shift operation hence the value is 0."
},
{
"code": null,
"e": 12431,
"s": 12379,
"text": "Q 35 - What is the output of the following program?"
},
{
"code": null,
"e": 12565,
"s": 12431,
"text": "#include<stdio.h>\n\nmain()\n{ \n float t = 2;\n\n switch(t)\n {\n case 2: printf(\"Hi\");\n default: printf(\"Hello\");\n }\n}"
},
{
"code": null,
"e": 12572,
"s": 12565,
"text": "A - Hi"
},
{
"code": null,
"e": 12584,
"s": 12572,
"text": "B - HiHello"
},
{
"code": null,
"e": 12594,
"s": 12584,
"text": "C - Hello"
},
{
"code": null,
"e": 12604,
"s": 12594,
"text": "D - Error"
},
{
"code": null,
"e": 12651,
"s": 12604,
"text": "Error, switch expression can’t be float value."
},
{
"code": null,
"e": 12703,
"s": 12651,
"text": "Q 36 - What is the output of the following program?"
},
{
"code": null,
"e": 12795,
"s": 12703,
"text": "#include<stdio.h>\n\nmain()\n{\n int i = 1;\n \n while(++i <= 5)\n printf(\"%d \",i++);\n}"
},
{
"code": null,
"e": 12805,
"s": 12795,
"text": "A - 1 3 5"
},
{
"code": null,
"e": 12813,
"s": 12805,
"text": "B - 2 4"
},
{
"code": null,
"e": 12823,
"s": 12813,
"text": "C - 2 4 6"
},
{
"code": null,
"e": 12829,
"s": 12823,
"text": "D - 2"
},
{
"code": null,
"e": 12930,
"s": 12829,
"text": "2 4, at while first incremented and later compared and in printf printed first and incremented later"
},
{
"code": null,
"e": 12982,
"s": 12930,
"text": "Q 37 - What is the output of the following program?"
},
{
"code": null,
"e": 13074,
"s": 12982,
"text": "#include<stdio.h>\n\nmain()\n{\n int i = 1;\n \n while( i++<=5 )\n printf(\"%d \",i++);\n}"
},
{
"code": null,
"e": 13084,
"s": 13074,
"text": "A - 1 3 5"
},
{
"code": null,
"e": 13092,
"s": 13084,
"text": "B - 2 4"
},
{
"code": null,
"e": 13102,
"s": 13092,
"text": "C - 2 4 6"
},
{
"code": null,
"e": 13108,
"s": 13102,
"text": "D - 2"
},
{
"code": null,
"e": 13212,
"s": 13108,
"text": "2 4 6, at while first compared and later incremented and in printf printed first and incremented later."
},
{
"code": null,
"e": 13264,
"s": 13212,
"text": "Q 38 - What is the output of the following program?"
},
{
"code": null,
"e": 13356,
"s": 13264,
"text": "#include<stdio.h>\n\nmain()\n{\n int i = 1;\n \n while(i++<=5);\n printf(\"%d \",i++);\n}"
},
{
"code": null,
"e": 13362,
"s": 13356,
"text": "A - 4"
},
{
"code": null,
"e": 13368,
"s": 13362,
"text": "B - 6"
},
{
"code": null,
"e": 13376,
"s": 13368,
"text": "C - 2 6"
},
{
"code": null,
"e": 13384,
"s": 13376,
"text": "D - 2 4"
},
{
"code": null,
"e": 13434,
"s": 13384,
"text": "6, there is an empty statement following ‘while’."
},
{
"code": null,
"e": 13486,
"s": 13434,
"text": "Q 39 - What is the output of the following program?"
},
{
"code": null,
"e": 13582,
"s": 13486,
"text": "#include<stdio.h>\n\nmain()\n{\n int x = 1;\n \n do\n printf(\"%d \", x);\n while(x++<=1);\n}"
},
{
"code": null,
"e": 13588,
"s": 13582,
"text": "A - 1"
},
{
"code": null,
"e": 13596,
"s": 13588,
"text": "B - 1 2"
},
{
"code": null,
"e": 13610,
"s": 13596,
"text": "C - No output"
},
{
"code": null,
"e": 13628,
"s": 13610,
"text": "D - Compile error"
},
{
"code": null,
"e": 13738,
"s": 13628,
"text": "1 2, do..while is an entry control loop. As the expression x++ is post form loop continues for 2nd time also."
},
{
"code": null,
"e": 13790,
"s": 13738,
"text": "Q 40 - What is the output of the following program?"
},
{
"code": null,
"e": 13877,
"s": 13790,
"text": "#include<stdio.h>\n\nmain()\n{ \n int a[] = {1,2}, *p = a;\n \n printf(\"%d\", p[1]); \n}"
},
{
"code": null,
"e": 13883,
"s": 13877,
"text": "A - 1"
},
{
"code": null,
"e": 13889,
"s": 13883,
"text": "B - 2"
},
{
"code": null,
"e": 13907,
"s": 13889,
"text": "C - Compile error"
},
{
"code": null,
"e": 13925,
"s": 13907,
"text": "D - Runtime error"
},
{
"code": null,
"e": 14012,
"s": 13925,
"text": "2, as ‘p’ holds the base address then we can access array using ‘p’ just like with ‘a’"
},
{
"code": null,
"e": 14064,
"s": 14012,
"text": "Q 41 - What is the output of the following program?"
},
{
"code": null,
"e": 14147,
"s": 14064,
"text": "#include<stdio.h>\n\nmain()\n{ \n int a[3] = {2,1};\n \n printf(\"%d\", a[a[1]]); \n}"
},
{
"code": null,
"e": 14153,
"s": 14147,
"text": "A - 0"
},
{
"code": null,
"e": 14159,
"s": 14153,
"text": "B - 1"
},
{
"code": null,
"e": 14165,
"s": 14159,
"text": "C - 2"
},
{
"code": null,
"e": 14171,
"s": 14165,
"text": "D - 3"
},
{
"code": null,
"e": 14265,
"s": 14171,
"text": "1, The inner indirection evaluates to 1, and the value at index 1 for outer indirection is 1."
},
{
"code": null,
"e": 14317,
"s": 14265,
"text": "Q 42 - What is the output of the following program?"
},
{
"code": null,
"e": 14401,
"s": 14317,
"text": "#include<stdio.h>\n\nmain()\n{ \n int a[3] = {2,,1};\n \n printf(\"%d\", a[a[0]]); \n}"
},
{
"code": null,
"e": 14407,
"s": 14401,
"text": "A - 0"
},
{
"code": null,
"e": 14413,
"s": 14407,
"text": "B - 1"
},
{
"code": null,
"e": 14419,
"s": 14413,
"text": "C - 2"
},
{
"code": null,
"e": 14437,
"s": 14419,
"text": "D - Compile error"
},
{
"code": null,
"e": 14494,
"s": 14437,
"text": "Compile error, invalid syntax in initializing the array."
},
{
"code": null,
"e": 14546,
"s": 14494,
"text": "Q 43 - What is the output of the following program?"
},
{
"code": null,
"e": 14623,
"s": 14546,
"text": "#include<stdio.h>\n\nmain()\n{ \n int a[] = {2,1};\n \n printf(\"%d\", *a); \n}"
},
{
"code": null,
"e": 14629,
"s": 14623,
"text": "A - 0"
},
{
"code": null,
"e": 14635,
"s": 14629,
"text": "B - 1"
},
{
"code": null,
"e": 14641,
"s": 14635,
"text": "C - 2"
},
{
"code": null,
"e": 14660,
"s": 14641,
"text": "D - Compile error."
},
{
"code": null,
"e": 14694,
"s": 14660,
"text": "2, as ‘a’ refers to base address."
},
{
"code": null,
"e": 14746,
"s": 14694,
"text": "Q 44 - What is the output of the following program?"
},
{
"code": null,
"e": 14877,
"s": 14746,
"text": "#include<stdio.h>\n\nmain()\n{\n int i = 1;\n \n Charminar:\n printf(\"%d \",i++);\n if(i==3) break;\n if(i<=5) goto Charminar;\n}"
},
{
"code": null,
"e": 14885,
"s": 14877,
"text": "A - 1 2"
},
{
"code": null,
"e": 14896,
"s": 14885,
"text": "B - 1 2 3 "
},
{
"code": null,
"e": 14908,
"s": 14896,
"text": "C - 1 2 4 5"
},
{
"code": null,
"e": 14926,
"s": 14908,
"text": "D - Compile error"
},
{
"code": null,
"e": 14976,
"s": 14926,
"text": "Compile error, wrong place for ‘break’ to appear."
},
{
"code": null,
"e": 15028,
"s": 14976,
"text": "Q 45 - What is the output of the following program?"
},
{
"code": null,
"e": 15149,
"s": 15028,
"text": "#include<stdio.h>\n\nmain()\n{ \n int i = 13, j = 60;\n \n i ^= j;\n j ^= i;\n i ^= j;\n \n printf(\"%d %d\", i, j);\n}"
},
{
"code": null,
"e": 15159,
"s": 15149,
"text": "A - 73 73"
},
{
"code": null,
"e": 15169,
"s": 15159,
"text": "B - 60 13"
},
{
"code": null,
"e": 15179,
"s": 15169,
"text": "C - 13 60"
},
{
"code": null,
"e": 15189,
"s": 15179,
"text": "D - 60 60"
},
{
"code": null,
"e": 15210,
"s": 15189,
"text": "60 13, its swapping."
},
{
"code": null,
"e": 15262,
"s": 15210,
"text": "Q 46 - What is the output of the following program?"
},
{
"code": null,
"e": 15387,
"s": 15262,
"text": "#include<stdio.h>\n\nmain()\n{\t\n union abc {\n int x;\n char ch;\n }var;\n\n var.ch = 'A';\n printf(\"%d\", var.x);\n}"
},
{
"code": null,
"e": 15393,
"s": 15387,
"text": "A - A"
},
{
"code": null,
"e": 15411,
"s": 15393,
"text": "B - Garbage value"
},
{
"code": null,
"e": 15418,
"s": 15411,
"text": "C - 65"
},
{
"code": null,
"e": 15425,
"s": 15418,
"text": "D - 97"
},
{
"code": null,
"e": 15545,
"s": 15425,
"text": "65, as the union variables share common memory for all its elements, x gets ‘A’ whose ASCII value is 65 and is printed."
},
{
"code": null,
"e": 15613,
"s": 15545,
"text": "Q 47 - Identify the incorrect file opening mode from the following."
},
{
"code": null,
"e": 15619,
"s": 15613,
"text": "A - r"
},
{
"code": null,
"e": 15625,
"s": 15619,
"text": "B - w"
},
{
"code": null,
"e": 15631,
"s": 15625,
"text": "C - x"
},
{
"code": null,
"e": 15637,
"s": 15631,
"text": "D - a"
},
{
"code": null,
"e": 15674,
"s": 15637,
"text": "x, there is no such mode called “x”."
},
{
"code": null,
"e": 15747,
"s": 15674,
"text": "Q 48 - Function fopen() with the mode \"r+\" tries to open the file for __"
},
{
"code": null,
"e": 15771,
"s": 15747,
"text": "A - reading and writing"
},
{
"code": null,
"e": 15806,
"s": 15771,
"text": "B - reading and adding new content"
},
{
"code": null,
"e": 15827,
"s": 15806,
"text": "C - only for reading"
},
{
"code": null,
"e": 15861,
"s": 15827,
"text": "D - it works only for directories"
},
{
"code": null,
"e": 15933,
"s": 15861,
"text": "Option (a), the file should exist and opens for both reading & writing."
},
{
"code": null,
"e": 16018,
"s": 15933,
"text": "Q 49 - Identify the invalid constant used in fseek() function as ‘whence’ reference."
},
{
"code": null,
"e": 16031,
"s": 16018,
"text": "A - SEEK_SET"
},
{
"code": null,
"e": 16044,
"s": 16031,
"text": "B - SEEK_CUR"
},
{
"code": null,
"e": 16057,
"s": 16044,
"text": "C - SEEK_BEG"
},
{
"code": null,
"e": 16070,
"s": 16057,
"text": "D - SEEK_END"
},
{
"code": null,
"e": 16134,
"s": 16070,
"text": "SEEK_BEG, all the rest are valid constants defined in ‘stdio.h’"
},
{
"code": null,
"e": 16203,
"s": 16134,
"text": "Q 50 - First operating system designed using C programming language."
},
{
"code": null,
"e": 16211,
"s": 16203,
"text": "A - DOS"
},
{
"code": null,
"e": 16223,
"s": 16211,
"text": "B - Windows"
},
{
"code": null,
"e": 16232,
"s": 16223,
"text": "C - UNIX"
},
{
"code": null,
"e": 16240,
"s": 16232,
"text": "D - Mac"
}
] |
How to find the subsequence in an input sequence that matches the pattern required in Java Regular Expressions?
|
The find() method finds the subsequence in an input sequence that matches the pattern required. This method is available in the Matcher class that is available in the java.util.regex package.
A program that demonstrates the method Matcher.find() in Java regular expressions is given as follows:
Live Demo
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
public static void main(String args[]) {
Pattern p = Pattern.compile("Sun");
Matcher m = p.matcher("The Earth revolves around the Sun");
System.out.println("Subsequence: Sun");
System.out.println("Sequence: The Earth revolves around the Sun");
if (m.find())
System.out.println("\nSubsequence found");
else
System.out.println("\nSubsequence not found");
}
}
Subsequence: Sun
Sequence: The Earth revolves around the Sun
Subsequence found
Now let us understand the above program.
The subsequence “Sun” is searched in the string sequence "The Earth revolves around the Sun". Then the find() method is used to find if the subsequence is in the input sequence and the required result is printed. A code snippet which demonstrates this is as follows:
Pattern p = Pattern.compile("Sun");
Matcher m = p.matcher("The Earth revolves around the Sun");
System.out.println("Subsequence: Sun" );
System.out.println("Sequence: The Earth revolves around the Sun" );
if (m.find())
System.out.println("\nSubsequence found");
else
System.out.println("\nSubsequence not found");
|
[
{
"code": null,
"e": 1379,
"s": 1187,
"text": "The find() method finds the subsequence in an input sequence that matches the pattern required. This method is available in the Matcher class that is available in the java.util.regex package."
},
{
"code": null,
"e": 1482,
"s": 1379,
"text": "A program that demonstrates the method Matcher.find() in Java regular expressions is given as follows:"
},
{
"code": null,
"e": 1493,
"s": 1482,
"text": " Live Demo"
},
{
"code": null,
"e": 1994,
"s": 1493,
"text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class Demo {\n public static void main(String args[]) {\n Pattern p = Pattern.compile(\"Sun\");\n Matcher m = p.matcher(\"The Earth revolves around the Sun\");\n System.out.println(\"Subsequence: Sun\");\n System.out.println(\"Sequence: The Earth revolves around the Sun\");\n if (m.find())\n System.out.println(\"\\nSubsequence found\");\n else\n System.out.println(\"\\nSubsequence not found\");\n }\n}"
},
{
"code": null,
"e": 2073,
"s": 1994,
"text": "Subsequence: Sun\nSequence: The Earth revolves around the Sun\nSubsequence found"
},
{
"code": null,
"e": 2114,
"s": 2073,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 2381,
"s": 2114,
"text": "The subsequence “Sun” is searched in the string sequence \"The Earth revolves around the Sun\". Then the find() method is used to find if the subsequence is in the input sequence and the required result is printed. A code snippet which demonstrates this is as follows:"
},
{
"code": null,
"e": 2701,
"s": 2381,
"text": "Pattern p = Pattern.compile(\"Sun\");\nMatcher m = p.matcher(\"The Earth revolves around the Sun\");\nSystem.out.println(\"Subsequence: Sun\" );\nSystem.out.println(\"Sequence: The Earth revolves around the Sun\" );\nif (m.find())\n System.out.println(\"\\nSubsequence found\");\nelse\n System.out.println(\"\\nSubsequence not found\");"
}
] |
GATE | GATE-CS-2005 | Question 82
|
28 Jun, 2021
Consider the following C-function:
double foo (int n){ int i; double sum; if (n = = 0) return 1.0; else { sum = 0.0; for (i = 0; i < n; i++) sum += foo (i); return sum; }}
Suppose we modify the above function foo() and store the values of foo (i), 0 < = i < n, as and when they are computed. With this modification, the time complexity for function foo() is significantly reduced. The space complexity of the modified function would be:(A) O(1)(B) O(n)(C) O(n!)(D) O(nn)Answer: (B)Explanation: Space complexity now is also O(n).
We would need an array of size O(n). The space required for recursive calls would be O(1) as the values would be taken from stored array rather than making function calls again and again.Quiz of this Question
GATE-CS-2005
GATE-GATE-CS-2005
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 1996 | Question 63
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2015 (Set 2) | Question 55
GATE | GATE-CS-2001 | Question 50
GATE | GATE-CS-2004 | Question 31
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 63,
"s": 28,
"text": "Consider the following C-function:"
},
{
"code": "double foo (int n){ int i; double sum; if (n = = 0) return 1.0; else { sum = 0.0; for (i = 0; i < n; i++) sum += foo (i); return sum; }}",
"e": 250,
"s": 63,
"text": null
},
{
"code": null,
"e": 607,
"s": 250,
"text": "Suppose we modify the above function foo() and store the values of foo (i), 0 < = i < n, as and when they are computed. With this modification, the time complexity for function foo() is significantly reduced. The space complexity of the modified function would be:(A) O(1)(B) O(n)(C) O(n!)(D) O(nn)Answer: (B)Explanation: Space complexity now is also O(n)."
},
{
"code": null,
"e": 816,
"s": 607,
"text": "We would need an array of size O(n). The space required for recursive calls would be O(1) as the values would be taken from stored array rather than making function calls again and again.Quiz of this Question"
},
{
"code": null,
"e": 829,
"s": 816,
"text": "GATE-CS-2005"
},
{
"code": null,
"e": 847,
"s": 829,
"text": "GATE-GATE-CS-2005"
},
{
"code": null,
"e": 852,
"s": 847,
"text": "GATE"
},
{
"code": null,
"e": 950,
"s": 852,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 992,
"s": 950,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 1054,
"s": 992,
"text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33"
},
{
"code": null,
"e": 1096,
"s": 1054,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 20"
},
{
"code": null,
"e": 1138,
"s": 1096,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 1180,
"s": 1138,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 1214,
"s": 1180,
"text": "GATE | GATE CS 1996 | Question 63"
},
{
"code": null,
"e": 1248,
"s": 1214,
"text": "GATE | GATE CS 2008 | Question 40"
},
{
"code": null,
"e": 1290,
"s": 1248,
"text": "GATE | GATE-CS-2015 (Set 2) | Question 55"
},
{
"code": null,
"e": 1324,
"s": 1290,
"text": "GATE | GATE-CS-2001 | Question 50"
}
] |
Web Scraping 1: Scraping Table Data | by Kiprono Elijah Koech | Towards Data Science
|
Web Scraping is the most important concept of data collection. In Python, BeautifulSoup, Selenium and XPath are the most important tools that can be used to accomplish the task of web scraping.
In this article, we will focus on BeautifulSoup and how to use it to scrape GDP data from Wikipedia page. The data we need on this site is in form of a table.
Take a look at the following image then we can go ahead and define the components of an HTML table
From the above image we can deduce the following:
The <table> tag defines an HTML table.
An HTML table consists of one <table> element and one or more <tr>, <th>, and <td> elements.
The <tr> element defines a table row, the <th> element defines a table header, and the <td> element defines a table cell.
An HTML table may also include <caption>, <colgroup>, <thead>, <tfoot>, and <tbody> elements.
Our interest is to inspect the elements of a given site (in this case the site we want to scrap — on the far right of Figure 1 shows the elements of the site). In most computers you visit the site and click Ctrl+Shift+I to inspect the page you wish to scrap.
Note: Elements of a web page are identified by using a class or id options on the tag. Ids are unique but classes are not. This means that a given class can identify more than one web element while one id identifies one and only one element.
Lets now see the image of the site we want to scrape
From this Figure note the following:
This is the Uniform Resource Locator (URL). We need this.Tag element for our object of interest. The object is defined by class and not id: class = “wikitable sortable jquery”. Note that the tag element contains 3 classes identifying one table (classes are separated by white space). Apart from general reference of a site element as we will use here, classes and ids are used as reference to support styling using languages like CSS.In the site there are 3 tables numbered 3, 4 and 5 in the Figure above. For the sake of this article we will go through how to scrape table 3 and you can easily figure out of how to do 4 and 5.The button labelled 6 is very important when you are hovering through the page to identify the elements of your interest. Once your object of interest is highlighted the tag element will also be highlighted. e.g for our case label 2 is matching label 3.
This is the Uniform Resource Locator (URL). We need this.
Tag element for our object of interest. The object is defined by class and not id: class = “wikitable sortable jquery”. Note that the tag element contains 3 classes identifying one table (classes are separated by white space). Apart from general reference of a site element as we will use here, classes and ids are used as reference to support styling using languages like CSS.
In the site there are 3 tables numbered 3, 4 and 5 in the Figure above. For the sake of this article we will go through how to scrape table 3 and you can easily figure out of how to do 4 and 5.
The button labelled 6 is very important when you are hovering through the page to identify the elements of your interest. Once your object of interest is highlighted the tag element will also be highlighted. e.g for our case label 2 is matching label 3.
Required packages: bs4, lxml, pandas and requests.
Once you have the said packages we can now go through the code.
In this snippet, we import necessary packages and parse HTML content of the site.
Upon inspection of the site elements and/or soup variable in snippet 1 you will realize that the three tables shown in Fig 3 belongs to the same class wikitable .
OUTPUT: Number of tables on site: 3
To scrap the first table we just need to get the 0th index from gdp. The body variable in the snippet below contains all the rows of the table including the header. The headers will be in body[0] and all the others rows will be in the list body[1:]
OUTPUT:['Rank', 'Country/Territory', 'US$']
The headers looks right.
Next, we need to loop through rest of the rows as below
At this point we now have the headers on headings and all the other rows on all_rows and from here we can pass this data and headers as a Pandas DataFrame
Full code
Web content are protected by copyright which, in most cases, restrict copy, distribution, transmission and adoption of the content. When you intent to scrap such a website you may need to get express and explicit permission for the content owners otherwise your act of scraping without proper consent may land you in trouble of breach.
Some sites, however, provides its content under Creative Commons License allowing you to copy, modify and distribute there content without any problem though some may provide restriction on commercialization of such content.
The bottom line is that before web scraping, you need to be sure that you have the right to do so.
Web scraping is the most important tool you can use to collect data from the web. To learn more about web scraping you can go through this repository which contains more examples.
Join medium on https://medium.com/@kiprono_65591/membership to get full access to every story on Medium.
You can also get the articles into your email inbox whenever I post using this link: https://medium.com/subscribe/@kiprono_65591
Thanks for reading.
|
[
{
"code": null,
"e": 366,
"s": 172,
"text": "Web Scraping is the most important concept of data collection. In Python, BeautifulSoup, Selenium and XPath are the most important tools that can be used to accomplish the task of web scraping."
},
{
"code": null,
"e": 525,
"s": 366,
"text": "In this article, we will focus on BeautifulSoup and how to use it to scrape GDP data from Wikipedia page. The data we need on this site is in form of a table."
},
{
"code": null,
"e": 624,
"s": 525,
"text": "Take a look at the following image then we can go ahead and define the components of an HTML table"
},
{
"code": null,
"e": 674,
"s": 624,
"text": "From the above image we can deduce the following:"
},
{
"code": null,
"e": 713,
"s": 674,
"text": "The <table> tag defines an HTML table."
},
{
"code": null,
"e": 806,
"s": 713,
"text": "An HTML table consists of one <table> element and one or more <tr>, <th>, and <td> elements."
},
{
"code": null,
"e": 928,
"s": 806,
"text": "The <tr> element defines a table row, the <th> element defines a table header, and the <td> element defines a table cell."
},
{
"code": null,
"e": 1022,
"s": 928,
"text": "An HTML table may also include <caption>, <colgroup>, <thead>, <tfoot>, and <tbody> elements."
},
{
"code": null,
"e": 1281,
"s": 1022,
"text": "Our interest is to inspect the elements of a given site (in this case the site we want to scrap — on the far right of Figure 1 shows the elements of the site). In most computers you visit the site and click Ctrl+Shift+I to inspect the page you wish to scrap."
},
{
"code": null,
"e": 1523,
"s": 1281,
"text": "Note: Elements of a web page are identified by using a class or id options on the tag. Ids are unique but classes are not. This means that a given class can identify more than one web element while one id identifies one and only one element."
},
{
"code": null,
"e": 1576,
"s": 1523,
"text": "Lets now see the image of the site we want to scrape"
},
{
"code": null,
"e": 1613,
"s": 1576,
"text": "From this Figure note the following:"
},
{
"code": null,
"e": 2494,
"s": 1613,
"text": "This is the Uniform Resource Locator (URL). We need this.Tag element for our object of interest. The object is defined by class and not id: class = “wikitable sortable jquery”. Note that the tag element contains 3 classes identifying one table (classes are separated by white space). Apart from general reference of a site element as we will use here, classes and ids are used as reference to support styling using languages like CSS.In the site there are 3 tables numbered 3, 4 and 5 in the Figure above. For the sake of this article we will go through how to scrape table 3 and you can easily figure out of how to do 4 and 5.The button labelled 6 is very important when you are hovering through the page to identify the elements of your interest. Once your object of interest is highlighted the tag element will also be highlighted. e.g for our case label 2 is matching label 3."
},
{
"code": null,
"e": 2552,
"s": 2494,
"text": "This is the Uniform Resource Locator (URL). We need this."
},
{
"code": null,
"e": 2930,
"s": 2552,
"text": "Tag element for our object of interest. The object is defined by class and not id: class = “wikitable sortable jquery”. Note that the tag element contains 3 classes identifying one table (classes are separated by white space). Apart from general reference of a site element as we will use here, classes and ids are used as reference to support styling using languages like CSS."
},
{
"code": null,
"e": 3124,
"s": 2930,
"text": "In the site there are 3 tables numbered 3, 4 and 5 in the Figure above. For the sake of this article we will go through how to scrape table 3 and you can easily figure out of how to do 4 and 5."
},
{
"code": null,
"e": 3378,
"s": 3124,
"text": "The button labelled 6 is very important when you are hovering through the page to identify the elements of your interest. Once your object of interest is highlighted the tag element will also be highlighted. e.g for our case label 2 is matching label 3."
},
{
"code": null,
"e": 3429,
"s": 3378,
"text": "Required packages: bs4, lxml, pandas and requests."
},
{
"code": null,
"e": 3493,
"s": 3429,
"text": "Once you have the said packages we can now go through the code."
},
{
"code": null,
"e": 3575,
"s": 3493,
"text": "In this snippet, we import necessary packages and parse HTML content of the site."
},
{
"code": null,
"e": 3738,
"s": 3575,
"text": "Upon inspection of the site elements and/or soup variable in snippet 1 you will realize that the three tables shown in Fig 3 belongs to the same class wikitable ."
},
{
"code": null,
"e": 3775,
"s": 3738,
"text": "OUTPUT: Number of tables on site: 3"
},
{
"code": null,
"e": 4024,
"s": 3775,
"text": "To scrap the first table we just need to get the 0th index from gdp. The body variable in the snippet below contains all the rows of the table including the header. The headers will be in body[0] and all the others rows will be in the list body[1:]"
},
{
"code": null,
"e": 4068,
"s": 4024,
"text": "OUTPUT:['Rank', 'Country/Territory', 'US$']"
},
{
"code": null,
"e": 4093,
"s": 4068,
"text": "The headers looks right."
},
{
"code": null,
"e": 4149,
"s": 4093,
"text": "Next, we need to loop through rest of the rows as below"
},
{
"code": null,
"e": 4304,
"s": 4149,
"text": "At this point we now have the headers on headings and all the other rows on all_rows and from here we can pass this data and headers as a Pandas DataFrame"
},
{
"code": null,
"e": 4314,
"s": 4304,
"text": "Full code"
},
{
"code": null,
"e": 4650,
"s": 4314,
"text": "Web content are protected by copyright which, in most cases, restrict copy, distribution, transmission and adoption of the content. When you intent to scrap such a website you may need to get express and explicit permission for the content owners otherwise your act of scraping without proper consent may land you in trouble of breach."
},
{
"code": null,
"e": 4875,
"s": 4650,
"text": "Some sites, however, provides its content under Creative Commons License allowing you to copy, modify and distribute there content without any problem though some may provide restriction on commercialization of such content."
},
{
"code": null,
"e": 4974,
"s": 4875,
"text": "The bottom line is that before web scraping, you need to be sure that you have the right to do so."
},
{
"code": null,
"e": 5154,
"s": 4974,
"text": "Web scraping is the most important tool you can use to collect data from the web. To learn more about web scraping you can go through this repository which contains more examples."
},
{
"code": null,
"e": 5259,
"s": 5154,
"text": "Join medium on https://medium.com/@kiprono_65591/membership to get full access to every story on Medium."
},
{
"code": null,
"e": 5388,
"s": 5259,
"text": "You can also get the articles into your email inbox whenever I post using this link: https://medium.com/subscribe/@kiprono_65591"
}
] |
Paste command in Linux with examples - GeeksforGeeks
|
19 Feb, 2021
Paste command is one of the useful commands in Unix or Linux operating system. It is used to join files horizontally (parallel merging) by outputting lines consisting of lines from each file specified, separated by tab as delimiter, to the standard output. When no file is specified, or put dash (“-“) instead of file name, paste reads from standard input and gives output as it is until a interrupt command [Ctrl-c] is given.
Syntax:
paste [OPTION]... [FILES]...
Let us consider three files having name state, capital and number. state and capital file contains 5 names of the Indian states and capitals respectively. number file contains 5 numbers.
$ cat state
Arunachal Pradesh
Assam
Andhra Pradesh
Bihar
Chhattisgrah
$ cat capital
Itanagar
Dispur
Hyderabad
Patna
Raipur
Without any option paste merges the files in parallel. The paste command writes corresponding lines from the files with tab as a deliminator on the terminal.
$ paste number state capital
1 Arunachal Pradesh Itanagar
2 Assam Dispur
3 Andhra Pradesh Hyderabad
4 Bihar Patna
5 Chhattisgrah Raipur
In the above command three files are merges by paste command.
Options:
1. -d (delimiter): Paste command uses the tab delimiter by default for merging the files. The delimiter can be changed to any other character by using the -d option. If more than one character is specified as delimiter then paste uses it in a circular fashion for each file line separation.
Only one character is specified
$ paste -d "|" number state capital
1|Arunachal Pradesh|Itanagar
2|Assam|Dispur
3|Andhra Pradesh|Hyderabad
4|Bihar|Patna
5|Chhattisgrah|Raipur
More than one character is specified
$ paste -d "|," number state capital
1|Arunachal Pradesh,Itanagar
2|Assam,Dispur
3|Andhra Pradesh,Hyderabad
4|Bihar,Patna
5|Chhattisgrah,Raipur
First and second file is separated by '|' and second and third is separated by ','.
After that list is exhausted and reused.
2. -s (serial): We can merge the files in sequentially manner using the -s option. It reads all the lines from a single file and merges all these lines into a single line with each line separated by tab. And these single lines are separated by newline.
$ paste -s number state capital
1 2 3 4 5
Arunachal Pradesh Assam Andhra Pradesh Bihar Chhattisgrah
Itanagar Dispur Hyderabad Patna Raipur
In the above command, first it reads data from number file and merge them into single line with each line separated by tab. After that newline character is introduced and reading from next file i.e. state starts and process repeats again till all files are read.
Combination of -d and -s: The following example shows how to specify a delimiter for sequential merging of files:
$ paste -s -d ":" number state capital
1:2:3:4:5
Arunachal Pradesh:Assam:Andhra Pradesh:Bihar:Chhattisgrah
Itanagar:Dispur:Hyderabad:Patna:Raipur
3. –version: This option is used to display the version of paste which is currently running on your system.
$ paste --version
paste (GNU coreutils) 8.26
Packaged by Cygwin (8.26-2)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later .
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by David M. Ihnat and David MacKenzie.
Applications of Paste Command
1. Combining N consecutive lines: The paste command can also be used to merge N consecutive lines from a file into a single line. Here N can be specified by specifying number hyphens(-) after paste.
With 2 hyphens
$ cat capital | paste - -
Itanagar Dispur
Hyderabad Patna
Raipur
With 3 hyphens
$ paste - - - < capital
Itanagar Dispur Hyderabad
Patna Raipur
2. Combination with other commands: Even though paste require at least two files for concatenating lines, but data from one file can be given from shell. Like in our example below, cut command is used with -f option for cutting out first field of state file and output is pipelined with paste command having one file name and instead of second file name hyphen is specified.
Note: If hyphen is not specified then input from shell is not pasted.
Without hypen
$ cut -d " " -f 1 state | paste number
1
2
3
4
5
With hypen
$ cut -d " " -f 1 state | paste number -
1 Arunachal
2 Assam
3 Andhra
4 Bihar
5 Chhattisgrah
Ordering of pasting can be changed by altering the location of hyphen:
$ cut -d " " -f 1 state | paste - number
Arunachal 1
Assam 2
Andhra 3
Bihar 4
Chhattisgrah 5
YouTubeGeeksforGeeks500K subscribersLinux Tutorials | paste command | GeeksforGeeksWatch laterShareCopy link25/36InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:07•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ilV6dcTJzzE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Akash Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
linux-command
Linux-text-processing-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
tar command in Linux with examples
UDP Server-Client implementation in C
Conditional Statements | Shell Script
Cat command in Linux with examples
echo command in Linux with Examples
Mutex lock for Linux Thread Synchronization
touch command in Linux with Examples
Tail command in Linux with examples
Compiling with g++
tee command in Linux with examples
|
[
{
"code": null,
"e": 23950,
"s": 23922,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 24377,
"s": 23950,
"text": "Paste command is one of the useful commands in Unix or Linux operating system. It is used to join files horizontally (parallel merging) by outputting lines consisting of lines from each file specified, separated by tab as delimiter, to the standard output. When no file is specified, or put dash (“-“) instead of file name, paste reads from standard input and gives output as it is until a interrupt command [Ctrl-c] is given."
},
{
"code": null,
"e": 24385,
"s": 24377,
"text": "Syntax:"
},
{
"code": null,
"e": 24415,
"s": 24385,
"text": "paste [OPTION]... [FILES]...\n"
},
{
"code": null,
"e": 24602,
"s": 24415,
"text": "Let us consider three files having name state, capital and number. state and capital file contains 5 names of the Indian states and capitals respectively. number file contains 5 numbers."
},
{
"code": null,
"e": 24727,
"s": 24602,
"text": "$ cat state\nArunachal Pradesh\nAssam\nAndhra Pradesh\nBihar\nChhattisgrah\n\n$ cat capital\nItanagar\nDispur\nHyderabad\nPatna\nRaipur\n"
},
{
"code": null,
"e": 24885,
"s": 24727,
"text": "Without any option paste merges the files in parallel. The paste command writes corresponding lines from the files with tab as a deliminator on the terminal."
},
{
"code": null,
"e": 25066,
"s": 24885,
"text": "$ paste number state capital\n1 Arunachal Pradesh Itanagar\n2 Assam Dispur\n3 Andhra Pradesh Hyderabad\n4 Bihar Patna\n5 Chhattisgrah Raipur\n"
},
{
"code": null,
"e": 25128,
"s": 25066,
"text": "In the above command three files are merges by paste command."
},
{
"code": null,
"e": 25137,
"s": 25128,
"text": "Options:"
},
{
"code": null,
"e": 25428,
"s": 25137,
"text": "1. -d (delimiter): Paste command uses the tab delimiter by default for merging the files. The delimiter can be changed to any other character by using the -d option. If more than one character is specified as delimiter then paste uses it in a circular fashion for each file line separation."
},
{
"code": null,
"e": 25912,
"s": 25428,
"text": "Only one character is specified\n$ paste -d \"|\" number state capital\n1|Arunachal Pradesh|Itanagar\n2|Assam|Dispur\n3|Andhra Pradesh|Hyderabad\n4|Bihar|Patna\n5|Chhattisgrah|Raipur\n\nMore than one character is specified\n$ paste -d \"|,\" number state capital\n1|Arunachal Pradesh,Itanagar\n2|Assam,Dispur\n3|Andhra Pradesh,Hyderabad\n4|Bihar,Patna\n5|Chhattisgrah,Raipur\n\nFirst and second file is separated by '|' and second and third is separated by ','.\nAfter that list is exhausted and reused.\n"
},
{
"code": null,
"e": 26165,
"s": 25912,
"text": "2. -s (serial): We can merge the files in sequentially manner using the -s option. It reads all the lines from a single file and merges all these lines into a single line with each line separated by tab. And these single lines are separated by newline."
},
{
"code": null,
"e": 26356,
"s": 26165,
"text": "$ paste -s number state capital\n1 2 3 4 5\nArunachal Pradesh Assam Andhra Pradesh Bihar Chhattisgrah\nItanagar Dispur Hyderabad Patna Raipur\n"
},
{
"code": null,
"e": 26619,
"s": 26356,
"text": "In the above command, first it reads data from number file and merge them into single line with each line separated by tab. After that newline character is introduced and reading from next file i.e. state starts and process repeats again till all files are read."
},
{
"code": null,
"e": 26733,
"s": 26619,
"text": "Combination of -d and -s: The following example shows how to specify a delimiter for sequential merging of files:"
},
{
"code": null,
"e": 26880,
"s": 26733,
"text": "$ paste -s -d \":\" number state capital\n1:2:3:4:5\nArunachal Pradesh:Assam:Andhra Pradesh:Bihar:Chhattisgrah\nItanagar:Dispur:Hyderabad:Patna:Raipur\n"
},
{
"code": null,
"e": 26988,
"s": 26880,
"text": "3. –version: This option is used to display the version of paste which is currently running on your system."
},
{
"code": null,
"e": 27326,
"s": 26988,
"text": "$ paste --version\npaste (GNU coreutils) 8.26\nPackaged by Cygwin (8.26-2)\nCopyright (C) 2016 Free Software Foundation, Inc.\nLicense GPLv3+: GNU GPL version 3 or later .\nThis is free software: you are free to change and redistribute it.\nThere is NO WARRANTY, to the extent permitted by law.\n\nWritten by David M. Ihnat and David MacKenzie.\n"
},
{
"code": null,
"e": 27356,
"s": 27326,
"text": "Applications of Paste Command"
},
{
"code": null,
"e": 27555,
"s": 27356,
"text": "1. Combining N consecutive lines: The paste command can also be used to merge N consecutive lines from a file into a single line. Here N can be specified by specifying number hyphens(-) after paste."
},
{
"code": null,
"e": 27739,
"s": 27555,
"text": "With 2 hyphens\n$ cat capital | paste - -\nItanagar Dispur\nHyderabad Patna\nRaipur\n\nWith 3 hyphens\n$ paste - - - < capital\nItanagar Dispur Hyderabad\nPatna Raipur\n\n"
},
{
"code": null,
"e": 28114,
"s": 27739,
"text": "2. Combination with other commands: Even though paste require at least two files for concatenating lines, but data from one file can be given from shell. Like in our example below, cut command is used with -f option for cutting out first field of state file and output is pipelined with paste command having one file name and instead of second file name hyphen is specified."
},
{
"code": null,
"e": 28184,
"s": 28114,
"text": "Note: If hyphen is not specified then input from shell is not pasted."
},
{
"code": null,
"e": 28383,
"s": 28184,
"text": "Without hypen\n$ cut -d \" \" -f 1 state | paste number\n1\n2\n3\n4\n5\n\nWith hypen\n$ cut -d \" \" -f 1 state | paste number -\n1 Arunachal\n2 Assam\n3 Andhra\n4 Bihar\n5 Chhattisgrah\n"
},
{
"code": null,
"e": 28454,
"s": 28383,
"text": "Ordering of pasting can be changed by altering the location of hyphen:"
},
{
"code": null,
"e": 28562,
"s": 28454,
"text": "$ cut -d \" \" -f 1 state | paste - number\nArunachal 1\nAssam 2\nAndhra 3\nBihar 4\nChhattisgrah 5\n"
},
{
"code": null,
"e": 29397,
"s": 28562,
"text": "YouTubeGeeksforGeeks500K subscribersLinux Tutorials | paste command | GeeksforGeeksWatch laterShareCopy link25/36InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:07•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=ilV6dcTJzzE\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 29696,
"s": 29397,
"text": "This article is contributed by Akash Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 29821,
"s": 29696,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29835,
"s": 29821,
"text": "linux-command"
},
{
"code": null,
"e": 29866,
"s": 29835,
"text": "Linux-text-processing-commands"
},
{
"code": null,
"e": 29877,
"s": 29866,
"text": "Linux-Unix"
},
{
"code": null,
"e": 29975,
"s": 29877,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29984,
"s": 29975,
"text": "Comments"
},
{
"code": null,
"e": 29997,
"s": 29984,
"text": "Old Comments"
},
{
"code": null,
"e": 30032,
"s": 29997,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 30070,
"s": 30032,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 30108,
"s": 30070,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 30143,
"s": 30108,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 30179,
"s": 30143,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 30223,
"s": 30179,
"text": "Mutex lock for Linux Thread Synchronization"
},
{
"code": null,
"e": 30260,
"s": 30223,
"text": "touch command in Linux with Examples"
},
{
"code": null,
"e": 30296,
"s": 30260,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 30315,
"s": 30296,
"text": "Compiling with g++"
}
] |
C# - Stack Class
|
It represents a last-in, first out collection of object. It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item.
The following table lists some commonly used properties of the Stack class −
Count
Gets the number of elements contained in the Stack.
The following table lists some of the commonly used methods of the Stack class −
public virtual void Clear();
Removes all elements from the Stack.
public virtual bool Contains(object obj);
Determines whether an element is in the Stack.
public virtual object Peek();
Returns the object at the top of the Stack without removing it.
public virtual object Pop();
Removes and returns the object at the top of the Stack.
public virtual void Push(object obj);
Inserts an object at the top of the Stack.
public virtual object[] ToArray();
Copies the Stack to a new array.
The following example demonstrates use of Stack −
using System;
using System.Collections;
namespace CollectionsApplication {
class Program {
static void Main(string[] args) {
Stack st = new Stack();
st.Push('A');
st.Push('M');
st.Push('G');
st.Push('W');
Console.WriteLine("Current stack: ");
foreach (char c in st) {
Console.Write(c + " ");
}
Console.WriteLine();
st.Push('V');
st.Push('H');
Console.WriteLine("The next poppable value in stack: {0}", st.Peek());
Console.WriteLine("Current stack: ");
foreach (char c in st) {
Console.Write(c + " ");
}
Console.WriteLine();
Console.WriteLine("Removing values ");
st.Pop();
st.Pop();
st.Pop();
Console.WriteLine("Current stack: ");
foreach (char c in st) {
Console.Write(c + " ");
}
}
}
}
When the above code is compiled and executed, it produces the following result −
Current stack:
W G M A
The next poppable value in stack: H
Current stack:
H V W G M A
Removing values
Current stack:
G M A
119 Lectures
23.5 hours
Raja Biswas
37 Lectures
13 hours
Trevoir Williams
16 Lectures
1 hours
Peter Jepson
159 Lectures
21.5 hours
Ebenezer Ogbu
193 Lectures
17 hours
Arnold Higuit
24 Lectures
2.5 hours
Eric Frick
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2509,
"s": 2270,
"text": "It represents a last-in, first out collection of object.\tIt is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item."
},
{
"code": null,
"e": 2586,
"s": 2509,
"text": "The following table lists some commonly used properties of the Stack class −"
},
{
"code": null,
"e": 2592,
"s": 2586,
"text": "Count"
},
{
"code": null,
"e": 2644,
"s": 2592,
"text": "Gets the number of elements contained in the Stack."
},
{
"code": null,
"e": 2725,
"s": 2644,
"text": "The following table lists some of the commonly used methods of the Stack class −"
},
{
"code": null,
"e": 2754,
"s": 2725,
"text": "public virtual void Clear();"
},
{
"code": null,
"e": 2791,
"s": 2754,
"text": "Removes all elements from the Stack."
},
{
"code": null,
"e": 2833,
"s": 2791,
"text": "public virtual bool Contains(object obj);"
},
{
"code": null,
"e": 2880,
"s": 2833,
"text": "Determines whether an element is in the Stack."
},
{
"code": null,
"e": 2910,
"s": 2880,
"text": "public virtual object Peek();"
},
{
"code": null,
"e": 2974,
"s": 2910,
"text": "Returns the object at the top of the Stack without removing it."
},
{
"code": null,
"e": 3003,
"s": 2974,
"text": "public virtual object Pop();"
},
{
"code": null,
"e": 3059,
"s": 3003,
"text": "Removes and returns the object at the top of the Stack."
},
{
"code": null,
"e": 3097,
"s": 3059,
"text": "public virtual void Push(object obj);"
},
{
"code": null,
"e": 3140,
"s": 3097,
"text": "Inserts an object at the top of the Stack."
},
{
"code": null,
"e": 3175,
"s": 3140,
"text": "public virtual object[] ToArray();"
},
{
"code": null,
"e": 3208,
"s": 3175,
"text": "Copies the Stack to a new array."
},
{
"code": null,
"e": 3258,
"s": 3208,
"text": "The following example demonstrates use of Stack −"
},
{
"code": null,
"e": 4278,
"s": 3258,
"text": "using System;\nusing System.Collections;\n\nnamespace CollectionsApplication {\n class Program {\n static void Main(string[] args) {\n Stack st = new Stack();\n \n st.Push('A');\n st.Push('M');\n st.Push('G');\n st.Push('W');\n \n Console.WriteLine(\"Current stack: \");\n foreach (char c in st) {\n Console.Write(c + \" \");\n }\n Console.WriteLine();\n \n st.Push('V');\n st.Push('H');\n Console.WriteLine(\"The next poppable value in stack: {0}\", st.Peek());\n Console.WriteLine(\"Current stack: \");\n \n foreach (char c in st) {\n Console.Write(c + \" \");\n }\n \n Console.WriteLine();\n \n Console.WriteLine(\"Removing values \");\n st.Pop();\n st.Pop();\n st.Pop();\n \n Console.WriteLine(\"Current stack: \");\n foreach (char c in st) {\n Console.Write(c + \" \");\n }\n }\n }\n}"
},
{
"code": null,
"e": 4359,
"s": 4278,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4486,
"s": 4359,
"text": "Current stack: \nW G M A\nThe next poppable value in stack: H\nCurrent stack: \nH V W G M A\nRemoving values\nCurrent stack: \nG M A\n"
},
{
"code": null,
"e": 4523,
"s": 4486,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 4536,
"s": 4523,
"text": " Raja Biswas"
},
{
"code": null,
"e": 4570,
"s": 4536,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4588,
"s": 4570,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 4621,
"s": 4588,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4635,
"s": 4621,
"text": " Peter Jepson"
},
{
"code": null,
"e": 4672,
"s": 4635,
"text": "\n 159 Lectures \n 21.5 hours \n"
},
{
"code": null,
"e": 4687,
"s": 4672,
"text": " Ebenezer Ogbu"
},
{
"code": null,
"e": 4722,
"s": 4687,
"text": "\n 193 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 4737,
"s": 4722,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 4772,
"s": 4737,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4784,
"s": 4772,
"text": " Eric Frick"
},
{
"code": null,
"e": 4791,
"s": 4784,
"text": " Print"
},
{
"code": null,
"e": 4802,
"s": 4791,
"text": " Add Notes"
}
] |
How does Constraint Layout works in android?
|
In simple words, constraint layout is an advanced version of a Relative layout. It is used to reduce the child view hierarchies and improve the performance.
Properties of constraint layout as shown below -
Wrap Content –It wrap the view size according to data.
Any Size – This is very similar to match parent.
Fixed Size – This allows standard height and width(fixed sizes).
In the above example we have shown the button with all properties, now look into code level as shown below -
<Button
android:layout_width="wrap_content"
android:layout_height="53dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.391"
app:layout_constraintStart_toStartOf="@+id/data1"
app:layout_constraintTop_toTopOf="parent" />
In the above, we have declare layout margin-top, bottom, start and end. those are the standard distance (Similar to match parent)
There is two bias available in constraint layout as horizontal and vertical. Gravity space in a horizontal way and Vertical way.
By clicking view, it shows all hierarchies which are connected to the view.
By clicking view, you will get "X" color icon button to remove hierarchy with other view or parent view.
This example demonstrates how to use constraint layout 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"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/layout"
android:gravity="center"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/data"
android:layout_width="wrap_content"
android:gravity="center"
android:textSize="30sp"
android:text="www.tutorialspoint.com"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/data1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="80dp"
android:layout_marginEnd="8dp"
android:gravity="center"
android:text="www.tutorialspoint.com"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_width="wrap_content"
android:layout_height="53dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.43"
app:layout_constraintStart_toStartOf="@+id/data1"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
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 Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code
|
[
{
"code": null,
"e": 1219,
"s": 1062,
"text": "In simple words, constraint layout is an advanced version of a Relative layout. It is used to reduce the child view hierarchies and improve the performance."
},
{
"code": null,
"e": 1268,
"s": 1219,
"text": "Properties of constraint layout as shown below -"
},
{
"code": null,
"e": 1324,
"s": 1268,
"text": "Wrap Content –It wrap the view size according to data. "
},
{
"code": null,
"e": 1374,
"s": 1324,
"text": "Any Size – This is very similar to match parent. "
},
{
"code": null,
"e": 1440,
"s": 1374,
"text": "Fixed Size – This allows standard height and width(fixed sizes). "
},
{
"code": null,
"e": 1549,
"s": 1440,
"text": "In the above example we have shown the button with all properties, now look into code level as shown below -"
},
{
"code": null,
"e": 2039,
"s": 1549,
"text": "<Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"53dp\"\n android:layout_marginStart=\"8dp\"\n android:layout_marginTop=\"8dp\"\n android:layout_marginEnd=\"8dp\"\n android:layout_marginBottom=\"8dp\"\n android:text=\"Button\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintHorizontal_bias=\"0.391\"\n app:layout_constraintStart_toStartOf=\"@+id/data1\"\n app:layout_constraintTop_toTopOf=\"parent\" />"
},
{
"code": null,
"e": 2169,
"s": 2039,
"text": "In the above, we have declare layout margin-top, bottom, start and end. those are the standard distance (Similar to match parent)"
},
{
"code": null,
"e": 2298,
"s": 2169,
"text": "There is two bias available in constraint layout as horizontal and vertical. Gravity space in a horizontal way and Vertical way."
},
{
"code": null,
"e": 2374,
"s": 2298,
"text": "By clicking view, it shows all hierarchies which are connected to the view."
},
{
"code": null,
"e": 2479,
"s": 2374,
"text": "By clicking view, you will get \"X\" color icon button to remove hierarchy with other view or parent view."
},
{
"code": null,
"e": 2546,
"s": 2479,
"text": "This example demonstrates how to use constraint layout in android."
},
{
"code": null,
"e": 2675,
"s": 2546,
"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": 2739,
"s": 2675,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml"
},
{
"code": null,
"e": 4466,
"s": 2739,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<android.support.constraint.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:id=\"@+id/layout\"\n android:gravity=\"center\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\">\n <TextView\n android:id=\"@+id/data\"\n android:layout_width=\"wrap_content\"\n android:gravity=\"center\"\n android:textSize=\"30sp\"\n android:text=\"www.tutorialspoint.com\"\n android:layout_height=\"wrap_content\" />\n <TextView\n android:id=\"@+id/data1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginStart=\"8dp\"\n android:layout_marginTop=\"80dp\"\n android:layout_marginEnd=\"8dp\"\n android:gravity=\"center\"\n android:text=\"www.tutorialspoint.com\"\n android:textSize=\"30sp\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"53dp\"\n android:layout_marginStart=\"8dp\"\n android:layout_marginTop=\"8dp\"\n android:layout_marginEnd=\"8dp\"\n android:layout_marginBottom=\"8dp\"\n android:text=\"Button\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintHorizontal_bias=\"0.43\"\n app:layout_constraintStart_toStartOf=\"@+id/data1\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 4817,
"s": 4466,
"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 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": 4857,
"s": 4817,
"text": "Click here to download the project code"
}
] |
Difference between const char* p, char * const p, and const char * const p in C
|
In C programming language, *p represents the value stored in a pointer and p represents the address of the value, is referred as a pointer.
const char* and char const* says that the pointer can point to a constant char and value of char pointed by this pointer cannot be changed. But we can change the value of pointer as it is not constant and it can point to another constant char.
char* const says that the pointer can point to a char and value of char pointed by this pointer can be changed. But we cannot change the value of pointer as it is now constant and it cannot point to another char.
const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant char.
Thumb rule is to naming syntax from right to left.
// constant pointer to constant char
const char * const
// constant pointer to char
char * const
// pointer to constant char
const char *
Uncomment the commented errorneous codes and see the error.
Live Demo
#include <stdio.h>
int main() {
//Example: char const*
//Note: char const* is same as const char*
const char p = 'A';
// q is a pointer to const char
char const* q = &p;
//Invalid asssignment
// value of p cannot be changed
// error: assignment of read-only location '*q'
//*q = 'B';
const char r = 'C';
//q can point to another const char
q = &r;
printf("%c\n", *q);
//Example: char* const
char u = 'D';
char * const t = &u;
//You can change the value
*t = 'E';
printf("%c", *t);
// Invalid asssignment
// t cannot be changed
// error: assignment of read-only variable 't'
//t = &r;
//Example: char const* const
char const* const s = &p;
// Invalid asssignment
// value of s cannot be changed
// error: assignment of read-only location '*s'
// *s = 'D';
// Invalid asssignment
// s cannot be changed
// error: assignment of read-only variable 's'
// s = &r;
return 0;
}
C
E
|
[
{
"code": null,
"e": 1202,
"s": 1062,
"text": "In C programming language, *p represents the value stored in a pointer and p represents the address of the value, is referred as a pointer."
},
{
"code": null,
"e": 1446,
"s": 1202,
"text": "const char* and char const* says that the pointer can point to a constant char and value of char pointed by this pointer cannot be changed. But we can change the value of pointer as it is not constant and it can point to another constant char."
},
{
"code": null,
"e": 1659,
"s": 1446,
"text": "char* const says that the pointer can point to a char and value of char pointed by this pointer can be changed. But we cannot change the value of pointer as it is now constant and it cannot point to another char."
},
{
"code": null,
"e": 1903,
"s": 1659,
"text": "const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant char."
},
{
"code": null,
"e": 1954,
"s": 1903,
"text": "Thumb rule is to naming syntax from right to left."
},
{
"code": null,
"e": 2092,
"s": 1954,
"text": "// constant pointer to constant char\nconst char * const\n// constant pointer to char\nchar * const\n// pointer to constant char\nconst char *"
},
{
"code": null,
"e": 2152,
"s": 2092,
"text": "Uncomment the commented errorneous codes and see the error."
},
{
"code": null,
"e": 2163,
"s": 2152,
"text": " Live Demo"
},
{
"code": null,
"e": 3136,
"s": 2163,
"text": "#include <stdio.h>\nint main() {\n //Example: char const*\n //Note: char const* is same as const char*\n const char p = 'A';\n // q is a pointer to const char\n char const* q = &p;\n //Invalid asssignment\n // value of p cannot be changed\n // error: assignment of read-only location '*q'\n //*q = 'B';\n const char r = 'C';\n //q can point to another const char\n q = &r;\n printf(\"%c\\n\", *q);\n //Example: char* const\n char u = 'D';\n char * const t = &u;\n //You can change the value\n *t = 'E';\n printf(\"%c\", *t);\n // Invalid asssignment\n // t cannot be changed\n // error: assignment of read-only variable 't'\n //t = &r;\n //Example: char const* const\n char const* const s = &p;\n // Invalid asssignment\n // value of s cannot be changed\n // error: assignment of read-only location '*s'\n // *s = 'D';\n // Invalid asssignment\n // s cannot be changed\n // error: assignment of read-only variable 's'\n // s = &r;\n return 0;\n}"
},
{
"code": null,
"e": 3140,
"s": 3136,
"text": "C\nE"
}
] |
MongoDB aggregation to combine or merge fields and then count?
|
To combine or merge fields and then perform count, use $group along with $sum and $sort. Let us create a collection with documents −
> db.demo647.insertOne({"Subject":"MySQL"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9c86316c954c74be91e6ee")
}
> db.demo647.insertOne({"Subject":"MongoDB"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9c86356c954c74be91e6ef")
}
> db.demo647.insertOne({"Subject":"MySQL"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9c86376c954c74be91e6f0")
}
> db.demo647.insertOne({"Subject":"SQL Server"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9c86406c954c74be91e6f1")
}
> db.demo647.insertOne({"Subject":"MongoDB"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9c86436c954c74be91e6f2")
}
> db.demo647.insertOne({"Subject":"PL/SQL"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9c864b6c954c74be91e6f3")
}
> db.demo647.insertOne({"Subject":"MongoDB"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9c86c16c954c74be91e6f4")
}
Display all documents from a collection with the help of find() method −
> db.demo647.find();
This will produce the following output −
{ "_id" : ObjectId("5e9c86316c954c74be91e6ee"), "Subject" : "MySQL" }
{ "_id" : ObjectId("5e9c86356c954c74be91e6ef"), "Subject" : "MongoDB" }
{ "_id" : ObjectId("5e9c86376c954c74be91e6f0"), "Subject" : "MySQL" }
{ "_id" : ObjectId("5e9c86406c954c74be91e6f1"), "Subject" : "SQL Server" }
{ "_id" : ObjectId("5e9c86436c954c74be91e6f2"), "Subject" : "MongoDB" }
{ "_id" : ObjectId("5e9c864b6c954c74be91e6f3"), "Subject" : "PL/SQL" }
{ "_id" : ObjectId("5e9c86c16c954c74be91e6f4"), "Subject" : "MongoDB" }
Following is the query to combine or merge fields then count −
> db.demo647.aggregate([ { "$group": { "_id": "$Subject", "COUNT": { "$sum": 1 } } }, { "$sort": { "COUNT": -1 } }, { "$limit": 2 } ] );
This will produce the following output −
{ "_id" : "MongoDB", "COUNT" : 3 }
{ "_id" : "MySQL", "COUNT" : 2 }
|
[
{
"code": null,
"e": 1195,
"s": 1062,
"text": "To combine or merge fields and then perform count, use $group along with $sum and $sort. Let us create a collection with documents −"
},
{
"code": null,
"e": 2117,
"s": 1195,
"text": "> db.demo647.insertOne({\"Subject\":\"MySQL\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e9c86316c954c74be91e6ee\")\n}\n> db.demo647.insertOne({\"Subject\":\"MongoDB\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e9c86356c954c74be91e6ef\")\n}\n> db.demo647.insertOne({\"Subject\":\"MySQL\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e9c86376c954c74be91e6f0\")\n}\n> db.demo647.insertOne({\"Subject\":\"SQL Server\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e9c86406c954c74be91e6f1\")\n}\n> db.demo647.insertOne({\"Subject\":\"MongoDB\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e9c86436c954c74be91e6f2\")\n}\n> db.demo647.insertOne({\"Subject\":\"PL/SQL\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e9c864b6c954c74be91e6f3\")\n}\n> db.demo647.insertOne({\"Subject\":\"MongoDB\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e9c86c16c954c74be91e6f4\")\n}"
},
{
"code": null,
"e": 2190,
"s": 2117,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 2211,
"s": 2190,
"text": "> db.demo647.find();"
},
{
"code": null,
"e": 2252,
"s": 2211,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2754,
"s": 2252,
"text": "{ \"_id\" : ObjectId(\"5e9c86316c954c74be91e6ee\"), \"Subject\" : \"MySQL\" }\n{ \"_id\" : ObjectId(\"5e9c86356c954c74be91e6ef\"), \"Subject\" : \"MongoDB\" }\n{ \"_id\" : ObjectId(\"5e9c86376c954c74be91e6f0\"), \"Subject\" : \"MySQL\" }\n{ \"_id\" : ObjectId(\"5e9c86406c954c74be91e6f1\"), \"Subject\" : \"SQL Server\" }\n{ \"_id\" : ObjectId(\"5e9c86436c954c74be91e6f2\"), \"Subject\" : \"MongoDB\" }\n{ \"_id\" : ObjectId(\"5e9c864b6c954c74be91e6f3\"), \"Subject\" : \"PL/SQL\" }\n{ \"_id\" : ObjectId(\"5e9c86c16c954c74be91e6f4\"), \"Subject\" : \"MongoDB\" }"
},
{
"code": null,
"e": 2817,
"s": 2754,
"text": "Following is the query to combine or merge fields then count −"
},
{
"code": null,
"e": 2954,
"s": 2817,
"text": "> db.demo647.aggregate([ { \"$group\": { \"_id\": \"$Subject\", \"COUNT\": { \"$sum\": 1 } } }, { \"$sort\": { \"COUNT\": -1 } }, { \"$limit\": 2 } ] );"
},
{
"code": null,
"e": 2995,
"s": 2954,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3063,
"s": 2995,
"text": "{ \"_id\" : \"MongoDB\", \"COUNT\" : 3 }\n{ \"_id\" : \"MySQL\", \"COUNT\" : 2 }"
}
] |
Nagios - Hosts and Services
|
Nagios is the most popular tool which is used to monitor hosts and services running in your IT infrastructure. Hosts and service configurations are the building blocks of Nagios Core.
Host is just like a computer; it can be a physical device or virtual.
Host is just like a computer; it can be a physical device or virtual.
Services are those which are used by Nagios to check something about a host.
Services are those which are used by Nagios to check something about a host.
You can create a host file inside the server directory of Nagios and mention the host and service definitions. For example −
sudo gedit /usr/local/nagios/etc/servers/ubuntu_host.cfg
define host {
use linux-server
host_name ubuntu_host
alias Ubuntu Host
address 192.168.1.10
register 1
}
define service {
host_name ubuntu_host
service_description PING
check_command check_ping!100.0,20%!500.0,60%
max_check_attempts 2
check_interval 2
retry_interval 2
check_period 24x7
check_freshness 1
contact_groups admins
notification_interval 2
notification_period 24x7
notifications_enabled 1
register 1
}
The above definitions add a host called ubuntu_host and defines the services which will run on this host. When you restart the Nagios, this host will start getting monitored by Nagios and the specified services will run.
There are many more services in Nagios which can be used to monitor pretty much anything on the running host.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2080,
"s": 1896,
"text": "Nagios is the most popular tool which is used to monitor hosts and services running in your IT infrastructure. Hosts and service configurations are the building blocks of Nagios Core."
},
{
"code": null,
"e": 2150,
"s": 2080,
"text": "Host is just like a computer; it can be a physical device or virtual."
},
{
"code": null,
"e": 2220,
"s": 2150,
"text": "Host is just like a computer; it can be a physical device or virtual."
},
{
"code": null,
"e": 2297,
"s": 2220,
"text": "Services are those which are used by Nagios to check something about a host."
},
{
"code": null,
"e": 2374,
"s": 2297,
"text": "Services are those which are used by Nagios to check something about a host."
},
{
"code": null,
"e": 2499,
"s": 2374,
"text": "You can create a host file inside the server directory of Nagios and mention the host and service definitions. For example −"
},
{
"code": null,
"e": 2557,
"s": 2499,
"text": "sudo gedit /usr/local/nagios/etc/servers/ubuntu_host.cfg\n"
},
{
"code": null,
"e": 3024,
"s": 2557,
"text": "define host {\n use linux-server\n host_name ubuntu_host\n alias Ubuntu Host\n address 192.168.1.10\n register 1\n}\ndefine service {\n host_name ubuntu_host\n service_description PING\n check_command check_ping!100.0,20%!500.0,60%\n max_check_attempts 2\n check_interval 2\n retry_interval 2\n check_period 24x7\n check_freshness 1\n contact_groups admins\n notification_interval 2\n notification_period 24x7\n notifications_enabled 1\n register 1\n}"
},
{
"code": null,
"e": 3245,
"s": 3024,
"text": "The above definitions add a host called ubuntu_host and defines the services which will run on this host. When you restart the Nagios, this host will start getting monitored by Nagios and the specified services will run."
},
{
"code": null,
"e": 3355,
"s": 3245,
"text": "There are many more services in Nagios which can be used to monitor pretty much anything on the running host."
},
{
"code": null,
"e": 3362,
"s": 3355,
"text": " Print"
},
{
"code": null,
"e": 3373,
"s": 3362,
"text": " Add Notes"
}
] |
Multi-Sample Dropout in Keras. Accelerated Training and Better... | by Marco Cerliani | Towards Data Science
|
Dropout is an efficient regularization instrument for avoiding overfitting of deep neural networks. It works very simply randomly discarding a portion of neurons during training; as a result, a generalization occurs because in this way neurons depend no more on each other. Dropout is easily applicable in every neural network structure and it can be also used for various purposes: for example, I used it to estimate neural network uncertainty with a bayesian approach in a previous post.
In this post, I try to reproduce the results presented in this paper; which introduced a technique called Multi-Sample Dropout. As declared by the author, its scopes are:
accelerate training and improve generalization over the original dropout;
reduce computational cost because most of the computation time is consumed in the layers below (often convolutional or recurrent) and the weights in the layers at the top are shared;
achieve lower error rates and losses.
I want to applicate the procedures introduced in the paper, in a NLP problem. I found a valuable dataset on Kaggle. The News Headlines Dataset was provided to carry out sarcasm detection in sentences. Texts inside this dataset are collected from the web with the relative annotation of sarcastic or not sarcastic.
I chose a NLP task because it permits us to try a recurrent model structure with consistent training time. In addition, the usage of dropout and fully connected layer near the end of the network makes the execution time not significant.
The basic idea is quite simple: create multiple dropout samples instead of only one, as depicted in the figure below. The dropout layer and several layers after the dropout are duplicated for each dropout sample. The “dropout”, “fully connected” and “softmax + loss func” layers are duplicated. Different masks are used for each dropout sample in the dropout layer so that a different subset of neurons is used for each dropout sample. In contrast, the parameters (i.e., connection weights) are shared between the duplicated fully connected layers. The loss is computed for each dropout sample using the same loss function, e.g., cross entropy, and the final loss value is obtained by averaging the loss values for all dropout samples. This final loss value is used as the objective function for optimization during training. The class label with the highest value in the average of outputs from the last fully connected layer is taken as the prediction.
In Keras language all the concepts can be implemented with simple code:
def get_model(num):inp = Input(shape=(max_len,)) emb = Embedding(len(tokenizer.word_index) + 1, 64)(inp) x = SpatialDropout1D(0.2)(emb) x = GRU(128, return_sequences=True, activation='relu')(x) out = GRU(32, activation='relu')(x) dense = [] FC = Dense(32, activation='relu') for p in np.linspace(0.1,0.5, num): x = Dropout(p)(out) x = FC(x) x = Dense(y_train.shape[1], activation='softmax')(x) dense.append(x) out = Average()(dense) model = Model(inp, out) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model
As a recurrent block, at the bottom of the model, I’ve used GRU layers. The number of dropout samples is defined as parameter when the model is initialized. The fully connected layer at the top shares the weights in every dropout sample. I’ve built every dropout sample with a different mask and different probabilities from 0.1 to 0.5, and not always 0.5 (this is a little change that I allowed myself to adopt). The network has multiple output layers as many as the dropout sample. The final step of our network is an average layer which combines the previous fully connected layer outputs as a simple average. In this way, the final loss value is computed as the average of outputs of our dropout samples.
At the end of the training phase, we are able to achieve a final accuracy of around 0.85% on the test set.
In this post, I try to reproduce a technique called multi-sample dropout. It is an upgrading of the classical dropout. It can be simply applied in every neural network structure (also in deep ones) and offers a costless way to better generalize and improve results especially in classification tasks.
CHECK MY GITHUB REPO
Keep in touch: Linkedin
REFERENCES
Multi-Sample Dropout for Accelerated Training and Better Generalization: Hiroshi Inoue, IBM Research, Tokyo
|
[
{
"code": null,
"e": 536,
"s": 46,
"text": "Dropout is an efficient regularization instrument for avoiding overfitting of deep neural networks. It works very simply randomly discarding a portion of neurons during training; as a result, a generalization occurs because in this way neurons depend no more on each other. Dropout is easily applicable in every neural network structure and it can be also used for various purposes: for example, I used it to estimate neural network uncertainty with a bayesian approach in a previous post."
},
{
"code": null,
"e": 707,
"s": 536,
"text": "In this post, I try to reproduce the results presented in this paper; which introduced a technique called Multi-Sample Dropout. As declared by the author, its scopes are:"
},
{
"code": null,
"e": 781,
"s": 707,
"text": "accelerate training and improve generalization over the original dropout;"
},
{
"code": null,
"e": 964,
"s": 781,
"text": "reduce computational cost because most of the computation time is consumed in the layers below (often convolutional or recurrent) and the weights in the layers at the top are shared;"
},
{
"code": null,
"e": 1002,
"s": 964,
"text": "achieve lower error rates and losses."
},
{
"code": null,
"e": 1316,
"s": 1002,
"text": "I want to applicate the procedures introduced in the paper, in a NLP problem. I found a valuable dataset on Kaggle. The News Headlines Dataset was provided to carry out sarcasm detection in sentences. Texts inside this dataset are collected from the web with the relative annotation of sarcastic or not sarcastic."
},
{
"code": null,
"e": 1553,
"s": 1316,
"text": "I chose a NLP task because it permits us to try a recurrent model structure with consistent training time. In addition, the usage of dropout and fully connected layer near the end of the network makes the execution time not significant."
},
{
"code": null,
"e": 2508,
"s": 1553,
"text": "The basic idea is quite simple: create multiple dropout samples instead of only one, as depicted in the figure below. The dropout layer and several layers after the dropout are duplicated for each dropout sample. The “dropout”, “fully connected” and “softmax + loss func” layers are duplicated. Different masks are used for each dropout sample in the dropout layer so that a different subset of neurons is used for each dropout sample. In contrast, the parameters (i.e., connection weights) are shared between the duplicated fully connected layers. The loss is computed for each dropout sample using the same loss function, e.g., cross entropy, and the final loss value is obtained by averaging the loss values for all dropout samples. This final loss value is used as the objective function for optimization during training. The class label with the highest value in the average of outputs from the last fully connected layer is taken as the prediction."
},
{
"code": null,
"e": 2580,
"s": 2508,
"text": "In Keras language all the concepts can be implemented with simple code:"
},
{
"code": null,
"e": 3228,
"s": 2580,
"text": "def get_model(num):inp = Input(shape=(max_len,)) emb = Embedding(len(tokenizer.word_index) + 1, 64)(inp) x = SpatialDropout1D(0.2)(emb) x = GRU(128, return_sequences=True, activation='relu')(x) out = GRU(32, activation='relu')(x) dense = [] FC = Dense(32, activation='relu') for p in np.linspace(0.1,0.5, num): x = Dropout(p)(out) x = FC(x) x = Dense(y_train.shape[1], activation='softmax')(x) dense.append(x) out = Average()(dense) model = Model(inp, out) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model"
},
{
"code": null,
"e": 3937,
"s": 3228,
"text": "As a recurrent block, at the bottom of the model, I’ve used GRU layers. The number of dropout samples is defined as parameter when the model is initialized. The fully connected layer at the top shares the weights in every dropout sample. I’ve built every dropout sample with a different mask and different probabilities from 0.1 to 0.5, and not always 0.5 (this is a little change that I allowed myself to adopt). The network has multiple output layers as many as the dropout sample. The final step of our network is an average layer which combines the previous fully connected layer outputs as a simple average. In this way, the final loss value is computed as the average of outputs of our dropout samples."
},
{
"code": null,
"e": 4044,
"s": 3937,
"text": "At the end of the training phase, we are able to achieve a final accuracy of around 0.85% on the test set."
},
{
"code": null,
"e": 4345,
"s": 4044,
"text": "In this post, I try to reproduce a technique called multi-sample dropout. It is an upgrading of the classical dropout. It can be simply applied in every neural network structure (also in deep ones) and offers a costless way to better generalize and improve results especially in classification tasks."
},
{
"code": null,
"e": 4366,
"s": 4345,
"text": "CHECK MY GITHUB REPO"
},
{
"code": null,
"e": 4390,
"s": 4366,
"text": "Keep in touch: Linkedin"
},
{
"code": null,
"e": 4401,
"s": 4390,
"text": "REFERENCES"
}
] |
How to compare date strings in Python?
|
Python date implementations support all the comparision operators. So, if you are using the datetime module to create and handle date objects, you can simply use the <, >, <=, >=, etc. operators on the dates. This makes it very easy to compare and check dates for validations, etc.
from datetime import datetime
from datetime import timedelta
today = datetime.today()
yesterday = today - timedelta(days=1)
print(today < yesterday)
print(today > yesterday)
print(today == yesterday)
This will give the output −
False
True
False
|
[
{
"code": null,
"e": 1344,
"s": 1062,
"text": "Python date implementations support all the comparision operators. So, if you are using the datetime module to create and handle date objects, you can simply use the <, >, <=, >=, etc. operators on the dates. This makes it very easy to compare and check dates for validations, etc."
},
{
"code": null,
"e": 1544,
"s": 1344,
"text": "from datetime import datetime\nfrom datetime import timedelta\ntoday = datetime.today()\nyesterday = today - timedelta(days=1)\nprint(today < yesterday)\nprint(today > yesterday)\nprint(today == yesterday)"
},
{
"code": null,
"e": 1572,
"s": 1544,
"text": "This will give the output −"
},
{
"code": null,
"e": 1589,
"s": 1572,
"text": "False\nTrue\nFalse"
}
] |
Comparator in Kotlin - GeeksforGeeks
|
02 Aug, 2019
In programming contexts, as there arises a need for a new type, there is also a major task of ordering the instances of a type. To compare two instances of a type we implement Comparable interface. However, since in ordering instances they must be compared automatically and also since the order can vary according to various parameters, Kotlin provides a simple Comparator interface. This interface compares two objects of a type and arranges them in an order.
compare: This function compares two instance of a type and returns zero if both are equal, a negative number if second instance is bigger otherwise returns a positive number.
abstract fun compare(a: T, b: T): Int
reversed: This function takes a comparator as an argument and returns the comparator with the ordering reversed as that of the passed comparator.
fun <T> Comparator<T>.reversed(): Comparator<T>
then: This function combines two comparator, and the second one is used only when the values are equal according to the first comparator.
infix fun <T> Comparator<T>.then(
comparator: Comparator<in T>
): Comparator<T>
Example to demonstrate the compare, then and reversed functions.
// A simple class to represent a nameclass Name(val firstName: String,val lastName: String){ override fun toString(): String { return """$firstName $lastName""" }} // A comparator to compare first names of Nameclass ComparatorOne: Comparator<Name>{ override fun compare(o1: Name?, o2: Name?): Int { if(o1 == null || o2 == null){ return 0; } return o1.firstName.compareTo(o2.firstName) }} // A comparator to compare last names of Nameclass AnotherComparator: Comparator<Name>{ override fun compare(o1: Name?, o2: Name?): Int { if(o1 == null || o2 == null) return 0 return o1.lastName.compareTo(o2.lastName) }} fun main(){ val list = ArrayList<Name>() list.add(Name("Steve","Waugh")) list.add(Name("Steve","Smith")) list.add(Name("Virat","Kohli")) list.add(Name("Kane","Williamson")) list.add(Name("Joe","Root")) println("The list is:") println(list) val comparatorOne = ComparatorOne() // Sorting list according to first names list.sortWith(comparatorOne) println("List sorted according to first name") println(list) val anotherComparator = AnotherComparator() val finalComparator = comparatorOne.then(anotherComparator) // Sorting list according to first name then by last name list.sortWith(finalComparator) println("List sorted according to first name and last name") println(list) val reverseComparator = finalComparator.reversed() // Reverse sorting the list list.sortWith(reverseComparator) println("List reverse sorted") println(list)}
Output:
The list is:
[Steve Waugh, Steve Smith, Virat Kohli, Kane Williamson, Joe Root]
List sorted according to first name
[Joe Root, Kane Williamson, Steve Waugh, Steve Smith, Virat Kohli]
List sorted according to first name and last name
[Joe Root, Kane Williamson, Steve Smith, Steve Waugh, Virat Kohli]
List reverse sorted
[Virat Kohli, Steve Waugh, Steve Smith, Kane Williamson, Joe Root]
thenBy: This function converts the type instances to an instance of type Comparable and then compares them using these instances.
fun <T> Comparator<T>.thenBy(
selector: (T) -> Comparable<*>?
): Comparator<T>
thenByDescending: This function returns a descending comparator which converts a value into an instance of type Comparable and then compares the instances.
inline fun <T> Comparator<T>.thenByDescending(
crossinline selector: (T) -> Comparable<*>?
): Comparator<T>
Example to demonstrate the thenBy and thenByDescending functions
class Person(val height: Int,val weight: Int){ override fun toString(): String { return "Height = ${height}, Weight = ${weight}" }} fun main() { val comparator = compareBy<Person> { it.height } val list = listOf<Person>( Person(4, 10), Person(2, 10), Person(3, 45), Person(3, 25), Person(7, 95), Person(5, 50) ) println("Sorted first according to height then by weight") val anotherComparator = comparator.thenBy { it.weight } println(list.sortedWith(anotherComparator)) println("Sorted first according to weight then by descending order in height") val comparator2 = compareBy<Person> { it.weight }.thenByDescending { it.height } println(list.sortedWith(comparator2))}
Output:
Sorted first according to height then by weight
[Height = 2, Weight = 10, Height = 3, Weight = 25, Height = 3, Weight = 45, Height = 4, Weight = 10, Height = 5, Weight = 50, Height = 7, Weight = 95]
Sorted first according to weight then by descending order in height
[Height = 4, Weight = 10, Height = 2, Weight = 10, Height = 3, Weight = 25, Height = 3, Weight = 45, Height = 5, Weight = 50, Height = 7, Weight = 95]
thenComparator: This function returns a Comparator which uses the primary Comparator along with a function to perform a comparison.
fun <T> Comparator<T>.thenComparator(
comparison: (a: T, b: T) -> Int
): Comparator<T>
thenDescending: This function combines two comparator, and the second one is used only when the values are equal according to the first comparator, and sorts the elements in descending order.
infix fun <T> Comparator<T>.thenDescending(
comparator: Comparator<in T>
): Comparator<T>
Example to demonstrate the thenComparator and thenDescending functions.
fun main(){ val list = listOf<Pair<String,Int>>( Pair("A",3), Pair("B",1), Pair("G",345), Pair("E",20), Pair("A",0), Pair("J",0) ) val comparator = compareBy<Pair<String,Int>> { it.first } .thenComparator({a,b -> compareValues(a.second,b.second)}) println("Pairs sorted by String then by Integers") println(list.sortedWith(comparator)) val anotherComparator = compareBy<Pair<String,Int>> { it.second } val anotherComparator2 = compareBy<Pair<String,Int>>{it.first} println("Pairs sorted by Integers then by Strings in Descending order") println(list.sortedWith(anotherComparator.thenDescending(anotherComparator2)))}
Output:
Pairs sorted by String then by Integers
[(A, 0), (A, 3), (B, 1), (E, 20), (G, 345), (J, 0)]
Pairs sorted by Integers then by Strings in Descending order
[(J, 0), (A, 0), (B, 1), (A, 3), (E, 20), (G, 345)]
Kotlin
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
Content Providers in Android with Example
Android RecyclerView in Kotlin
Android UI Layouts
Retrofit with Kotlin Coroutine in Android
Kotlin Setters and Getters
Android Menus
How to Change the Color of Status Bar in an Android App?
MVP (Model View Presenter) Architecture Pattern in Android with Example
Kotlin Android Tutorial
|
[
{
"code": null,
"e": 24112,
"s": 24084,
"text": "\n02 Aug, 2019"
},
{
"code": null,
"e": 24574,
"s": 24112,
"text": "In programming contexts, as there arises a need for a new type, there is also a major task of ordering the instances of a type. To compare two instances of a type we implement Comparable interface. However, since in ordering instances they must be compared automatically and also since the order can vary according to various parameters, Kotlin provides a simple Comparator interface. This interface compares two objects of a type and arranges them in an order."
},
{
"code": null,
"e": 24749,
"s": 24574,
"text": "compare: This function compares two instance of a type and returns zero if both are equal, a negative number if second instance is bigger otherwise returns a positive number."
},
{
"code": null,
"e": 24788,
"s": 24749,
"text": "abstract fun compare(a: T, b: T): Int\n"
},
{
"code": null,
"e": 24934,
"s": 24788,
"text": "reversed: This function takes a comparator as an argument and returns the comparator with the ordering reversed as that of the passed comparator."
},
{
"code": null,
"e": 24983,
"s": 24934,
"text": "fun <T> Comparator<T>.reversed(): Comparator<T>\n"
},
{
"code": null,
"e": 25122,
"s": 24983,
"text": " then: This function combines two comparator, and the second one is used only when the values are equal according to the first comparator."
},
{
"code": null,
"e": 25207,
"s": 25122,
"text": "infix fun <T> Comparator<T>.then(\n comparator: Comparator<in T>\n): Comparator<T>\n"
},
{
"code": null,
"e": 25272,
"s": 25207,
"text": "Example to demonstrate the compare, then and reversed functions."
},
{
"code": "// A simple class to represent a nameclass Name(val firstName: String,val lastName: String){ override fun toString(): String { return \"\"\"$firstName $lastName\"\"\" }} // A comparator to compare first names of Nameclass ComparatorOne: Comparator<Name>{ override fun compare(o1: Name?, o2: Name?): Int { if(o1 == null || o2 == null){ return 0; } return o1.firstName.compareTo(o2.firstName) }} // A comparator to compare last names of Nameclass AnotherComparator: Comparator<Name>{ override fun compare(o1: Name?, o2: Name?): Int { if(o1 == null || o2 == null) return 0 return o1.lastName.compareTo(o2.lastName) }} fun main(){ val list = ArrayList<Name>() list.add(Name(\"Steve\",\"Waugh\")) list.add(Name(\"Steve\",\"Smith\")) list.add(Name(\"Virat\",\"Kohli\")) list.add(Name(\"Kane\",\"Williamson\")) list.add(Name(\"Joe\",\"Root\")) println(\"The list is:\") println(list) val comparatorOne = ComparatorOne() // Sorting list according to first names list.sortWith(comparatorOne) println(\"List sorted according to first name\") println(list) val anotherComparator = AnotherComparator() val finalComparator = comparatorOne.then(anotherComparator) // Sorting list according to first name then by last name list.sortWith(finalComparator) println(\"List sorted according to first name and last name\") println(list) val reverseComparator = finalComparator.reversed() // Reverse sorting the list list.sortWith(reverseComparator) println(\"List reverse sorted\") println(list)}",
"e": 26886,
"s": 25272,
"text": null
},
{
"code": null,
"e": 26894,
"s": 26886,
"text": "Output:"
},
{
"code": null,
"e": 27282,
"s": 26894,
"text": "The list is:\n[Steve Waugh, Steve Smith, Virat Kohli, Kane Williamson, Joe Root]\nList sorted according to first name\n[Joe Root, Kane Williamson, Steve Waugh, Steve Smith, Virat Kohli]\nList sorted according to first name and last name\n[Joe Root, Kane Williamson, Steve Smith, Steve Waugh, Virat Kohli]\nList reverse sorted\n[Virat Kohli, Steve Waugh, Steve Smith, Kane Williamson, Joe Root]\n"
},
{
"code": null,
"e": 27414,
"s": 27284,
"text": "thenBy: This function converts the type instances to an instance of type Comparable and then compares them using these instances."
},
{
"code": null,
"e": 27498,
"s": 27414,
"text": "fun <T> Comparator<T>.thenBy(\n selector: (T) -> Comparable<*>?\n): Comparator<T>\n"
},
{
"code": null,
"e": 27655,
"s": 27498,
"text": " thenByDescending: This function returns a descending comparator which converts a value into an instance of type Comparable and then compares the instances."
},
{
"code": null,
"e": 27768,
"s": 27655,
"text": "inline fun <T> Comparator<T>.thenByDescending(\n crossinline selector: (T) -> Comparable<*>?\n): Comparator<T>\n"
},
{
"code": null,
"e": 27833,
"s": 27768,
"text": "Example to demonstrate the thenBy and thenByDescending functions"
},
{
"code": "class Person(val height: Int,val weight: Int){ override fun toString(): String { return \"Height = ${height}, Weight = ${weight}\" }} fun main() { val comparator = compareBy<Person> { it.height } val list = listOf<Person>( Person(4, 10), Person(2, 10), Person(3, 45), Person(3, 25), Person(7, 95), Person(5, 50) ) println(\"Sorted first according to height then by weight\") val anotherComparator = comparator.thenBy { it.weight } println(list.sortedWith(anotherComparator)) println(\"Sorted first according to weight then by descending order in height\") val comparator2 = compareBy<Person> { it.weight }.thenByDescending { it.height } println(list.sortedWith(comparator2))}",
"e": 28593,
"s": 27833,
"text": null
},
{
"code": null,
"e": 28601,
"s": 28593,
"text": "Output:"
},
{
"code": null,
"e": 29020,
"s": 28601,
"text": "Sorted first according to height then by weight\n[Height = 2, Weight = 10, Height = 3, Weight = 25, Height = 3, Weight = 45, Height = 4, Weight = 10, Height = 5, Weight = 50, Height = 7, Weight = 95]\nSorted first according to weight then by descending order in height\n[Height = 4, Weight = 10, Height = 2, Weight = 10, Height = 3, Weight = 25, Height = 3, Weight = 45, Height = 5, Weight = 50, Height = 7, Weight = 95]\n"
},
{
"code": null,
"e": 29153,
"s": 29020,
"text": " thenComparator: This function returns a Comparator which uses the primary Comparator along with a function to perform a comparison."
},
{
"code": null,
"e": 29245,
"s": 29153,
"text": "fun <T> Comparator<T>.thenComparator(\n comparison: (a: T, b: T) -> Int\n): Comparator<T>\n"
},
{
"code": null,
"e": 29438,
"s": 29245,
"text": " thenDescending: This function combines two comparator, and the second one is used only when the values are equal according to the first comparator, and sorts the elements in descending order."
},
{
"code": null,
"e": 29533,
"s": 29438,
"text": "infix fun <T> Comparator<T>.thenDescending(\n comparator: Comparator<in T>\n): Comparator<T>\n"
},
{
"code": null,
"e": 29605,
"s": 29533,
"text": "Example to demonstrate the thenComparator and thenDescending functions."
},
{
"code": "fun main(){ val list = listOf<Pair<String,Int>>( Pair(\"A\",3), Pair(\"B\",1), Pair(\"G\",345), Pair(\"E\",20), Pair(\"A\",0), Pair(\"J\",0) ) val comparator = compareBy<Pair<String,Int>> { it.first } .thenComparator({a,b -> compareValues(a.second,b.second)}) println(\"Pairs sorted by String then by Integers\") println(list.sortedWith(comparator)) val anotherComparator = compareBy<Pair<String,Int>> { it.second } val anotherComparator2 = compareBy<Pair<String,Int>>{it.first} println(\"Pairs sorted by Integers then by Strings in Descending order\") println(list.sortedWith(anotherComparator.thenDescending(anotherComparator2)))}",
"e": 30307,
"s": 29605,
"text": null
},
{
"code": null,
"e": 30315,
"s": 30307,
"text": "Output:"
},
{
"code": null,
"e": 30521,
"s": 30315,
"text": "Pairs sorted by String then by Integers\n[(A, 0), (A, 3), (B, 1), (E, 20), (G, 345), (J, 0)]\nPairs sorted by Integers then by Strings in Descending order\n[(J, 0), (A, 0), (B, 1), (A, 3), (E, 20), (G, 345)]\n"
},
{
"code": null,
"e": 30528,
"s": 30521,
"text": "Kotlin"
},
{
"code": null,
"e": 30626,
"s": 30528,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30635,
"s": 30626,
"text": "Comments"
},
{
"code": null,
"e": 30648,
"s": 30635,
"text": "Old Comments"
},
{
"code": null,
"e": 30691,
"s": 30648,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 30733,
"s": 30691,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 30764,
"s": 30733,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 30783,
"s": 30764,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 30825,
"s": 30783,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 30852,
"s": 30825,
"text": "Kotlin Setters and Getters"
},
{
"code": null,
"e": 30866,
"s": 30852,
"text": "Android Menus"
},
{
"code": null,
"e": 30923,
"s": 30866,
"text": "How to Change the Color of Status Bar in an Android App?"
},
{
"code": null,
"e": 30995,
"s": 30923,
"text": "MVP (Model View Presenter) Architecture Pattern in Android with Example"
}
] |
Adding labels to histogram bars in Matplotlib - GeeksforGeeks
|
24 Feb, 2021
In this article, we are going to discuss how to add labels to histogram bars in matplotlib. Histograms are used to display continuous data using bars. It looks similar to the bar graph. It shows the count or frequency of element that falls under the category mentioned in that range it means, taller the graph, higher the frequency of that range. To display the histogram and its labels we are going to use matplotlib.
Approach:
We import matplotlib and numpy library.
Create a dataset using numpy library so that we can plot it.
Create a histogram using matplotlib library.
To give labels use set_xlabel() and set_ylabel() functions.
We add label to each bar in histogram and for that, we loop over each bar and use text() function to add text over it. We also calculate height and width of each bar so that our label don’t coincide with each other.
Use show() function to display the histogram.
Below is the code Implementation:
Python
from matplotlib import pyplot as pltimport numpy as np # Creating datasetmarks = np.array([70, 50, 40, 90, 55, 85, 74, 66, 33, 11, 45, 36, 89]) # Creating histogramfig, ax = plt.subplots(1, 1)ax.hist(marks) # Set titleax.set_title("Title") # adding labelsax.set_xlabel('x-label')ax.set_ylabel('y-label') # Make some labels.rects = ax.patcheslabels = ["label%d" % i for i in range(len(rects))] for rect, label in zip(rects, labels): height = rect.get_height() ax.text(rect.get_x() + rect.get_width() / 2, height+0.01, label, ha='center', va='bottom') # Show plotplt.show()
Output:
Explanation:
In the above code first, we created an array using np.array(). After that, we created a histogram using hist() function. To give labels we used set_xlabel() and set_ylabel() functions. To give title to our graph we used the set_title() function. We also added labels to each bar and for that first we used the get_height function to get height then, we used for loop to loop over each bar and add text over it using text() function. We used label variable to store the names of variables. Finally, to display histogram we used show() function.
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n24 Feb, 2021"
},
{
"code": null,
"e": 24320,
"s": 23901,
"text": "In this article, we are going to discuss how to add labels to histogram bars in matplotlib. Histograms are used to display continuous data using bars. It looks similar to the bar graph. It shows the count or frequency of element that falls under the category mentioned in that range it means, taller the graph, higher the frequency of that range. To display the histogram and its labels we are going to use matplotlib."
},
{
"code": null,
"e": 24330,
"s": 24320,
"text": "Approach:"
},
{
"code": null,
"e": 24370,
"s": 24330,
"text": "We import matplotlib and numpy library."
},
{
"code": null,
"e": 24431,
"s": 24370,
"text": "Create a dataset using numpy library so that we can plot it."
},
{
"code": null,
"e": 24476,
"s": 24431,
"text": "Create a histogram using matplotlib library."
},
{
"code": null,
"e": 24536,
"s": 24476,
"text": "To give labels use set_xlabel() and set_ylabel() functions."
},
{
"code": null,
"e": 24752,
"s": 24536,
"text": "We add label to each bar in histogram and for that, we loop over each bar and use text() function to add text over it. We also calculate height and width of each bar so that our label don’t coincide with each other."
},
{
"code": null,
"e": 24798,
"s": 24752,
"text": "Use show() function to display the histogram."
},
{
"code": null,
"e": 24832,
"s": 24798,
"text": "Below is the code Implementation:"
},
{
"code": null,
"e": 24839,
"s": 24832,
"text": "Python"
},
{
"code": "from matplotlib import pyplot as pltimport numpy as np # Creating datasetmarks = np.array([70, 50, 40, 90, 55, 85, 74, 66, 33, 11, 45, 36, 89]) # Creating histogramfig, ax = plt.subplots(1, 1)ax.hist(marks) # Set titleax.set_title(\"Title\") # adding labelsax.set_xlabel('x-label')ax.set_ylabel('y-label') # Make some labels.rects = ax.patcheslabels = [\"label%d\" % i for i in range(len(rects))] for rect, label in zip(rects, labels): height = rect.get_height() ax.text(rect.get_x() + rect.get_width() / 2, height+0.01, label, ha='center', va='bottom') # Show plotplt.show()",
"e": 25435,
"s": 24839,
"text": null
},
{
"code": null,
"e": 25443,
"s": 25435,
"text": "Output:"
},
{
"code": null,
"e": 25456,
"s": 25443,
"text": "Explanation:"
},
{
"code": null,
"e": 26004,
"s": 25456,
"text": "In the above code first, we created an array using np.array(). After that, we created a histogram using hist() function. To give labels we used set_xlabel() and set_ylabel() functions. To give title to our graph we used the set_title() function. We also added labels to each bar and for that first we used the get_height function to get height then, we used for loop to loop over each bar and add text over it using text() function. We used label variable to store the names of variables. Finally, to display histogram we used show() function. "
},
{
"code": null,
"e": 26011,
"s": 26004,
"text": "Picked"
},
{
"code": null,
"e": 26029,
"s": 26011,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 26036,
"s": 26029,
"text": "Python"
},
{
"code": null,
"e": 26134,
"s": 26036,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26143,
"s": 26134,
"text": "Comments"
},
{
"code": null,
"e": 26156,
"s": 26143,
"text": "Old Comments"
},
{
"code": null,
"e": 26188,
"s": 26156,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26244,
"s": 26188,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26286,
"s": 26244,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26328,
"s": 26286,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26364,
"s": 26328,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26386,
"s": 26364,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26425,
"s": 26386,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26452,
"s": 26425,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26483,
"s": 26452,
"text": "Python | os.path.join() method"
}
] |
Index Replication using Portfolio Optimization Methods | by Jason Yip | Towards Data Science
|
It’s been a whole year since I last posted and I thought to write about a project I’ve done recently during the stay-home period. It was difficult finding practical resources online. There were many math-heavy and theoretical academic papers, but I wanted to support others out there who were looking out for code and a layman’s understanding since I’ve already spent the past 4 days researching and working on this project.
I will leave most of the code out from this post but you can access everything here:
👉🏻Link to Code / Notebook
👉🏻Link to Repo
is a passive investment strategy that attempts to re-create a portfolio that generates returns similar to a broad market index. This can be achieved in these ways:
Full Replication
A Full Replication of an index requires the fund to hold the shares of all the assets in the index and replicate as close as possible each asset’s weight in the index. Trading illiquid assets in the index could add to higher transaction costs for the fund, resulting in higher expense ratios and a poorer fund performance.
Portfolio Optimization
The aim of this project is to replicate the index using an optimal portfolio selection of the largest assets in the index by reducing Tracking Error. Ultimately, we will produce a weight for each of the largest assets in the portfolio to replicate the performance of the index with only a few assets.
Tracking Error
Information Ratio
Russell 1000 is a stock market index maintained by FTSE Russell that tracks the highest-ranking 1,000 stocks in the entire U.S stock market that we aim to replicate for the following. Test Period: 2019–04–01 to 2019–04–30.
Market indices go through periodic rebalancing to ensure they keep up with the current market. Back when FTSE Russell started the index in 1984, Standard Oil of Indiana was among the largest companies in the U.S by market cap. Today, the company doesn’t exist as it had been dissolved.
According to the annual reconstitution schedules, there is a ‘rank day’ where the rankings for the top 1000 companies by market cap are computed at market close. This is followed by a transition period before the reconstitution takes place on the ‘effect day’, where markets open with the newly reconstituted index. We should be careful to account for this in approximating the index with the top companies because they (or their weights) might change across the years. I used the Top 10 components of the index published by FTSE’s reconstitution recap report in 2018 and 2017. The training data is taken from 2018–06–25 to 2019–02–28.
Market Cap of Top 10 in 2018 {'AAPL': 5016475823, 'AMZN': 483381822, 'GOOG': 694989876, 'MSFT': 7898764549, 'FB': 2917587472, 'BRK-B': 2444334034, 'JPM': 3601578394, 'XOM': 4614039868, 'JNJ': 2875386042, 'BAC': 10598321272}
We will reconstruct the Index with the Top 10 components using the Price Return Index from Russell (page 4). The Index value (page 34) is then obtained by compounding the daily return percentages of the Price Return Index. The starting value of the index is equal to the base and this was set as 100 on 12/31/78. Therefore on our base date: 2017–06–27 and we will use the ^RUI’s Close = 1341.03 (from Yahoo Finance) as our base value. The results don’t look close at all using only the Top 10.
The idea is to fit a linear combination of the current top 10 components against index prices in a constrained linear least squares model for the training period. The coeffs obtained will then be non-negative since it is a Long only portfolio.
Each coeff is taken over the sum of coeffs as weightings for each component to be taken in the test period. The sum of weightings will be the amount of leverage that the portfolio requires to replicate the index price.
The optimization called from the library is essentially:
from scipy.optimize import nnlsresult = nnls(trainX, trainY)
The coeffs are then used as weights in this linear combination, where the leverage factor is the sum of coefficients:
While I have validated the model on a holdout period of 1 month before the test period as well, I will only show the results on the test set.
The replicated index seems to visually match up well to the actual index in terms of price and daily returns. The Tracking Error is 43 basis points (0.43%) and RMSE (from the actual) seems pretty low.
The idea is to allocate more weight to a component if it is more correlated with the index’s actual close. Partial correlation correlates the residuals from 1) least-squares regression of Index on the other IVs & 2) least-squares regression of individual IV on other IVs. This accounts for confounding & 3rd party effects. I also ignored negatively correlated components by setting it to 0. Similarly, we will take each correlation over the sum to get the weightings
The optimization called from the library is essentially (where train includes both the historic component & actual index prices:
import pandas as pdtrain.pcorr()
As above, the similar linear combination approach will be used to simulate the actual.
Tracking Error and Returns RMSE are higher than the benchmark. However, the Price RMSE is a lot lower. This is probably due to the oversimplification made by this model in considering the effects of each component independently.
Pearson correlation is unable to capture shape similarity and will determine that a pair of timeseries are uncorrelated with each other even though they maybe are very similar and simply out of phase. This could be apparent between leading/lagging variables and their counterparts. The idea is to allocate more weight to a component if it has a relatively shorter DTW distance with the index and thus, a more similar shape.
The goal is to optimize this for each component (x) and the actual index (y):
The optimization called from the library is essentially:
from tslearn.metrics import dtwtrainX.apply(lambda x: dtw(x, trainY))
The Tracking error, Price RMSE & Returns RMSE performed worse than the Partial Correlation Model. This could mean that the shape similarity might not have been a huge factor in differentiating each component from each other.
While NNLS is a supervised learning approach, the unsupervised NMF method is able to learn the representation of the data via a single principal component. The principal component will be a linear combination of the assets such that the coeffs will be non-negative due to the constraints in this algo. The idea is to find the relative importance of each asset in contributing to the overall variation in the data and use that as our weightings in a linear combination again.
The optimization called from the library is essentially:
from sklearn.decomposition import NMFnmf = NMF(n_components=1)nmf.fit(trainX)coeffs = nmf.components_.tolist()[0]
The problem with this approach is that the prices cannot be properly replicated as we will not know the leverage factor in an unsupervised learning method, thus the price RMSE is very high.
PSO emulates ‘social creatures’ that are scattered around the search space and moving to find the optima. The optimization function here is to minimize Tracking Error.
Bounds = [0,1] since coeffs are non-negative and the value of the component cannot be more than the index.
Grid search is performed over c1, c2, w. The code for the grid search is almost the same as the chunk below and it will give you best_pos to be used in the chunk below to for the final optimization.
from pyswarms.utils.search.grid_search import GridSearchfrom pyswarms.utils.search.random_search import RandomSearchfrom pyswarms.single.global_best import GlobalBestPSOfrom pyswarms.utils.plotters import (plot_cost_history, plot_contour, plot_surface)def find_particle_loss(coeffs): trainX_returns = trainX.pct_change().dropna() trainY_returns = trainY.pct_change().dropna() benchmark_tracking_error = np.std(trainX.dot(coeffs) - trainY) return benchmark_tracking_errordef swarm(x): n_particles = x.shape[0] particle_loss = [find_particle_loss(x[i]) for i in range(n_particles)] return particle_lossfeature_count = len(trainX.columns)min_bound = feature_count*[0]max_bound = feature_count*[1]optimizer = GlobalBestPSO(n_particles=1000, dimensions=len(trainX.columns), options=best_pos, bounds=(min_bound,max_bound))# Perform optimization, cost=lowest particle_loss among all iterationscost, pos = optimizer.optimize(swarm,iters=100)
The particle (set of coefficients) with the lowest cost (Tracking Error) will be used as coefficients, taken over the sum of coefficients as weights, and used in a linear combination to reconstruct the index.
NMF (Tracking Error: 56 bps, Price RMSE: 368.7, Returns RMSE: 0.006032)
NNLS (Tracking Error: 43 bps, Price RMSE: 27.37, Returns RMSE: 0.004587)
Tracking Error for the PSO model is the lowest.
The following quantitative methods were used on prices of the Top 10 components and the actual Index price in the training period:
Non-negative Least Squares (NNLS) OptimizationRelative Partial CorrelationDynamic Time Warping (DTW) OptimizationNon-negative Matrix Factorization (NMF)Particle Swarm Optimisation (PSO)
Non-negative Least Squares (NNLS) Optimization
Relative Partial Correlation
Dynamic Time Warping (DTW) Optimization
Non-negative Matrix Factorization (NMF)
Particle Swarm Optimisation (PSO)
The weights obtained were then used to allocate a portfolio to simulate the index prices and daily returns in the test period. The performance was then measured by the Tracking Error and Price/Daily Returns RMSE from the actual index.
I have learnt a lot from this project in such a short amount of time and it has really opened my eyes up to more applications of quantitative methods in finance. Hope you’ve enjoyed reading this as much as I’ve enjoyed creating it.
|
[
{
"code": null,
"e": 472,
"s": 47,
"text": "It’s been a whole year since I last posted and I thought to write about a project I’ve done recently during the stay-home period. It was difficult finding practical resources online. There were many math-heavy and theoretical academic papers, but I wanted to support others out there who were looking out for code and a layman’s understanding since I’ve already spent the past 4 days researching and working on this project."
},
{
"code": null,
"e": 557,
"s": 472,
"text": "I will leave most of the code out from this post but you can access everything here:"
},
{
"code": null,
"e": 583,
"s": 557,
"text": "👉🏻Link to Code / Notebook"
},
{
"code": null,
"e": 598,
"s": 583,
"text": "👉🏻Link to Repo"
},
{
"code": null,
"e": 762,
"s": 598,
"text": "is a passive investment strategy that attempts to re-create a portfolio that generates returns similar to a broad market index. This can be achieved in these ways:"
},
{
"code": null,
"e": 779,
"s": 762,
"text": "Full Replication"
},
{
"code": null,
"e": 1102,
"s": 779,
"text": "A Full Replication of an index requires the fund to hold the shares of all the assets in the index and replicate as close as possible each asset’s weight in the index. Trading illiquid assets in the index could add to higher transaction costs for the fund, resulting in higher expense ratios and a poorer fund performance."
},
{
"code": null,
"e": 1125,
"s": 1102,
"text": "Portfolio Optimization"
},
{
"code": null,
"e": 1426,
"s": 1125,
"text": "The aim of this project is to replicate the index using an optimal portfolio selection of the largest assets in the index by reducing Tracking Error. Ultimately, we will produce a weight for each of the largest assets in the portfolio to replicate the performance of the index with only a few assets."
},
{
"code": null,
"e": 1441,
"s": 1426,
"text": "Tracking Error"
},
{
"code": null,
"e": 1459,
"s": 1441,
"text": "Information Ratio"
},
{
"code": null,
"e": 1682,
"s": 1459,
"text": "Russell 1000 is a stock market index maintained by FTSE Russell that tracks the highest-ranking 1,000 stocks in the entire U.S stock market that we aim to replicate for the following. Test Period: 2019–04–01 to 2019–04–30."
},
{
"code": null,
"e": 1968,
"s": 1682,
"text": "Market indices go through periodic rebalancing to ensure they keep up with the current market. Back when FTSE Russell started the index in 1984, Standard Oil of Indiana was among the largest companies in the U.S by market cap. Today, the company doesn’t exist as it had been dissolved."
},
{
"code": null,
"e": 2604,
"s": 1968,
"text": "According to the annual reconstitution schedules, there is a ‘rank day’ where the rankings for the top 1000 companies by market cap are computed at market close. This is followed by a transition period before the reconstitution takes place on the ‘effect day’, where markets open with the newly reconstituted index. We should be careful to account for this in approximating the index with the top companies because they (or their weights) might change across the years. I used the Top 10 components of the index published by FTSE’s reconstitution recap report in 2018 and 2017. The training data is taken from 2018–06–25 to 2019–02–28."
},
{
"code": null,
"e": 2828,
"s": 2604,
"text": "Market Cap of Top 10 in 2018 {'AAPL': 5016475823, 'AMZN': 483381822, 'GOOG': 694989876, 'MSFT': 7898764549, 'FB': 2917587472, 'BRK-B': 2444334034, 'JPM': 3601578394, 'XOM': 4614039868, 'JNJ': 2875386042, 'BAC': 10598321272}"
},
{
"code": null,
"e": 3322,
"s": 2828,
"text": "We will reconstruct the Index with the Top 10 components using the Price Return Index from Russell (page 4). The Index value (page 34) is then obtained by compounding the daily return percentages of the Price Return Index. The starting value of the index is equal to the base and this was set as 100 on 12/31/78. Therefore on our base date: 2017–06–27 and we will use the ^RUI’s Close = 1341.03 (from Yahoo Finance) as our base value. The results don’t look close at all using only the Top 10."
},
{
"code": null,
"e": 3566,
"s": 3322,
"text": "The idea is to fit a linear combination of the current top 10 components against index prices in a constrained linear least squares model for the training period. The coeffs obtained will then be non-negative since it is a Long only portfolio."
},
{
"code": null,
"e": 3785,
"s": 3566,
"text": "Each coeff is taken over the sum of coeffs as weightings for each component to be taken in the test period. The sum of weightings will be the amount of leverage that the portfolio requires to replicate the index price."
},
{
"code": null,
"e": 3842,
"s": 3785,
"text": "The optimization called from the library is essentially:"
},
{
"code": null,
"e": 3903,
"s": 3842,
"text": "from scipy.optimize import nnlsresult = nnls(trainX, trainY)"
},
{
"code": null,
"e": 4021,
"s": 3903,
"text": "The coeffs are then used as weights in this linear combination, where the leverage factor is the sum of coefficients:"
},
{
"code": null,
"e": 4163,
"s": 4021,
"text": "While I have validated the model on a holdout period of 1 month before the test period as well, I will only show the results on the test set."
},
{
"code": null,
"e": 4364,
"s": 4163,
"text": "The replicated index seems to visually match up well to the actual index in terms of price and daily returns. The Tracking Error is 43 basis points (0.43%) and RMSE (from the actual) seems pretty low."
},
{
"code": null,
"e": 4831,
"s": 4364,
"text": "The idea is to allocate more weight to a component if it is more correlated with the index’s actual close. Partial correlation correlates the residuals from 1) least-squares regression of Index on the other IVs & 2) least-squares regression of individual IV on other IVs. This accounts for confounding & 3rd party effects. I also ignored negatively correlated components by setting it to 0. Similarly, we will take each correlation over the sum to get the weightings"
},
{
"code": null,
"e": 4960,
"s": 4831,
"text": "The optimization called from the library is essentially (where train includes both the historic component & actual index prices:"
},
{
"code": null,
"e": 4993,
"s": 4960,
"text": "import pandas as pdtrain.pcorr()"
},
{
"code": null,
"e": 5080,
"s": 4993,
"text": "As above, the similar linear combination approach will be used to simulate the actual."
},
{
"code": null,
"e": 5309,
"s": 5080,
"text": "Tracking Error and Returns RMSE are higher than the benchmark. However, the Price RMSE is a lot lower. This is probably due to the oversimplification made by this model in considering the effects of each component independently."
},
{
"code": null,
"e": 5733,
"s": 5309,
"text": "Pearson correlation is unable to capture shape similarity and will determine that a pair of timeseries are uncorrelated with each other even though they maybe are very similar and simply out of phase. This could be apparent between leading/lagging variables and their counterparts. The idea is to allocate more weight to a component if it has a relatively shorter DTW distance with the index and thus, a more similar shape."
},
{
"code": null,
"e": 5811,
"s": 5733,
"text": "The goal is to optimize this for each component (x) and the actual index (y):"
},
{
"code": null,
"e": 5868,
"s": 5811,
"text": "The optimization called from the library is essentially:"
},
{
"code": null,
"e": 5938,
"s": 5868,
"text": "from tslearn.metrics import dtwtrainX.apply(lambda x: dtw(x, trainY))"
},
{
"code": null,
"e": 6163,
"s": 5938,
"text": "The Tracking error, Price RMSE & Returns RMSE performed worse than the Partial Correlation Model. This could mean that the shape similarity might not have been a huge factor in differentiating each component from each other."
},
{
"code": null,
"e": 6638,
"s": 6163,
"text": "While NNLS is a supervised learning approach, the unsupervised NMF method is able to learn the representation of the data via a single principal component. The principal component will be a linear combination of the assets such that the coeffs will be non-negative due to the constraints in this algo. The idea is to find the relative importance of each asset in contributing to the overall variation in the data and use that as our weightings in a linear combination again."
},
{
"code": null,
"e": 6695,
"s": 6638,
"text": "The optimization called from the library is essentially:"
},
{
"code": null,
"e": 6809,
"s": 6695,
"text": "from sklearn.decomposition import NMFnmf = NMF(n_components=1)nmf.fit(trainX)coeffs = nmf.components_.tolist()[0]"
},
{
"code": null,
"e": 6999,
"s": 6809,
"text": "The problem with this approach is that the prices cannot be properly replicated as we will not know the leverage factor in an unsupervised learning method, thus the price RMSE is very high."
},
{
"code": null,
"e": 7167,
"s": 6999,
"text": "PSO emulates ‘social creatures’ that are scattered around the search space and moving to find the optima. The optimization function here is to minimize Tracking Error."
},
{
"code": null,
"e": 7274,
"s": 7167,
"text": "Bounds = [0,1] since coeffs are non-negative and the value of the component cannot be more than the index."
},
{
"code": null,
"e": 7473,
"s": 7274,
"text": "Grid search is performed over c1, c2, w. The code for the grid search is almost the same as the chunk below and it will give you best_pos to be used in the chunk below to for the final optimization."
},
{
"code": null,
"e": 8470,
"s": 7473,
"text": "from pyswarms.utils.search.grid_search import GridSearchfrom pyswarms.utils.search.random_search import RandomSearchfrom pyswarms.single.global_best import GlobalBestPSOfrom pyswarms.utils.plotters import (plot_cost_history, plot_contour, plot_surface)def find_particle_loss(coeffs): trainX_returns = trainX.pct_change().dropna() trainY_returns = trainY.pct_change().dropna() benchmark_tracking_error = np.std(trainX.dot(coeffs) - trainY) return benchmark_tracking_errordef swarm(x): n_particles = x.shape[0] particle_loss = [find_particle_loss(x[i]) for i in range(n_particles)] return particle_lossfeature_count = len(trainX.columns)min_bound = feature_count*[0]max_bound = feature_count*[1]optimizer = GlobalBestPSO(n_particles=1000, dimensions=len(trainX.columns), options=best_pos, bounds=(min_bound,max_bound))# Perform optimization, cost=lowest particle_loss among all iterationscost, pos = optimizer.optimize(swarm,iters=100)"
},
{
"code": null,
"e": 8679,
"s": 8470,
"text": "The particle (set of coefficients) with the lowest cost (Tracking Error) will be used as coefficients, taken over the sum of coefficients as weights, and used in a linear combination to reconstruct the index."
},
{
"code": null,
"e": 8751,
"s": 8679,
"text": "NMF (Tracking Error: 56 bps, Price RMSE: 368.7, Returns RMSE: 0.006032)"
},
{
"code": null,
"e": 8824,
"s": 8751,
"text": "NNLS (Tracking Error: 43 bps, Price RMSE: 27.37, Returns RMSE: 0.004587)"
},
{
"code": null,
"e": 8872,
"s": 8824,
"text": "Tracking Error for the PSO model is the lowest."
},
{
"code": null,
"e": 9003,
"s": 8872,
"text": "The following quantitative methods were used on prices of the Top 10 components and the actual Index price in the training period:"
},
{
"code": null,
"e": 9189,
"s": 9003,
"text": "Non-negative Least Squares (NNLS) OptimizationRelative Partial CorrelationDynamic Time Warping (DTW) OptimizationNon-negative Matrix Factorization (NMF)Particle Swarm Optimisation (PSO)"
},
{
"code": null,
"e": 9236,
"s": 9189,
"text": "Non-negative Least Squares (NNLS) Optimization"
},
{
"code": null,
"e": 9265,
"s": 9236,
"text": "Relative Partial Correlation"
},
{
"code": null,
"e": 9305,
"s": 9265,
"text": "Dynamic Time Warping (DTW) Optimization"
},
{
"code": null,
"e": 9345,
"s": 9305,
"text": "Non-negative Matrix Factorization (NMF)"
},
{
"code": null,
"e": 9379,
"s": 9345,
"text": "Particle Swarm Optimisation (PSO)"
},
{
"code": null,
"e": 9614,
"s": 9379,
"text": "The weights obtained were then used to allocate a portfolio to simulate the index prices and daily returns in the test period. The performance was then measured by the Tracking Error and Price/Daily Returns RMSE from the actual index."
}
] |
Generate random characters and numbers in JavaScript?
|
At first, set the characters and numbers −
var storedCharacters =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
To generate randomly, use Math.random(). Following is the code −
function generateRandom3Characters(size) {
var generatedOutput= '';
var storedCharacters =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var totalCharacterSize = storedCharacters.length;
for ( var index = 0; index < size; index++ ) {
generatedOutput+=storedCharacters.charAt(Math.floor(Math.random() *
totalCharacterSize));
}
return generatedOutput;
}
console.log(generateRandom3Characters(3));
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo136.js. This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo136.js
lq4
|
[
{
"code": null,
"e": 1105,
"s": 1062,
"text": "At first, set the characters and numbers −"
},
{
"code": null,
"e": 1194,
"s": 1105,
"text": "var storedCharacters =\n'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';"
},
{
"code": null,
"e": 1259,
"s": 1194,
"text": "To generate randomly, use Math.random(). Following is the code −"
},
{
"code": null,
"e": 1707,
"s": 1259,
"text": "function generateRandom3Characters(size) {\n var generatedOutput= '';\n var storedCharacters =\n '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n var totalCharacterSize = storedCharacters.length;\n for ( var index = 0; index < size; index++ ) {\n generatedOutput+=storedCharacters.charAt(Math.floor(Math.random() *\n totalCharacterSize));\n }\n return generatedOutput;\n}\nconsole.log(generateRandom3Characters(3));"
},
{
"code": null,
"e": 1773,
"s": 1707,
"text": "To run the above program, you need to use the following command −"
},
{
"code": null,
"e": 1791,
"s": 1773,
"text": "node fileName.js."
},
{
"code": null,
"e": 1866,
"s": 1791,
"text": "Here, my file name is demo136.js. This will produce the following output −"
},
{
"code": null,
"e": 1920,
"s": 1866,
"text": "PS C:\\Users\\Amit\\JavaScript-code> node demo136.js\nlq4"
}
] |
PyQt5 QListWidget | Python - GeeksforGeeks
|
17 Dec, 2019
In PyQt, QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list.
Syntax:
listWidget = QListWidget()
There are two ways to add items to the list.
They can be constructed with the list widget as their parent widget.QListWidgetItem("Geeks", listWidget)
QListWidgetItem("For", listWidget)
QListWidgetItem("Geeks", listWidget)
They can be constructed with no parent widget and added to the list later.listWidgetItem = QListWidgetItem("GeeksForGeeks")
listWidget.addItem(listWidgetItem)
They can be constructed with the list widget as their parent widget.QListWidgetItem("Geeks", listWidget)
QListWidgetItem("For", listWidget)
QListWidgetItem("Geeks", listWidget)
QListWidgetItem("Geeks", listWidget)
QListWidgetItem("For", listWidget)
QListWidgetItem("Geeks", listWidget)
They can be constructed with no parent widget and added to the list later.listWidgetItem = QListWidgetItem("GeeksForGeeks")
listWidget.addItem(listWidgetItem)
listWidgetItem = QListWidgetItem("GeeksForGeeks")
listWidget.addItem(listWidgetItem)
Some of the most frequently used methods in QListWidget:
addItem() : To add QListWidgetItem object in list
addItems() : To add multiple QListWidgetItem objects
insertItem() : It adds item at specified position
clear() : To delete all the items present in the list
count() : To count number of items present in the list
Below is the code –
import sysfrom PyQt5.QtWidgets import QApplication, QWidget, QListWidget, QVBoxLayout, QListWidgetItem class Ui_MainWindow(QWidget): def __init__(self, parent = None): super(Ui_MainWindow, self).__init__(parent) if __name__ == '__main__': app = QApplication(sys.argv) window = QWidget() listWidget = QListWidget() window.setWindowTitle("Demo for QListWidget") QListWidgetItem("Geeks", listWidget) QListWidgetItem("For", listWidget) QListWidgetItem("Geeks", listWidget) listWidgetItem = QListWidgetItem("GeeksForGeeks") listWidget.addItem(listWidgetItem) window_layout = QVBoxLayout(window) window_layout.addWidget(listWidget) window.setLayout(window_layout) window.show() sys.exit(app.exec_())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Read a file line by line in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Deque in Python
Python String | replace()
|
[
{
"code": null,
"e": 24629,
"s": 24601,
"text": "\n17 Dec, 2019"
},
{
"code": null,
"e": 24845,
"s": 24629,
"text": "In PyQt, QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list."
},
{
"code": null,
"e": 24853,
"s": 24845,
"text": "Syntax:"
},
{
"code": null,
"e": 24881,
"s": 24853,
"text": "listWidget = QListWidget()\n"
},
{
"code": null,
"e": 24926,
"s": 24881,
"text": "There are two ways to add items to the list."
},
{
"code": null,
"e": 25263,
"s": 24926,
"text": "They can be constructed with the list widget as their parent widget.QListWidgetItem(\"Geeks\", listWidget)\nQListWidgetItem(\"For\", listWidget)\nQListWidgetItem(\"Geeks\", listWidget)\nThey can be constructed with no parent widget and added to the list later.listWidgetItem = QListWidgetItem(\"GeeksForGeeks\")\nlistWidget.addItem(listWidgetItem)\n"
},
{
"code": null,
"e": 25441,
"s": 25263,
"text": "They can be constructed with the list widget as their parent widget.QListWidgetItem(\"Geeks\", listWidget)\nQListWidgetItem(\"For\", listWidget)\nQListWidgetItem(\"Geeks\", listWidget)\n"
},
{
"code": null,
"e": 25551,
"s": 25441,
"text": "QListWidgetItem(\"Geeks\", listWidget)\nQListWidgetItem(\"For\", listWidget)\nQListWidgetItem(\"Geeks\", listWidget)\n"
},
{
"code": null,
"e": 25711,
"s": 25551,
"text": "They can be constructed with no parent widget and added to the list later.listWidgetItem = QListWidgetItem(\"GeeksForGeeks\")\nlistWidget.addItem(listWidgetItem)\n"
},
{
"code": null,
"e": 25797,
"s": 25711,
"text": "listWidgetItem = QListWidgetItem(\"GeeksForGeeks\")\nlistWidget.addItem(listWidgetItem)\n"
},
{
"code": null,
"e": 25854,
"s": 25797,
"text": "Some of the most frequently used methods in QListWidget:"
},
{
"code": null,
"e": 26116,
"s": 25854,
"text": "addItem() : To add QListWidgetItem object in list\naddItems() : To add multiple QListWidgetItem objects\ninsertItem() : It adds item at specified position\nclear() : To delete all the items present in the list\ncount() : To count number of items present in the list"
},
{
"code": null,
"e": 26136,
"s": 26116,
"text": "Below is the code –"
},
{
"code": "import sysfrom PyQt5.QtWidgets import QApplication, QWidget, QListWidget, QVBoxLayout, QListWidgetItem class Ui_MainWindow(QWidget): def __init__(self, parent = None): super(Ui_MainWindow, self).__init__(parent) if __name__ == '__main__': app = QApplication(sys.argv) window = QWidget() listWidget = QListWidget() window.setWindowTitle(\"Demo for QListWidget\") QListWidgetItem(\"Geeks\", listWidget) QListWidgetItem(\"For\", listWidget) QListWidgetItem(\"Geeks\", listWidget) listWidgetItem = QListWidgetItem(\"GeeksForGeeks\") listWidget.addItem(listWidgetItem) window_layout = QVBoxLayout(window) window_layout.addWidget(listWidget) window.setLayout(window_layout) window.show() sys.exit(app.exec_())",
"e": 26902,
"s": 26136,
"text": null
},
{
"code": null,
"e": 26911,
"s": 26902,
"text": "Output :"
},
{
"code": null,
"e": 26922,
"s": 26911,
"text": "Python-gui"
},
{
"code": null,
"e": 26934,
"s": 26922,
"text": "Python-PyQt"
},
{
"code": null,
"e": 26941,
"s": 26934,
"text": "Python"
},
{
"code": null,
"e": 27039,
"s": 26941,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27048,
"s": 27039,
"text": "Comments"
},
{
"code": null,
"e": 27061,
"s": 27048,
"text": "Old Comments"
},
{
"code": null,
"e": 27079,
"s": 27061,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27101,
"s": 27079,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27136,
"s": 27101,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27158,
"s": 27136,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27200,
"s": 27158,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27225,
"s": 27200,
"text": "sum() function in Python"
},
{
"code": null,
"e": 27255,
"s": 27225,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27287,
"s": 27255,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27303,
"s": 27287,
"text": "Deque in Python"
}
] |
Migrating PHP 5.x to PHP 7 on CentOS 7
|
In this article, we will learn about how to upgrade and update PHP 5.x to PHP 7, PHP 7 which was released in 2015 with speed improvements comparable to the older versions of the PHP.
Assuming that we have already installed PHP 5.x on CentOS7, and mod_php module should be enabled by Apache, and we need Sudo privileges or root user.
As PHP 7.x is not available in the official repositories, so we need to use IUS community Project Repository.
Download the IUS repository in the machine with the below command
# curl 'https://setup.ius.io/' -o setup-ius.sh
curl 'https://setup.ius.io/' -o setup-ius.sh
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 1913 100 1913 0 0 1554 0 0:00:01 0:00:01 --:--:-- 1555
Installing the IUS repository to the local machine with the below command
# bash setup-ius.sh
bash setup-ius.sh
detected CentOS 7
Loaded plugins: fastestmirror
base | 3.6 kB
epel/x86_64/metalink | 5.2 kB
epel | 4.3 kB
extras | 3. 4 kB 00:00:00
mysql56-community | 2.5 kB 00:00:00
updates | 3.4 kB 00:00:00
(1/3): updates/7/x86_64/primary_db | 5.7 MB 00:00:00
(2/3): epel/x86_64/updateinfo | 584 kB 00:00:02
(3/3): epel/x86_64/primary_db | 4.3 MB 00:00:03
Loading mirror speeds from cached hostfile
* base: mirrors.nhanhoa.com
* epel: kodeterbuka.beritagar.id
* extras: mirrors.nhanhoa.com
* updates: mirrors.nhanhoa.com
Package epel-release-7-7.noarch already installed and latest version
Nothing to do
Loaded plugins: fastestmirror
ius-release.rpm | 8.1 kB 00:00:00
Examining /var/tmp/yum-root-BRDs50/ius-release.rpm: ius-release-1.0-14.ius.centos7.noarch
Marking /var/tmp/yum-root-BRDs50/ius-release.rpm to be installed
Resolving Dependencies
--> Running transaction check
---> Package ius-release.noarch 0:1.0-14.ius.centos7 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
=========================================================================================================================
Package Arch Version Repository Size=========================================================================================================================
Installing:
ius-release noarch 1.0-14.ius.centos7 /ius-release 8.
Transaction Summary
=========================================================================================================================
Install 1 Package
Total size: 8.5 k
Installed size: 8.5 k
Downloading packages:
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : ius-release-1.0-14.ius.centos7.noarch 1/1
Verifying : ius-release-1.0-14.ius.centos7.noarch 1/1
Installed:
ius-release.noarch 0:1.0-14.ius.centos7
Complete!
Here,we will upgrade the system for Apachhe module mod_php. First, we will remove the old packages using the below command.
# yum remove php-cli mod_php php-common
Installing the new PHP 7 modules using the IUS repository using the below command.
# yum install php70-mysqlnd mod_php70u php70u-cli
Loaded plugins: fastestmirror
ius | 2.2 kB 00:00:00
ius/x86_64/primary_db | 173 kB 00:00:00
Loading mirror speeds from cached hostfile
* base: mirrors.nhanhoa.com
* epel: kodeterbuka.beritagar.id
* extras: mirrors.nhanhoa.com
* ius: hkg.mirror.rackspace.com
* updates: mirrors.nhanhoa.com
Resolving Dependencies
--> Running transaction check
---> Package mod_php70u.x86_64 0:7.0.8-1.ius.centos7 will be installed
--> Processing Dependency: php-common(x86-64) = 7.0.8-1.ius.centos7 for package: mod_php70u-7.0.8-1.ius.centos7.x86_64
---> Package php70u-cli.x86_64 0:7.0.8-1.ius.centos7 will be installed
---> Package php70u-mysqlnd.x86_64 0:7.0.8-1.ius.centos7 will be installed
--> Processing Dependency: php-pdo(x86-64) = 7.0.8-1.ius.centos7 for package: php70u-mysqlnd-7.0.8-1.ius.centos7.x86_64
--> Running transaction check
---> Package php70u-common.x86_64 0:7.0.8-1.ius.centos7 will be installed
---> Package php70u-pdo.x86_64 0:7.0.8-1.ius.centos7 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
=========================================================================================================================
Package Arch Version Repository Size
=========================================================================================================================
Installing:
mod_php70u x86_64 7.0.8-1.ius.centos7 ius 2.6 M
php70u-cli x86_64 7.0.8-1.ius.centos7 ius 4.0 M
php70u-mysqlnd x86_64 7.0.8-1.ius.centos7 ius 239 k
Installing for dependencies:
php70u-common x86_64 7.0.8-1.ius.centos7 ius 1.1 M
php70u-pdo x86_64 7.0.8-1.ius.centos7 ius 126 k
Transaction Summary
=========================================================================================================================
Install 3 Packages (+2 Dependent packages)
Total download size: 8.0 M
Installed size: 30 M
Is this ok [y/d/N]: y
Downloading packages:
(1/5): php70u-pdo-7.0.8-1.ius.centos7.x86_64.rpm | 126 kB 00:00:00
(2/5): mod_php70u-7.0.8-1.ius.centos7.x86_64.rpm | 2.6 MB 00:00:01
(3/5): php70u-common-7.0.8-1.ius.centos7.x86_64.rpm | 1.1 MB 00:00:01
(4/5): php70u-mysqlnd-7.0.8-1.ius.centos7.x86_64.rpm | 239 kB 00:00:01
(5/5): php70u-cli-7.0.8-1.ius.centos7.x86_64.rpm | 4.0 MB 00:00:03
-------------------------------------------------------------------------------------------------------------------------
Total 2.2 MB/s | 8.0 MB 00:00:03
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : php70u-common-7.0.8-1.ius.centos7.x86_64 1/5
Installing : php70u-pdo-7.0.8-1.ius.centos7.x86_64 2/5
Installing : php70u-mysqlnd-7.0.8-1.ius.centos7.x86_64 3/5
Installing : php70u-cli-7.0.8-1.ius.centos7.x86_64 4/5
Installing : mod_php70u-7.0.8-1.ius.centos7.x86_64 5/5
Verifying : php70u-cli-7.0.8-1.ius.centos7.x86_64 1/5
Verifying : php70u-common-7.0.8-1.ius.centos7.x86_64 2/5
Verifying : mod_php70u-7.0.8-1.ius.centos7.x86_64 3/5
Verifying : php70u-pdo-7.0.8-1.ius.centos7.x86_64 4/5
Verifying : php70u-mysqlnd-7.0.8-1.ius.centos7.x86_64 5/5
Installed:
mod_php70u.x86_64 0:7.0.8-1.ius.centos7 php70u-cli.x86_64 0:7.0.8-1.ius.centos7
php70u-mysqlnd.x86_64 0:7.0.8-1.ius.centos7
Dependency Installed:
php70u-common.x86_64 0:7.0.8-1.ius.centos7 php70u-pdo.x86_64 0:7.0.8-1.ius.centos7
Complete!
Finally, we will restart the apache and check the status of the apache
# systemctl restart httpd
Checking the apache service status
# systemctl status httpd
httpd.service - The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
Active: active (running) since Thu 2016-07-21 10:24:44 EDT; 46s ago
Docs: man:httpd(8)
man:apachectl(8)
Main PID: 3636 (httpd)
Status: "Total requests: 0; Current requests/sec: 0; Current traffic: 0 B/sec"
CGroup: /system.slice/httpd.service
├─3636 /usr/sbin/httpd -DFOREGROUND
├─3637 /usr/sbin/httpd -DFOREGROUND
├─3638 /usr/sbin/httpd -DFOREGROUND
├─3639 /usr/sbin/httpd -DFOREGROUND
├─3640 /usr/sbin/httpd -DFOREGROUND
└─3641 /usr/sbin/httpd -DFOREGROUND
Jul 21 10:24:43 centos-linux-1.shared systemd[1]: Starting The Apache HTTP Server...
Jul 21 10:24:44 centos-linux-1.shared systemd[1]: Started The Apache HTTP Server.
We can verify the PHP version by using a command line mode and we can also create an info.php and check the version of the PHP
# php -v
PHP 7.0.8 (cli) (built: Jun 23 2016 11:34:57) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
Creating the info.php file using the below code and check the info in GUI mode.
# /var/www/html/info.php
<?php
Phpinfo();
?>
After we create the file access the web browser with the below url
http://IP_Address /info.php
After we setup and configure the above steps we can now able to update the PHP 5.x to PHP 7 on Centos 7 / RHEL 7 as of now the Official repository for the CentOS 7 is not released. We can also see that PHP 7 upgraded on the server.
|
[
{
"code": null,
"e": 1245,
"s": 1062,
"text": "In this article, we will learn about how to upgrade and update PHP 5.x to PHP 7, PHP 7 which was released in 2015 with speed improvements comparable to the older versions of the PHP."
},
{
"code": null,
"e": 1395,
"s": 1245,
"text": "Assuming that we have already installed PHP 5.x on CentOS7, and mod_php module should be enabled by Apache, and we need Sudo privileges or root user."
},
{
"code": null,
"e": 1505,
"s": 1395,
"text": "As PHP 7.x is not available in the official repositories, so we need to use IUS community Project Repository."
},
{
"code": null,
"e": 1571,
"s": 1505,
"text": "Download the IUS repository in the machine with the below command"
},
{
"code": null,
"e": 1824,
"s": 1571,
"text": "# curl 'https://setup.ius.io/' -o setup-ius.sh\ncurl 'https://setup.ius.io/' -o setup-ius.sh\n% Total % Received % Xferd Average Speed Time Time Time Current\nDload Upload Total Spent Left Speed\n100 1913 100 1913 0 0 1554 0 0:00:01 0:00:01 --:--:-- 1555\n\n"
},
{
"code": null,
"e": 1898,
"s": 1824,
"text": "Installing the IUS repository to the local machine with the below command"
},
{
"code": null,
"e": 3763,
"s": 1898,
"text": "# bash setup-ius.sh\nbash setup-ius.sh\ndetected CentOS 7\nLoaded plugins: fastestmirror\nbase | 3.6 kB\nepel/x86_64/metalink | 5.2 kB\nepel | 4.3 kB\nextras | 3. 4 kB 00:00:00\nmysql56-community | 2.5 kB 00:00:00\nupdates | 3.4 kB 00:00:00\n(1/3): updates/7/x86_64/primary_db | 5.7 MB 00:00:00\n(2/3): epel/x86_64/updateinfo | 584 kB 00:00:02\n(3/3): epel/x86_64/primary_db | 4.3 MB 00:00:03\nLoading mirror speeds from cached hostfile\n* base: mirrors.nhanhoa.com\n* epel: kodeterbuka.beritagar.id\n* extras: mirrors.nhanhoa.com\n* updates: mirrors.nhanhoa.com\nPackage epel-release-7-7.noarch already installed and latest version\nNothing to do\nLoaded plugins: fastestmirror\nius-release.rpm | 8.1 kB 00:00:00\nExamining /var/tmp/yum-root-BRDs50/ius-release.rpm: ius-release-1.0-14.ius.centos7.noarch\nMarking /var/tmp/yum-root-BRDs50/ius-release.rpm to be installed\nResolving Dependencies\n--> Running transaction check\n---> Package ius-release.noarch 0:1.0-14.ius.centos7 will be installed\n--> Finished Dependency Resolution\nDependencies Resolved\n=========================================================================================================================\nPackage Arch Version Repository Size=========================================================================================================================\nInstalling:\nius-release noarch 1.0-14.ius.centos7 /ius-release 8.\nTransaction Summary\n=========================================================================================================================\nInstall 1 Package\nTotal size: 8.5 k\nInstalled size: 8.5 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\nInstalling : ius-release-1.0-14.ius.centos7.noarch 1/1\nVerifying : ius-release-1.0-14.ius.centos7.noarch 1/1\nInstalled:\nius-release.noarch 0:1.0-14.ius.centos7\nComplete!"
},
{
"code": null,
"e": 3887,
"s": 3763,
"text": "Here,we will upgrade the system for Apachhe module mod_php. First, we will remove the old packages using the below command."
},
{
"code": null,
"e": 3927,
"s": 3887,
"text": "# yum remove php-cli mod_php php-common"
},
{
"code": null,
"e": 4010,
"s": 3927,
"text": "Installing the new PHP 7 modules using the IUS repository using the below command."
},
{
"code": null,
"e": 7340,
"s": 4010,
"text": "# yum install php70-mysqlnd mod_php70u php70u-cli\nLoaded plugins: fastestmirror\nius | 2.2 kB 00:00:00\nius/x86_64/primary_db | 173 kB 00:00:00\nLoading mirror speeds from cached hostfile\n* base: mirrors.nhanhoa.com\n* epel: kodeterbuka.beritagar.id\n* extras: mirrors.nhanhoa.com\n* ius: hkg.mirror.rackspace.com\n* updates: mirrors.nhanhoa.com\nResolving Dependencies\n--> Running transaction check\n---> Package mod_php70u.x86_64 0:7.0.8-1.ius.centos7 will be installed\n--> Processing Dependency: php-common(x86-64) = 7.0.8-1.ius.centos7 for package: mod_php70u-7.0.8-1.ius.centos7.x86_64\n---> Package php70u-cli.x86_64 0:7.0.8-1.ius.centos7 will be installed\n---> Package php70u-mysqlnd.x86_64 0:7.0.8-1.ius.centos7 will be installed\n--> Processing Dependency: php-pdo(x86-64) = 7.0.8-1.ius.centos7 for package: php70u-mysqlnd-7.0.8-1.ius.centos7.x86_64\n--> Running transaction check\n---> Package php70u-common.x86_64 0:7.0.8-1.ius.centos7 will be installed\n---> Package php70u-pdo.x86_64 0:7.0.8-1.ius.centos7 will be installed\n--> Finished Dependency Resolution\nDependencies Resolved\n=========================================================================================================================\nPackage Arch Version Repository Size\n=========================================================================================================================\nInstalling:\nmod_php70u x86_64 7.0.8-1.ius.centos7 ius 2.6 M\nphp70u-cli x86_64 7.0.8-1.ius.centos7 ius 4.0 M\nphp70u-mysqlnd x86_64 7.0.8-1.ius.centos7 ius 239 k\nInstalling for dependencies:\nphp70u-common x86_64 7.0.8-1.ius.centos7 ius 1.1 M\nphp70u-pdo x86_64 7.0.8-1.ius.centos7 ius 126 k\nTransaction Summary\n=========================================================================================================================\nInstall 3 Packages (+2 Dependent packages)\nTotal download size: 8.0 M\nInstalled size: 30 M\nIs this ok [y/d/N]: y\nDownloading packages:\n(1/5): php70u-pdo-7.0.8-1.ius.centos7.x86_64.rpm | 126 kB 00:00:00\n(2/5): mod_php70u-7.0.8-1.ius.centos7.x86_64.rpm | 2.6 MB 00:00:01\n(3/5): php70u-common-7.0.8-1.ius.centos7.x86_64.rpm | 1.1 MB 00:00:01\n(4/5): php70u-mysqlnd-7.0.8-1.ius.centos7.x86_64.rpm | 239 kB 00:00:01\n(5/5): php70u-cli-7.0.8-1.ius.centos7.x86_64.rpm | 4.0 MB 00:00:03\n-------------------------------------------------------------------------------------------------------------------------\nTotal 2.2 MB/s | 8.0 MB 00:00:03\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\nInstalling : php70u-common-7.0.8-1.ius.centos7.x86_64 1/5\nInstalling : php70u-pdo-7.0.8-1.ius.centos7.x86_64 2/5\nInstalling : php70u-mysqlnd-7.0.8-1.ius.centos7.x86_64 3/5\nInstalling : php70u-cli-7.0.8-1.ius.centos7.x86_64 4/5\nInstalling : mod_php70u-7.0.8-1.ius.centos7.x86_64 5/5\nVerifying : php70u-cli-7.0.8-1.ius.centos7.x86_64 1/5\nVerifying : php70u-common-7.0.8-1.ius.centos7.x86_64 2/5\nVerifying : mod_php70u-7.0.8-1.ius.centos7.x86_64 3/5\nVerifying : php70u-pdo-7.0.8-1.ius.centos7.x86_64 4/5\nVerifying : php70u-mysqlnd-7.0.8-1.ius.centos7.x86_64 5/5\nInstalled:\nmod_php70u.x86_64 0:7.0.8-1.ius.centos7 php70u-cli.x86_64 0:7.0.8-1.ius.centos7\nphp70u-mysqlnd.x86_64 0:7.0.8-1.ius.centos7\nDependency Installed:\nphp70u-common.x86_64 0:7.0.8-1.ius.centos7 php70u-pdo.x86_64 0:7.0.8-1.ius.centos7\nComplete!"
},
{
"code": null,
"e": 7411,
"s": 7340,
"text": "Finally, we will restart the apache and check the status of the apache"
},
{
"code": null,
"e": 7437,
"s": 7411,
"text": "# systemctl restart httpd"
},
{
"code": null,
"e": 7472,
"s": 7437,
"text": "Checking the apache service status"
},
{
"code": null,
"e": 8251,
"s": 7472,
"text": "# systemctl status httpd\nhttpd.service - The Apache HTTP Server\nLoaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)\nActive: active (running) since Thu 2016-07-21 10:24:44 EDT; 46s ago\nDocs: man:httpd(8)\nman:apachectl(8)\nMain PID: 3636 (httpd)\nStatus: \"Total requests: 0; Current requests/sec: 0; Current traffic: 0 B/sec\"\nCGroup: /system.slice/httpd.service\n├─3636 /usr/sbin/httpd -DFOREGROUND\n├─3637 /usr/sbin/httpd -DFOREGROUND\n├─3638 /usr/sbin/httpd -DFOREGROUND\n├─3639 /usr/sbin/httpd -DFOREGROUND\n├─3640 /usr/sbin/httpd -DFOREGROUND\n└─3641 /usr/sbin/httpd -DFOREGROUND\nJul 21 10:24:43 centos-linux-1.shared systemd[1]: Starting The Apache HTTP Server...\nJul 21 10:24:44 centos-linux-1.shared systemd[1]: Started The Apache HTTP Server."
},
{
"code": null,
"e": 8378,
"s": 8251,
"text": "We can verify the PHP version by using a command line mode and we can also create an info.php and check the version of the PHP"
},
{
"code": null,
"e": 8541,
"s": 8378,
"text": "# php -v\nPHP 7.0.8 (cli) (built: Jun 23 2016 11:34:57) ( NTS )\nCopyright (c) 1997-2016 The PHP Group\nZend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies"
},
{
"code": null,
"e": 8621,
"s": 8541,
"text": "Creating the info.php file using the below code and check the info in GUI mode."
},
{
"code": null,
"e": 8666,
"s": 8621,
"text": "# /var/www/html/info.php\n<?php\nPhpinfo();\n?>"
},
{
"code": null,
"e": 8733,
"s": 8666,
"text": "After we create the file access the web browser with the below url"
},
{
"code": null,
"e": 8761,
"s": 8733,
"text": "http://IP_Address /info.php"
},
{
"code": null,
"e": 8993,
"s": 8761,
"text": "After we setup and configure the above steps we can now able to update the PHP 5.x to PHP 7 on Centos 7 / RHEL 7 as of now the Official repository for the CentOS 7 is not released. We can also see that PHP 7 upgraded on the server."
}
] |
TypeScript - String Length Property
|
Returns the length of the string.
var uname = new String("Hello World")
console.log(uname)
console.log("Length "+uname.length) // returns the total number of characters
// including whitespace
On compiling, it will generate the same code in JavaScript.
Its output is as follows −
Hello World
Length 11
45 Lectures
4 hours
Antonio Papa
41 Lectures
7 hours
Haider Malik
60 Lectures
2.5 hours
Skillbakerystudios
77 Lectures
8 hours
Sean Bradley
77 Lectures
3.5 hours
TELCOMA Global
19 Lectures
3 hours
Christopher Frewin
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2082,
"s": 2048,
"text": "Returns the length of the string."
},
{
"code": null,
"e": 2283,
"s": 2082,
"text": "var uname = new String(\"Hello World\") \nconsole.log(uname) \nconsole.log(\"Length \"+uname.length) // returns the total number of characters \n // including whitespace\n"
},
{
"code": null,
"e": 2343,
"s": 2283,
"text": "On compiling, it will generate the same code in JavaScript."
},
{
"code": null,
"e": 2370,
"s": 2343,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 2394,
"s": 2370,
"text": "Hello World \nLength 11\n"
},
{
"code": null,
"e": 2427,
"s": 2394,
"text": "\n 45 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2441,
"s": 2427,
"text": " Antonio Papa"
},
{
"code": null,
"e": 2474,
"s": 2441,
"text": "\n 41 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 2488,
"s": 2474,
"text": " Haider Malik"
},
{
"code": null,
"e": 2523,
"s": 2488,
"text": "\n 60 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2543,
"s": 2523,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 2576,
"s": 2543,
"text": "\n 77 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2590,
"s": 2576,
"text": " Sean Bradley"
},
{
"code": null,
"e": 2625,
"s": 2590,
"text": "\n 77 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2641,
"s": 2625,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 2674,
"s": 2641,
"text": "\n 19 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 2694,
"s": 2674,
"text": " Christopher Frewin"
},
{
"code": null,
"e": 2701,
"s": 2694,
"text": " Print"
},
{
"code": null,
"e": 2712,
"s": 2701,
"text": " Add Notes"
}
] |
Number of Unique Paths | Practice | GeeksforGeeks
|
Given a A X B matrix with your initial position at the top-left cell, find the number of possible unique paths to reach the bottom-right cell of the matrix from the initial position.
Note: Possible moves can be either down or right at any point in time, i.e., we can move to matrix[i+1][j] or matrix[i][j+1] from matrix[i][j].
Example 1:
Input:
A = 2, B = 2
Output: 2
Explanation: There are only two unique
paths to reach the end of the matrix of
size two from the starting cell of the
matrix.
Example 2:
Input:
A = 3, B = 4
Output: 10
Explanation: There are only 10 unique
paths to reach the end of the matrix of
size two from the starting cell of the
matrix.
Your Task:
Complete NumberOfPath() function which takes 2 arguments(A and B) and returns the number of unique paths from top-left to the bottom-right cell.
Expected Time Complexity: O(A*B).
Expected Auxiliary Space: O(A*B).
Constraints:
1 ≤ A ≤ 15
1 ≤ B ≤ 15
0
abro20 hours ago
class Solution{ private: int n,m; vector<vector<int>>dp; public: //Function to find total number of unique paths. int solve( vector<vector<int>>&dp,int i,int j) { if(i==n or j==m) return dp[i][j]=0; if(dp[i][j]!=-1) return dp[i][j]; if(i==n-1 and j==m-1) return dp[i][j]=1; return dp[i][j] = solve(dp,i+1,j)+ solve(dp,i,j+1); } int NumberOfPath(int a, int b) { //code here n=a; m=b; dp.resize(n+1, vector<int>(m+1,-1)); return solve(dp,0,0); }};
+1
kashyapjhon2 days ago
C++ Solution Time=(0.01/1.31) EASY:
int NumberOfPath(int a, int b) { //code here vector<vector<int> > dp(a+1,vector<int> (b+1,1)); for(int i=1;i<a;i++){ for(int j=1;j<b;j++){ dp[i][j]=dp[i-1][j]+dp[i][j-1]; } } return dp[a-1][b-1]; }
0
vinamrajha1 week ago
int NumberOfPath(int a, int b)
{
//code here
int dp[a][b];
for(int i =0; i<a; ++i){
for(int j =0; j<b; ++j){
if(i==0 || j==0)dp[i][j] =1;
else dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[a-1][b-1];
}
0
tirtha19025681 month ago
class Solution
{
public static int NumberOfPath(int a, int b)
{
int[][]dp = new int[a][b];
for(int i=0;i<dp.length;i++){
for(int j=0;j<dp[0].length;j++){
dp[i][j] = -1;
}
}
int ans = helper(dp,0,0,a,b);
return ans;
}
static int helper(int[][]dp,int i,int j,int a,int b){
if(i == a || j == b ) return 0;
if(i == a-1 && j==b-1) return 1;
if(dp[i][j] != -1) return dp[i][j];
return dp[i][j] = helper(dp,i+1,j,a,b) + helper(dp,i,j+1,a,b);
}
}
0
vishalpandey100220002 months ago
public static int NumberOfPath(int a, int b) { //Your code here int dp[][]=new int[a][b]; for (int i=0;i<a;i++){ for (int j=0;j<b;j++){ if (i==0 || j==0){ dp[i][j]=1; } else{ dp[i][j]=dp[i][j-1]+dp[i-1][j]; } } } return dp[a-1][b-1]; }
0
ashiqhussainkumar1432 months ago
//Function to find total number of unique paths. int NumberOfPath(int N, int M) { //code here int DP[N][M]; for(int i=0;i<N;i++){ for(int j=0;j<M;j++){ if(i==0 or j==0) DP[i][j]=1; else DP[i][j]=DP[i][j-1] + DP[i-1][j]; } } return DP[N-1][M-1]; }
0
baibhavrajputt2 months ago
Java DP bottom up solution
class Solution
{
//Function to find total number of unique paths.
public static int NumberOfPath(int a, int b)
{
//Your code here
int dp[][] = new int[a][b];
for(int i=0 ; i<a ; i++){
for(int j=0 ; j<b ; j++){
if(i==0 && j==0)
dp[i][j] = 1;
else{
int up = 0;
int left = 0;
if(i>0)
up = dp[i-1][j];
if(j>0)
left = dp[i][j-1];
dp[i][j] = up + left;
}
}
}
return dp[a-1][b-1];
}
}
0
raunakmishra12432 months ago
int NumberOfPath(int n, int m)
{
int dp[n+1][m+1];
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(i==1 || j==1)
dp[i][j]=1;
}
}
for(int i=2;i<=n;i++)
{
for(int j=2;j<=m;j++)
dp[i][j]=dp[i][j-1]+dp[i-1][j];
}
return dp[n][m];
}
0
chaitanyasai3213 months ago
int NumberOfPath(int m, int n) { if(m == 1 || n == 1) return 1; m--; n--; if(m < n) { m = m + n; n = m - n; m = m - n; } long res = 1; int j = 1; for(int i = m+1; i <= m+n; i++, j++){ res *= i; res /= j; } return (int)res; }
+2
devendray21063 months ago
C++ solution :-
int NumberOfPath(int a, int b)
{
if(a==1 || b==1)
return 1;
return NumberOfPath(a-1,b)+NumberOfPath(a,b-1);
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 421,
"s": 238,
"text": "Given a A X B matrix with your initial position at the top-left cell, find the number of possible unique paths to reach the bottom-right cell of the matrix from the initial position."
},
{
"code": null,
"e": 565,
"s": 421,
"text": "Note: Possible moves can be either down or right at any point in time, i.e., we can move to matrix[i+1][j] or matrix[i][j+1] from matrix[i][j]."
},
{
"code": null,
"e": 576,
"s": 565,
"text": "Example 1:"
},
{
"code": null,
"e": 733,
"s": 576,
"text": "Input:\nA = 2, B = 2\nOutput: 2\nExplanation: There are only two unique\npaths to reach the end of the matrix of\nsize two from the starting cell of the\nmatrix.\n"
},
{
"code": null,
"e": 744,
"s": 733,
"text": "Example 2:"
},
{
"code": null,
"e": 900,
"s": 744,
"text": "Input:\nA = 3, B = 4\nOutput: 10\nExplanation: There are only 10 unique\npaths to reach the end of the matrix of\nsize two from the starting cell of the\nmatrix."
},
{
"code": null,
"e": 1056,
"s": 900,
"text": "Your Task:\nComplete NumberOfPath() function which takes 2 arguments(A and B) and returns the number of unique paths from top-left to the bottom-right cell."
},
{
"code": null,
"e": 1124,
"s": 1056,
"text": "Expected Time Complexity: O(A*B).\nExpected Auxiliary Space: O(A*B)."
},
{
"code": null,
"e": 1159,
"s": 1124,
"text": "Constraints:\n1 ≤ A ≤ 15\n1 ≤ B ≤ 15"
},
{
"code": null,
"e": 1161,
"s": 1159,
"text": "0"
},
{
"code": null,
"e": 1178,
"s": 1161,
"text": "abro20 hours ago"
},
{
"code": null,
"e": 1760,
"s": 1178,
"text": "class Solution{ private: int n,m; vector<vector<int>>dp; public: //Function to find total number of unique paths. int solve( vector<vector<int>>&dp,int i,int j) { if(i==n or j==m) return dp[i][j]=0; if(dp[i][j]!=-1) return dp[i][j]; if(i==n-1 and j==m-1) return dp[i][j]=1; return dp[i][j] = solve(dp,i+1,j)+ solve(dp,i,j+1); } int NumberOfPath(int a, int b) { //code here n=a; m=b; dp.resize(n+1, vector<int>(m+1,-1)); return solve(dp,0,0); }};"
},
{
"code": null,
"e": 1763,
"s": 1760,
"text": "+1"
},
{
"code": null,
"e": 1785,
"s": 1763,
"text": "kashyapjhon2 days ago"
},
{
"code": null,
"e": 1821,
"s": 1785,
"text": "C++ Solution Time=(0.01/1.31) EASY:"
},
{
"code": null,
"e": 2087,
"s": 1821,
"text": "int NumberOfPath(int a, int b) { //code here vector<vector<int> > dp(a+1,vector<int> (b+1,1)); for(int i=1;i<a;i++){ for(int j=1;j<b;j++){ dp[i][j]=dp[i-1][j]+dp[i][j-1]; } } return dp[a-1][b-1]; }"
},
{
"code": null,
"e": 2089,
"s": 2087,
"text": "0"
},
{
"code": null,
"e": 2110,
"s": 2089,
"text": "vinamrajha1 week ago"
},
{
"code": null,
"e": 2409,
"s": 2110,
"text": "int NumberOfPath(int a, int b)\n {\n //code here\n int dp[a][b];\n for(int i =0; i<a; ++i){\n for(int j =0; j<b; ++j){\n if(i==0 || j==0)dp[i][j] =1;\n else dp[i][j] = dp[i-1][j] + dp[i][j-1];\n }\n }\n return dp[a-1][b-1];\n }"
},
{
"code": null,
"e": 2411,
"s": 2409,
"text": "0"
},
{
"code": null,
"e": 2436,
"s": 2411,
"text": "tirtha19025681 month ago"
},
{
"code": null,
"e": 3028,
"s": 2436,
"text": "class Solution\n{\n public static int NumberOfPath(int a, int b) \n {\n int[][]dp = new int[a][b];\n \n for(int i=0;i<dp.length;i++){\n for(int j=0;j<dp[0].length;j++){\n dp[i][j] = -1;\n }\n }\n int ans = helper(dp,0,0,a,b);\n return ans;\n }\n \n static int helper(int[][]dp,int i,int j,int a,int b){\n if(i == a || j == b ) return 0;\n if(i == a-1 && j==b-1) return 1;\n \n if(dp[i][j] != -1) return dp[i][j];\n \n return dp[i][j] = helper(dp,i+1,j,a,b) + helper(dp,i,j+1,a,b);\n \n }\n}"
},
{
"code": null,
"e": 3030,
"s": 3028,
"text": "0"
},
{
"code": null,
"e": 3063,
"s": 3030,
"text": "vishalpandey100220002 months ago"
},
{
"code": null,
"e": 3446,
"s": 3063,
"text": "public static int NumberOfPath(int a, int b) { //Your code here int dp[][]=new int[a][b]; for (int i=0;i<a;i++){ for (int j=0;j<b;j++){ if (i==0 || j==0){ dp[i][j]=1; } else{ dp[i][j]=dp[i][j-1]+dp[i-1][j]; } } } return dp[a-1][b-1]; }"
},
{
"code": null,
"e": 3448,
"s": 3446,
"text": "0"
},
{
"code": null,
"e": 3481,
"s": 3448,
"text": "ashiqhussainkumar1432 months ago"
},
{
"code": null,
"e": 3816,
"s": 3481,
"text": " //Function to find total number of unique paths. int NumberOfPath(int N, int M) { //code here int DP[N][M]; for(int i=0;i<N;i++){ for(int j=0;j<M;j++){ if(i==0 or j==0) DP[i][j]=1; else DP[i][j]=DP[i][j-1] + DP[i-1][j]; } } return DP[N-1][M-1]; }"
},
{
"code": null,
"e": 3818,
"s": 3816,
"text": "0"
},
{
"code": null,
"e": 3845,
"s": 3818,
"text": "baibhavrajputt2 months ago"
},
{
"code": null,
"e": 3872,
"s": 3845,
"text": "Java DP bottom up solution"
},
{
"code": null,
"e": 4657,
"s": 3872,
"text": "class Solution\n{\n //Function to find total number of unique paths.\n public static int NumberOfPath(int a, int b) \n {\n //Your code here\n int dp[][] = new int[a][b];\n \n for(int i=0 ; i<a ; i++){\n for(int j=0 ; j<b ; j++){\n \n if(i==0 && j==0)\n dp[i][j] = 1;\n \n else{\n int up = 0;\n int left = 0;\n \n if(i>0)\n up = dp[i-1][j];\n \n if(j>0)\n left = dp[i][j-1];\n \n dp[i][j] = up + left;\n }\n }\n }\n return dp[a-1][b-1];\n }\n}"
},
{
"code": null,
"e": 4659,
"s": 4657,
"text": "0"
},
{
"code": null,
"e": 4688,
"s": 4659,
"text": "raunakmishra12432 months ago"
},
{
"code": null,
"e": 5105,
"s": 4688,
"text": "int NumberOfPath(int n, int m)\n {\n int dp[n+1][m+1];\n for(int i=1;i<=n;i++)\n {\n for(int j=1;j<=m;j++)\n {\n if(i==1 || j==1)\n dp[i][j]=1;\n \n }\n }\n \n for(int i=2;i<=n;i++)\n {\n for(int j=2;j<=m;j++)\n dp[i][j]=dp[i][j-1]+dp[i-1][j];\n }\n return dp[n][m];\n }"
},
{
"code": null,
"e": 5107,
"s": 5105,
"text": "0"
},
{
"code": null,
"e": 5135,
"s": 5107,
"text": "chaitanyasai3213 months ago"
},
{
"code": null,
"e": 5520,
"s": 5135,
"text": "int NumberOfPath(int m, int n) { if(m == 1 || n == 1) return 1; m--; n--; if(m < n) { m = m + n; n = m - n; m = m - n; } long res = 1; int j = 1; for(int i = m+1; i <= m+n; i++, j++){ res *= i; res /= j; } return (int)res; } "
},
{
"code": null,
"e": 5523,
"s": 5520,
"text": "+2"
},
{
"code": null,
"e": 5549,
"s": 5523,
"text": "devendray21063 months ago"
},
{
"code": null,
"e": 5565,
"s": 5549,
"text": "C++ solution :-"
},
{
"code": null,
"e": 5724,
"s": 5565,
"text": " int NumberOfPath(int a, int b)\n {\n if(a==1 || b==1)\n return 1;\n \n return NumberOfPath(a-1,b)+NumberOfPath(a,b-1);\n }"
},
{
"code": null,
"e": 5870,
"s": 5724,
"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": 5906,
"s": 5870,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5916,
"s": 5906,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5926,
"s": 5916,
"text": "\nContest\n"
},
{
"code": null,
"e": 5989,
"s": 5926,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6137,
"s": 5989,
"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": 6345,
"s": 6137,
"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": 6451,
"s": 6345,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
SWING - FocusListener Interface
|
The interface FocusListener is used for receiving keyboard focus events. The class that processes focus events needs to implements this interface.
Following is the declaration for java.awt.event.FocusListener interface −
public interface FocusListener
extends EventListener
void focusGained(FocusEvent e)
Invoked when a component gains the keyboard focus.
void focusLost(FocusEvent e)
Invoked when a component loses the keyboard focus.
This class inherits methods from the following interfaces −
java.awt.event.EventListener
Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingListenerDemo.java
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingListenerDemo {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public SwingListenerDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingListenerDemo swingListenerDemo = new SwingListenerDemo();
swingListenerDemo.showFocusListenerDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java SWING Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showFocusListenerDemo(){
headerLabel.setText("Listener in action: FocusListener");
JButton okButton = new JButton("OK");
JButton cancelButton = new JButton("Cancel");
okButton.addFocusListener(new CustomFocusListener());
cancelButton.addFocusListener(new CustomFocusListener());
controlPanel.add(okButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
class CustomFocusListener implements FocusListener{
public void focusGained(FocusEvent e) {
statusLabel.setText(statusLabel.getText()
+ e.getComponent().getClass().getSimpleName() + " gained focus. ");
}
public void focusLost(FocusEvent e) {
statusLabel.setText(statusLabel.getText()
+ e.getComponent().getClass().getSimpleName() + " lost focus. ");
}
}
}
Compile the program using the command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingListenerDemo.java
If no error occurs, it means the compilation is successful. Run the program using the following command.
D:\SWING>java com.tutorialspoint.gui.SwingListenerDemo
Verify the following output.
30 Lectures
3.5 hours
Pranjal Srivastava
13 Lectures
1 hours
Pranjal Srivastava
25 Lectures
4.5 hours
Emenwa Global, Ejike IfeanyiChukwu
14 Lectures
1.5 hours
Travis Rose
14 Lectures
1 hours
Travis Rose
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1911,
"s": 1763,
"text": "The interface FocusListener is used for receiving keyboard focus events. The class that processes focus events needs to implements this interface."
},
{
"code": null,
"e": 1985,
"s": 1911,
"text": "Following is the declaration for java.awt.event.FocusListener interface −"
},
{
"code": null,
"e": 2039,
"s": 1985,
"text": "public interface FocusListener\nextends EventListener\n"
},
{
"code": null,
"e": 2070,
"s": 2039,
"text": "void focusGained(FocusEvent e)"
},
{
"code": null,
"e": 2121,
"s": 2070,
"text": "Invoked when a component gains the keyboard focus."
},
{
"code": null,
"e": 2150,
"s": 2121,
"text": "void focusLost(FocusEvent e)"
},
{
"code": null,
"e": 2201,
"s": 2150,
"text": "Invoked when a component loses the keyboard focus."
},
{
"code": null,
"e": 2261,
"s": 2201,
"text": "This class inherits methods from the following interfaces −"
},
{
"code": null,
"e": 2290,
"s": 2261,
"text": "java.awt.event.EventListener"
},
{
"code": null,
"e": 2406,
"s": 2290,
"text": "Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >"
},
{
"code": null,
"e": 2429,
"s": 2406,
"text": "SwingListenerDemo.java"
},
{
"code": null,
"e": 4530,
"s": 2429,
"text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\n\npublic class SwingListenerDemo {\n private JFrame mainFrame;\n private JLabel headerLabel;\n private JLabel statusLabel;\n private JPanel controlPanel;\n \n public SwingListenerDemo(){\n prepareGUI();\n }\n public static void main(String[] args){\n SwingListenerDemo swingListenerDemo = new SwingListenerDemo(); \n swingListenerDemo.showFocusListenerDemo();\n }\n private void prepareGUI(){\n mainFrame = new JFrame(\"Java SWING Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n\n headerLabel = new JLabel(\"\",JLabel.CENTER );\n statusLabel = new JLabel(\"\",JLabel.CENTER); \n statusLabel.setSize(350,100);\n \n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n controlPanel = new JPanel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n private void showFocusListenerDemo(){\n headerLabel.setText(\"Listener in action: FocusListener\"); \n JButton okButton = new JButton(\"OK\");\n JButton cancelButton = new JButton(\"Cancel\");\n \n okButton.addFocusListener(new CustomFocusListener()); \n cancelButton.addFocusListener(new CustomFocusListener()); \n \n controlPanel.add(okButton);\n controlPanel.add(cancelButton); \n mainFrame.setVisible(true); \n }\n class CustomFocusListener implements FocusListener{\n public void focusGained(FocusEvent e) {\n statusLabel.setText(statusLabel.getText() \n + e.getComponent().getClass().getSimpleName() + \" gained focus. \");\n }\n public void focusLost(FocusEvent e) {\n statusLabel.setText(statusLabel.getText() \n + e.getComponent().getClass().getSimpleName() + \" lost focus. \");\n }\n }\n}"
},
{
"code": null,
"e": 4626,
"s": 4530,
"text": "Compile the program using the command prompt. Go to D:/ > SWING and type the following command."
},
{
"code": null,
"e": 4688,
"s": 4626,
"text": "D:\\SWING>javac com\\tutorialspoint\\gui\\SwingListenerDemo.java\n"
},
{
"code": null,
"e": 4793,
"s": 4688,
"text": "If no error occurs, it means the compilation is successful. Run the program using the following command."
},
{
"code": null,
"e": 4849,
"s": 4793,
"text": "D:\\SWING>java com.tutorialspoint.gui.SwingListenerDemo\n"
},
{
"code": null,
"e": 4878,
"s": 4849,
"text": "Verify the following output."
},
{
"code": null,
"e": 4913,
"s": 4878,
"text": "\n 30 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4933,
"s": 4913,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 4966,
"s": 4933,
"text": "\n 13 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4986,
"s": 4966,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 5021,
"s": 4986,
"text": "\n 25 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5057,
"s": 5021,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 5092,
"s": 5057,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5105,
"s": 5092,
"text": " Travis Rose"
},
{
"code": null,
"e": 5138,
"s": 5105,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5151,
"s": 5138,
"text": " Travis Rose"
},
{
"code": null,
"e": 5158,
"s": 5151,
"text": " Print"
},
{
"code": null,
"e": 5169,
"s": 5158,
"text": " Add Notes"
}
] |
How to create Horizontal ListView in Android using Kotlin?
|
This example demonstrates how to create Horizontal ListView in Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rlMain"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.util.ArrayList
class MainActivity : AppCompatActivity() {
private val movieList = ArrayList<MovieModel>()
private lateinit var moviesAdapter: MoviesAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
moviesAdapter = MoviesAdapter(movieList)
val mLayoutManager = LinearLayoutManager(applicationContext)
mLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
recyclerView.layoutManager = mLayoutManager
recyclerView.itemAnimator = DefaultItemAnimator()
recyclerView.adapter = moviesAdapter
prepareMovieData()
}
private fun prepareMovieData() {
var movie = MovieModel("Mad Max: Fury Road", "Action & Adventure", "2015")
movieList.add(movie)
movie = MovieModel("Inside Out", "Animation, Kids & Family", "2015")
movieList.add(movie)
movie = MovieModel("Star Wars: Episode VII - The Force Awakens", "Action", "2015")
movieList.add(movie)
movie = MovieModel("Shaun the Sheep", "Animation", "2015")
movieList.add(movie)
movie = MovieModel("The Martian", "Science Fiction & Fantasy", "2015")
movieList.add(movie)
movie = MovieModel("Mission: Impossible Rogue Nation", "Action", "2015")
movieList.add(movie)
movie = MovieModel("Up", "Animation", "2009")
movieList.add(movie)
movie = MovieModel("Star Trek", "Science Fiction", "2009")
movieList.add(movie)
movie = MovieModel("The LEGO MovieModel", "Animation", "2014")
movieList.add(movie)
movie = MovieModel("Iron Man", "Action & Adventure", "2008")
movieList.add(movie)
movie = MovieModel("Aliens", "Science Fiction", "1986")
movieList.add(movie)
movie = MovieModel("Chicken Run", "Animation", "2000")
movieList.add(movie)
movie = MovieModel("Back to the Future", "Science Fiction", "1985")
movieList.add(movie)
movie = MovieModel("Raiders of the Lost Ark", "Action & Adventure", "1981")
movieList.add(movie)
movie = MovieModel("Goldfinger", "Action & Adventure", "1965")
movieList.add(movie)
movie = MovieModel("Guardians of the Galaxy", "Science Fiction & Fantasy", "2014")
movieList.add(movie)
moviesAdapter.notifyDataSetChanged()
}
}
Step 4 − Create a new class MovieModel.kt and add the following code −
class MovieModel(title: String?, genre: String?, year: String?) {
private var title: String
private var genre: String
private var year: String
init {
this.title = title!!
this.genre = genre!!
this.year = year!!
}
fun getTitle(): String? {
return title
}
fun setTitle(name: String?) {
title = name!!
}
fun getYear(): String? {
return year
}
fun setYear(year: String?) {
this.year = year!!
}
fun getGenre(): String? {
return genre
}
fun setGenre(genre: String?) {
this.genre = genre!!
}
}
Step 5 − Create a new class MovieAdapter.kt and add the following code −
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.NonNull
import androidx.recyclerview.widget.RecyclerView
internal class MoviesAdapter(private var moviesList: List<MovieModel>) :
RecyclerView.Adapter<MoviesAdapter.MyViewHolder>() {
internal inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var title: TextView = view.findViewById(R.id.title)
var year: TextView = view.findViewById(R.id.year)
var genre: TextView = view.findViewById(R.id.genre)
}
@NonNull
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.movie_list, parent, false)
return MyViewHolder(itemView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val movie = moviesList[position]
holder.title.text = movie.getTitle()
holder.genre.text = movie.getGenre()
holder.year.text = movie.getYear()
}
override fun getItemCount(): Int {
return moviesList.size
}
}
Step 6 − Create a new Layout resource file (movie_list.xml) and add the following code −
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.NonNull
import androidx.recyclerview.widget.RecyclerView
internal class MoviesAdapter(private var moviesList: List<MovieModel>) :
RecyclerView.Adapter<MoviesAdapter.MyViewHolder>() {
internal inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var title: TextView = view.findViewById(R.id.title)
var year: TextView = view.findViewById(R.id.year)
var genre: TextView = view.findViewById(R.id.genre)
}
@NonNull
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.movie_list, parent, false)
return MyViewHolder(itemView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val movie = moviesList[position]
holder.title.text = movie.getTitle()
holder.genre.text = movie.getGenre()
holder.year.text = movie.getYear()
}
override fun getItemCount(): Int {
return moviesList.size
}
}
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="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
|
[
{
"code": null,
"e": 1147,
"s": 1062,
"text": "This example demonstrates how to create Horizontal ListView in Android using Kotlin."
},
{
"code": null,
"e": 1276,
"s": 1147,
"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": 1341,
"s": 1276,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1814,
"s": 1341,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:id=\"@+id/rlMain\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_margin=\"16dp\"\n android:orientation=\"vertical\">\n <androidx.recyclerview.widget.RecyclerView\n android:id=\"@+id/recyclerView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1869,
"s": 1814,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 4549,
"s": 1869,
"text": "import android.os.Bundle\nimport androidx.appcompat.app.AppCompatActivity\nimport androidx.recyclerview.widget.DefaultItemAnimator\nimport androidx.recyclerview.widget.LinearLayoutManager\nimport androidx.recyclerview.widget.RecyclerView\nimport java.util.ArrayList\nclass MainActivity : AppCompatActivity() {\n private val movieList = ArrayList<MovieModel>()\n private lateinit var moviesAdapter: MoviesAdapter\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)\n moviesAdapter = MoviesAdapter(movieList)\n val mLayoutManager = LinearLayoutManager(applicationContext)\n mLayoutManager.orientation = LinearLayoutManager.HORIZONTAL\n recyclerView.layoutManager = mLayoutManager\n recyclerView.itemAnimator = DefaultItemAnimator()\n recyclerView.adapter = moviesAdapter\n prepareMovieData()\n }\n private fun prepareMovieData() {\n var movie = MovieModel(\"Mad Max: Fury Road\", \"Action & Adventure\", \"2015\")\n movieList.add(movie)\n movie = MovieModel(\"Inside Out\", \"Animation, Kids & Family\", \"2015\")\n movieList.add(movie)\n movie = MovieModel(\"Star Wars: Episode VII - The Force Awakens\", \"Action\", \"2015\")\n movieList.add(movie)\n movie = MovieModel(\"Shaun the Sheep\", \"Animation\", \"2015\")\n movieList.add(movie)\n movie = MovieModel(\"The Martian\", \"Science Fiction & Fantasy\", \"2015\")\n movieList.add(movie)\n movie = MovieModel(\"Mission: Impossible Rogue Nation\", \"Action\", \"2015\")\n movieList.add(movie)\n movie = MovieModel(\"Up\", \"Animation\", \"2009\")\n movieList.add(movie)\n movie = MovieModel(\"Star Trek\", \"Science Fiction\", \"2009\")\n movieList.add(movie)\n movie = MovieModel(\"The LEGO MovieModel\", \"Animation\", \"2014\")\n movieList.add(movie)\n movie = MovieModel(\"Iron Man\", \"Action & Adventure\", \"2008\")\n movieList.add(movie)\n movie = MovieModel(\"Aliens\", \"Science Fiction\", \"1986\")\n movieList.add(movie)\n movie = MovieModel(\"Chicken Run\", \"Animation\", \"2000\")\n movieList.add(movie)\n movie = MovieModel(\"Back to the Future\", \"Science Fiction\", \"1985\")\n movieList.add(movie)\n movie = MovieModel(\"Raiders of the Lost Ark\", \"Action & Adventure\", \"1981\")\n movieList.add(movie)\n movie = MovieModel(\"Goldfinger\", \"Action & Adventure\", \"1965\")\n movieList.add(movie)\n movie = MovieModel(\"Guardians of the Galaxy\", \"Science Fiction & Fantasy\", \"2014\")\n movieList.add(movie)\n moviesAdapter.notifyDataSetChanged()\n }\n}"
},
{
"code": null,
"e": 4620,
"s": 4549,
"text": "Step 4 − Create a new class MovieModel.kt and add the following code −"
},
{
"code": null,
"e": 5212,
"s": 4620,
"text": "class MovieModel(title: String?, genre: String?, year: String?) {\n private var title: String\n private var genre: String\n private var year: String\n init {\n this.title = title!!\n this.genre = genre!!\n this.year = year!!\n }\n fun getTitle(): String? {\n return title\n }\n fun setTitle(name: String?) {\n title = name!!\n }\n fun getYear(): String? {\n return year\n }\n fun setYear(year: String?) {\n this.year = year!!\n }\n fun getGenre(): String? {\n return genre\n }\n fun setGenre(genre: String?) {\n this.genre = genre!!\n }\n}"
},
{
"code": null,
"e": 5285,
"s": 5212,
"text": "Step 5 − Create a new class MovieAdapter.kt and add the following code −"
},
{
"code": null,
"e": 6439,
"s": 5285,
"text": "import android.view.LayoutInflater\nimport android.view.View\nimport android.view.ViewGroup\nimport android.widget.TextView\nimport androidx.annotation.NonNull\nimport androidx.recyclerview.widget.RecyclerView\ninternal class MoviesAdapter(private var moviesList: List<MovieModel>) :\nRecyclerView.Adapter<MoviesAdapter.MyViewHolder>() {\n internal inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {\n var title: TextView = view.findViewById(R.id.title)\n var year: TextView = view.findViewById(R.id.year)\n var genre: TextView = view.findViewById(R.id.genre)\n }\n @NonNull\n override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {\n val itemView = LayoutInflater.from(parent.context)\n .inflate(R.layout.movie_list, parent, false)\n return MyViewHolder(itemView)\n }\n override fun onBindViewHolder(holder: MyViewHolder, position: Int) {\n val movie = moviesList[position]\n holder.title.text = movie.getTitle()\n holder.genre.text = movie.getGenre()\n holder.year.text = movie.getYear()\n }\n override fun getItemCount(): Int {\n return moviesList.size\n }\n}"
},
{
"code": null,
"e": 6528,
"s": 6439,
"text": "Step 6 − Create a new Layout resource file (movie_list.xml) and add the following code −"
},
{
"code": null,
"e": 7682,
"s": 6528,
"text": "import android.view.LayoutInflater\nimport android.view.View\nimport android.view.ViewGroup\nimport android.widget.TextView\nimport androidx.annotation.NonNull\nimport androidx.recyclerview.widget.RecyclerView\ninternal class MoviesAdapter(private var moviesList: List<MovieModel>) :\nRecyclerView.Adapter<MoviesAdapter.MyViewHolder>() {\n internal inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {\n var title: TextView = view.findViewById(R.id.title)\n var year: TextView = view.findViewById(R.id.year)\n var genre: TextView = view.findViewById(R.id.genre)\n }\n @NonNull\n override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {\n val itemView = LayoutInflater.from(parent.context)\n .inflate(R.layout.movie_list, parent, false)\n return MyViewHolder(itemView)\n }\n override fun onBindViewHolder(holder: MyViewHolder, position: Int) {\n val movie = moviesList[position]\n holder.title.text = movie.getTitle()\n holder.genre.text = movie.getGenre()\n holder.year.text = movie.getYear()\n }\n override fun getItemCount(): Int {\n return moviesList.size\n }\n}"
},
{
"code": null,
"e": 7737,
"s": 7682,
"text": "Step 7 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 8408,
"s": 7737,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 8756,
"s": 8408,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
Introduction to SQL with real life examples: analyze your grocery shopping habits | by Carolina Bento | Towards Data Science
|
SQL is a fundamental part of a Data Scientist’s toolbox. It’s a great tool to explore and prepare your data, either for analysis or to create a machine learning model.
An effective approach to learn SQL is to focus on the questions you want to answer, rather than on specific methods or functions. Once you know what you’re looking for, what questions you want to answer with data, the functions and operands you use to get there will make more sense.
This article is organized around what questions to ask about data, and you’ll become familiar with:
Structure of a SQL query,
Inspecting data quality,
Filtering, summarizing and combining data with SQL.
You’re the kind of person that likes to keep track of your daily activities, one of them being grocery shopping. Lately you’ve been keeping all grocery store receipts so you can analyze your buying patterns.
One way to analyze your buying patterns is to use SQL, with the local database engine sqlite. You downloaded sqlite and, using the command line, created a groceries database.
Now you’re in sqlite shell (see the prompt sqlite>).
Then you start thinking about how to organize that data from the receipts. You haven’t thought about specific questions yet, but you know to organize the data into two tables:
grocery_visit has summary of your trip to the grocery store with the date, the time spent shopping and how much money you spent.
grocery_list has the name and category of the items bought on each grocery store visit.
So, in the sqlite shell, you create those tables in your local database using the following commands:
create table grocery_visit(date TEXT, time_spent_min INTEGER, amount_spent REAL);create table grocery_list(date TEXT, item_name TEXT, item_category TEXT);
And just to make sure the tables were actually created, you double-check using the command .tables.
And then you go through each item of the grocery list.
insert into grocery_list values("2020-12-03", "Hamburger patties", "Meat and Fish");insert into grocery_list values("2020-12-03", "Chips", "Pantry");insert into grocery_list values("2020-12-03", "Avocado", "Fruits and Vegetables");insert into grocery_list values("2020-12-03", "Lime", "Fruits and Vegetables");insert into grocery_list values("2020-12-03", "Tomato", "Fruits and Vegetables");insert into grocery_list values("2020-12-15", "Rice cakes", "Pantry");insert into grocery_list values("2020-12-15", "Graham crackers", "Pantry");insert into grocery_list values("2020-12-15", "Toothpaste", NULL);insert into grocery_list values("2020-12-15", "Flour", "Pantry");insert into grocery_list values("2020-12-15", "Yeast", "Pantry");insert into grocery_list values("2020-12-15", "Popcorn", "Pantry");insert into grocery_list values("2020-12-15", "Eggs", NULL);insert into grocery_list values("2020-12-15", "Milk", "Dairy");insert into grocery_list values("2020-12-15", "Bananas", "Fruits and Vegetables");insert into grocery_list values("2020-12-15", "Frozen waffles", NULL);insert into grocery_list values("2020-12-23", "Mayo", "Pantry");insert into grocery_list values("2020-12-23", "Flour", "Pantry");insert into grocery_list values("2020-12-23", "Milk", "Dairy");insert into grocery_list values("2020-12-23", "Roasted Chicken", "Meat and Fish");insert into grocery_list values("2020-12-23", "Chocolate chip cookies", "Pantry");insert into grocery_list values("2020-12-23", "Yogurt", "Dairy");insert into grocery_list values("2020-12-23", "Soda", NULL);insert into grocery_list values("2020-12-23", "Grapes", "Fruits and Vegetables");
Now that all your grocery shopping data in the stored, you can start asking questions!
Before you start writing SQL to answer questions with data, let’s look at the building blocks of a SQL query.
You can think of a query as the result of filtering, transforming and combining one or more datasets.
In a broad sense, a SQL query is made of two parts, one mandatory and another optional:
Mandatory part defines the output and what data you are pulling from,
Optional part allows you to manipulate the data by filtering, aggregating, sorting or limiting the size of the output.
Each portion of the query, here numbered 1 through 6, is called a clause, which you can refer to using different reserved keywords. Each clause allows you to perform specific actions on the dataset you have at hand:
Select Everything after the select keyword represents the output of your query. It’s the end result.From The data you’re manipulating. It can be a table or the result of another query, usually called sub-query or inner query.Where Used to filter the data and to specify the set of conditions the data needs to comply to, in order for you to produce an output.Group by Indicates you’re aggregating the data, e.g., counting or summing values.Order by How you want to sort the results.Limit Indicates you only want to display a certain number of results.
Select Everything after the select keyword represents the output of your query. It’s the end result.
From The data you’re manipulating. It can be a table or the result of another query, usually called sub-query or inner query.
Where Used to filter the data and to specify the set of conditions the data needs to comply to, in order for you to produce an output.
Group by Indicates you’re aggregating the data, e.g., counting or summing values.
Order by How you want to sort the results.
Limit Indicates you only want to display a certain number of results.
Let’s write some queries and see all of this in action!
The first step in a data project is data exploration, getting to know your data. Once you know your data, it will be much easier to use the right methods or functions to answer your questions.
When you’re exploring this dataset, you may start by asking:
Can I see all the data?
Can I take a peek at the data?
Can I see all the possible values of a certain column?
In this case, you have very little data, so it’s possible to see all the data.
You can use select * to see all the data in a table, i.e., all the rows and columns.
select * from grocery_visit;
The wildcard * means you want to see all the columns in the resulting dataset. But, you might only be interested in a few columns:
select date, amount_spent from grocery_visit;
Notice that, at the end of each query statement there’s always a semicolon ;. This indicates the end of the query, and that sqlite can proceed to evaluate the query.
Even though you see all the data for date and amount_spent columns, it’s difficult to map the values to the respective column. This would be specially handy if you were working with a dataset built by someone else.
In sqlite you can adjust the settings to output column names, also referred to as table headers.
.headers on
So, if you run the query again you’ll see the columns names.
Seems like a small detail, but now it’s a bit easier to make sense of the results. From now on, all queries will output the headers of the resulting dataset.
Alright, back to your questions!
If you just want to take a peek at the data you can use, for instance, the limit operand to say limit the result of this query to only X number of records.
select * from grocery_list limit 10;
This returns the first 10 records from the grocery_list table.
You just took a quick look at the data but, before you start the analysis, it’s also important to check for any data quality issues.
For instance, you may have noticed that some items in the grocery_list don’t have a category. So you can ask Which items in my grocery list don’t have a category?
To check that, you can use the where clause and filter the output to only include items that have a null category.
select * from grocery_listwhere item_category is null;
You could also spot-check for invalid values, such as item names with typos or other values that don’t make sense in the column they are associated with. To do that you use the distinct reserved keyword, so it will output the a list of unique values instead of all values from a column, since there may be some duplication.
select distinct item_namefrom grocery_list;select distinct item_categoryfrom grocery_list;
Even the null category, with no name, shows up here.
In SQL you filter the dataset by defining a set of rules in the where clause. You just used to look for the item categories with Null values.
That was only one simple rule, but you can ask other interesting questions.
In this case you know the exact name of the item category, Fruits and Vegetables, but pretend for a second that you don’t 😀
You have a hunch that the category name must involve some variation of fruit, Fruit or even its plural. So, you can try to do a pattern match on the item category using the operator like. With this operator, you’re literally saying the filter for any item category like this [pattern].
select *from grocery_listwhere item_category like 'Fruit';
But you can’t just use it like this because, in practice, what you did was an exact match, the equivalent of using an equals instead of like.
To do a pattern match you need to use the wildcard %. This says filter for any item category that has Fruit in its name. Since the wildcard is at the end of the string, as long as it starts with Fruit, you’ll have a match.
select *from grocery_listwhere item_category like 'Fruit%';
In sqlite operator like is case-insensitive, so having condition like ‘Fruit%’ or like ‘fruit%’ produces the same output.
With this question, you want to filter the dataset based on multiple conditions. So you can use the where clause with two rules:
one that gives you all the days in which you’ve bought avocados,
one that gives you all the days in which you’ve bought milk.
select *from grocery_listwhere item_name = 'Avocado'or item_name = 'Milk';
You can re-write this where clause with the in operator, which will filter the dataset based on a list of items. In this case, the list contains only Avocado and Milk.
select *from grocery_listwhere item_name in ('Avocado', 'Milk');
Either way you want to filter, you’ll get the same output.
You can also filter the dataset to only output the data that is is within a certain range of values.
For instance, you may want to see all the grocery store visits in the first half of December.
select *from grocery_visitwhere date >= '2020-12-01'and date <= '2020-12-15';
Here you’re filtering the dataset using two conditions in the where clause but, if you want to make it easier to read, you can use the between operator.
select *from grocery_visitwhere date between '2020-12-01' and '2020-12-15';
Another set of questions you might want to ask can be seen as looking for a way to summarize the data.
For instance a summary of your visits to the grocery store can include:
Number of times you went to the grocery store, using the count function.
How long was you shortest and longest visits to the grocery store, using the min and max functions.
How much time have you spent shopping, on average, using the average function.
select count(*) as total_visits, min(time_spent_min) as shortest_visit, avg(time_spent_min) as average_visit, max(time_spent_min) as longest_visitfrom grocery_visit;
In your three visits to the grocery store, the shortest took 10 minutes, the longest took 50 minutes and, on average, your grocery store visits took approximately 29 minutes.
The wildcard *, means you’re counting all the records from the grocery_visit table.
When you’re exploring a dataset, it’s also useful to sort the output.
Going back to the structure of a SQL query, you can use the optional order by clause to specify how you want to sort the results. Then, using the ordering terms asc and desc, the output is sorted in ascending or descending order. By default, the order by clause sorts the output in ascending order.
Here you can use the default, and output the amount_spent in each grocery store visit from lowest to highest.
select *from grocery_visitorder by amount_spent;
Here it’s the exact same query, but specifying that the results are sorted in descending order.
select datefrom grocery_visitorder by date desc;
But, instead, you may only want to see the last time you went to the grocery store. Here you can use the clauses and operands you’ve seen so far.
select *from grocery_visitorder by date desclimit 1;
So far, you’ve been manipulating a single table. However, the most of the time, you’ll need to combine multiple tables to obtain insights.
In SQL, you combine multiple tables using the join operator. There are different types of joins and, each one combines the two tables according to different rules.
Since you also go to the department store often, you decided to store data about those visits in the table dept_store_visit.
create table dept_store_visit(date TEXT, time_spent_min INTEGER, amount_spent REAL);insert into dept_store_visit values ('2020-12-01', 40, 45.99);insert into dept_store_visit values ('2020-12-15', 25, 37.30);insert into dept_store_visit values ('2020-12-19', 20, 15.82);
With data from visits to both stores, you can ask a very interesting questions.
Joins are usually depicted as Venn diagrams (left), but you can also think about joining two datasets (right) that may or may not share characteristics, i.e., columns.
One way answer this question is to combine each record in one table with every record in the other table, to make sure the resulting dataset captures all the data from both tables.
To do this, you can use a cross join, then filter by the grocery visits when you spent more than $15.
In SQL, you’d write the following query:
select *from grocery_visitcross join dept_store_visitwhere grocery_visit.amount_spent > 15and dept_store_visit.amount_spent > 15;
By default in most database engines, and sqlite is no exception, you can omit the cross and you’ll be obtain the same output.
Because the records are mapped many-to-many, and the grocery_visit table only has one record greater than $15, it ends up paired with the 3 records in the dept_store_visit. Hence you see the record from grocery_visit table repeated 3 times in the output.
This definitely answers your question but, the structure of the output many not be exactly what you wanted.
It would be much easier to interpret if the output was a list of the days when you went to the grocery store and to the department store. As if you were appending the result of filtering each of those tables.
To do this you can use the union operator.
And because you are appending the records from each table, it’s mandatory that both tables have either the exact same structure or that you select the columns such that their structure matches by the time you perform the union.
select date, amount_spentfrom grocery_visitwhere amount_spent > 15unionselect date, amount_spentfrom dept_store_visitwhere amount_spent > 15;
Here again, the data necessary to answer this question lives in multiple tables, so you need to combine:
grocery_visit to get the amount_spent, and
grocery_list to filter by bread-making items like flour, yeast and eggs.
You just learned about cross joins. Let’s use it!
select *from grocery_visitcross join grocery_listwhere grocery_list.item_name in ('Flour', 'Yeast', 'Eggs');
If you inspect the resulting dataset, before doing the aggregation you see that something is not quite right.
The output dataset indeed has all the items you were looking for but, because you are using a cross join, all the records in the grocery_visit table are paired with the records you want in grocery_list.
If you did the average right now, you’d be looking at the wrong results, because the resulting dataset is not actually what you wanted.
What you really wanted is to only get data for the grocery visits when you’ve bought flour, yeast and eggs.
Thankfully there’s another join operator you can use, the inner join.
With an inner join you’re combining two datasets that have a similar characteristics and returning what’s common between them. For the inner join to work, both tables must have at least one column in common, because you need to specify which characteristic needs to be equal in both tables.
It follows the format:
tableA inner join tableB on tableA.shared_column = tableB.shared_column
Even if both tables have one or more columns in common, they must have the exact same value. Otherwise, your output dataset will be null.
Using the Venn diagram analogy, you’re looking for intersection between the two areas.
To answer this question you want to match both tables on the day of the grocery store visit.
select *from grocery_visitinner join grocery_liston grocery_visit.date = grocery_list.datewhere grocery_list.item_name in ('Flour', 'Yeast', 'Eggs');
So, taking a peek at the result of the inner join, you have:
You can also notice that you’ve bought multiple of those items on 2020–12–15, so the data for that grocery visit is repeated. However, you only want to calculate the average amount_spent in two visits, 2020–12–15 and 2020–12–23.
So, when you’re calculating the average amount_spent, you need to make sure you don’t count values multiple times. You can use the distinct keyword to take care of that.
select avg(distinct amount_spent) as avg_amount_spentfrom grocery_visitinner join grocery_liston grocery_visit.date = grocery_list.datewhere grocery_list.item_name in ('Flour', 'Yeast', 'Eggs');
But you might say, What about if different grocery visits have the same amount spent?
Going back to the anatomy of a SQL query, the from clause can pull data directly from a table like you’ve been doing so far, or from the result of another query, called sub-query.
To make sure you get all the different grocery visits where you bought flour, yeast and eggs, but also take into account:
Visits that happened in the same day, but have different amount spent and,
Visits from different days that have the exact same amount spent.
You can encapsulate that logic in a sub-query and only then do the average. That way you guarantee you’re not over-counting nor under-counting any of the grocery visits.
select avg(amount_spent) as avg_amount_spentfrom( select distinct grocery_visit.date, amount_spent from grocery_visit inner join grocery_list on grocery_visit.date = grocery_list.date where grocery_list.item_name in ('Flour', 'Yeast', 'Eggs');)
Since you’ve already filtered by the items of interest and you’re concerned about not over or under counting the spending in each visit, you can ignore all the columns from grocery_list in the sub-query.
In this question it’s clear that you’ll want to combine data that is in the grocery_visit and dept_store_visit tables.
But the main focus is on grocery store visits.
You’re going to be using a left join to answer this question.
Using the Venn diagram analogy, you’ll want all the data in the grocery_visit and only the records from dept_store_visit that match the days of the grocery store visits.
You can think of a left join as keep everything on the left (table) and bring only the matches from the right (table).
select grocery_visit.*, dept_store_visit.time_spent_min as time_spent_dept_store, dept_store_visit.amount_spent as amount_spent_dept_storefrom grocery_visitleft join dept_store_visiton grocery_visit.date = dept_store_visit.date;
Here grocery_visit.* means the output has all the columns from grocery_visit.
You can also think about this question the other way around On the days I went to the department store, did I also go to the grocery store? If so, how much time did I spend in these visits?
Most database engines support right join, which is exactly what is sounds like, the opposite of a left join. However, sqlite does not support right joins.
With a right join you keep everything on the right (table) and bring only the matches on the left (table). Which, in practice, means flipping the other of the tables in the last query.
You might also have noticed that, in the last query, the output of dept_store_visit was different than the original column names. That’s because we used an alias.
Aliases make it easier to reference tables and sub-queries with more interpretable names. In this case, we used aliases to rename the output columns to something that was distinguishable from the column in the other table table.
You’ve just went through an extensive look at the basics of SQL querying! But don’t worry, it doesn’t have to end here, there are many more nuanced questions you can ask with advanced SQL functions and operands.
Hope this article got you curious about SQL and how to answer questions with data.
Thanks for reading!
|
[
{
"code": null,
"e": 340,
"s": 172,
"text": "SQL is a fundamental part of a Data Scientist’s toolbox. It’s a great tool to explore and prepare your data, either for analysis or to create a machine learning model."
},
{
"code": null,
"e": 624,
"s": 340,
"text": "An effective approach to learn SQL is to focus on the questions you want to answer, rather than on specific methods or functions. Once you know what you’re looking for, what questions you want to answer with data, the functions and operands you use to get there will make more sense."
},
{
"code": null,
"e": 724,
"s": 624,
"text": "This article is organized around what questions to ask about data, and you’ll become familiar with:"
},
{
"code": null,
"e": 750,
"s": 724,
"text": "Structure of a SQL query,"
},
{
"code": null,
"e": 775,
"s": 750,
"text": "Inspecting data quality,"
},
{
"code": null,
"e": 827,
"s": 775,
"text": "Filtering, summarizing and combining data with SQL."
},
{
"code": null,
"e": 1035,
"s": 827,
"text": "You’re the kind of person that likes to keep track of your daily activities, one of them being grocery shopping. Lately you’ve been keeping all grocery store receipts so you can analyze your buying patterns."
},
{
"code": null,
"e": 1210,
"s": 1035,
"text": "One way to analyze your buying patterns is to use SQL, with the local database engine sqlite. You downloaded sqlite and, using the command line, created a groceries database."
},
{
"code": null,
"e": 1263,
"s": 1210,
"text": "Now you’re in sqlite shell (see the prompt sqlite>)."
},
{
"code": null,
"e": 1439,
"s": 1263,
"text": "Then you start thinking about how to organize that data from the receipts. You haven’t thought about specific questions yet, but you know to organize the data into two tables:"
},
{
"code": null,
"e": 1568,
"s": 1439,
"text": "grocery_visit has summary of your trip to the grocery store with the date, the time spent shopping and how much money you spent."
},
{
"code": null,
"e": 1656,
"s": 1568,
"text": "grocery_list has the name and category of the items bought on each grocery store visit."
},
{
"code": null,
"e": 1758,
"s": 1656,
"text": "So, in the sqlite shell, you create those tables in your local database using the following commands:"
},
{
"code": null,
"e": 1913,
"s": 1758,
"text": "create table grocery_visit(date TEXT, time_spent_min INTEGER, amount_spent REAL);create table grocery_list(date TEXT, item_name TEXT, item_category TEXT);"
},
{
"code": null,
"e": 2013,
"s": 1913,
"text": "And just to make sure the tables were actually created, you double-check using the command .tables."
},
{
"code": null,
"e": 2068,
"s": 2013,
"text": "And then you go through each item of the grocery list."
},
{
"code": null,
"e": 3705,
"s": 2068,
"text": "insert into grocery_list values(\"2020-12-03\", \"Hamburger patties\", \"Meat and Fish\");insert into grocery_list values(\"2020-12-03\", \"Chips\", \"Pantry\");insert into grocery_list values(\"2020-12-03\", \"Avocado\", \"Fruits and Vegetables\");insert into grocery_list values(\"2020-12-03\", \"Lime\", \"Fruits and Vegetables\");insert into grocery_list values(\"2020-12-03\", \"Tomato\", \"Fruits and Vegetables\");insert into grocery_list values(\"2020-12-15\", \"Rice cakes\", \"Pantry\");insert into grocery_list values(\"2020-12-15\", \"Graham crackers\", \"Pantry\");insert into grocery_list values(\"2020-12-15\", \"Toothpaste\", NULL);insert into grocery_list values(\"2020-12-15\", \"Flour\", \"Pantry\");insert into grocery_list values(\"2020-12-15\", \"Yeast\", \"Pantry\");insert into grocery_list values(\"2020-12-15\", \"Popcorn\", \"Pantry\");insert into grocery_list values(\"2020-12-15\", \"Eggs\", NULL);insert into grocery_list values(\"2020-12-15\", \"Milk\", \"Dairy\");insert into grocery_list values(\"2020-12-15\", \"Bananas\", \"Fruits and Vegetables\");insert into grocery_list values(\"2020-12-15\", \"Frozen waffles\", NULL);insert into grocery_list values(\"2020-12-23\", \"Mayo\", \"Pantry\");insert into grocery_list values(\"2020-12-23\", \"Flour\", \"Pantry\");insert into grocery_list values(\"2020-12-23\", \"Milk\", \"Dairy\");insert into grocery_list values(\"2020-12-23\", \"Roasted Chicken\", \"Meat and Fish\");insert into grocery_list values(\"2020-12-23\", \"Chocolate chip cookies\", \"Pantry\");insert into grocery_list values(\"2020-12-23\", \"Yogurt\", \"Dairy\");insert into grocery_list values(\"2020-12-23\", \"Soda\", NULL);insert into grocery_list values(\"2020-12-23\", \"Grapes\", \"Fruits and Vegetables\");"
},
{
"code": null,
"e": 3792,
"s": 3705,
"text": "Now that all your grocery shopping data in the stored, you can start asking questions!"
},
{
"code": null,
"e": 3902,
"s": 3792,
"text": "Before you start writing SQL to answer questions with data, let’s look at the building blocks of a SQL query."
},
{
"code": null,
"e": 4004,
"s": 3902,
"text": "You can think of a query as the result of filtering, transforming and combining one or more datasets."
},
{
"code": null,
"e": 4092,
"s": 4004,
"text": "In a broad sense, a SQL query is made of two parts, one mandatory and another optional:"
},
{
"code": null,
"e": 4162,
"s": 4092,
"text": "Mandatory part defines the output and what data you are pulling from,"
},
{
"code": null,
"e": 4281,
"s": 4162,
"text": "Optional part allows you to manipulate the data by filtering, aggregating, sorting or limiting the size of the output."
},
{
"code": null,
"e": 4497,
"s": 4281,
"text": "Each portion of the query, here numbered 1 through 6, is called a clause, which you can refer to using different reserved keywords. Each clause allows you to perform specific actions on the dataset you have at hand:"
},
{
"code": null,
"e": 5049,
"s": 4497,
"text": "Select Everything after the select keyword represents the output of your query. It’s the end result.From The data you’re manipulating. It can be a table or the result of another query, usually called sub-query or inner query.Where Used to filter the data and to specify the set of conditions the data needs to comply to, in order for you to produce an output.Group by Indicates you’re aggregating the data, e.g., counting or summing values.Order by How you want to sort the results.Limit Indicates you only want to display a certain number of results."
},
{
"code": null,
"e": 5150,
"s": 5049,
"text": "Select Everything after the select keyword represents the output of your query. It’s the end result."
},
{
"code": null,
"e": 5276,
"s": 5150,
"text": "From The data you’re manipulating. It can be a table or the result of another query, usually called sub-query or inner query."
},
{
"code": null,
"e": 5411,
"s": 5276,
"text": "Where Used to filter the data and to specify the set of conditions the data needs to comply to, in order for you to produce an output."
},
{
"code": null,
"e": 5493,
"s": 5411,
"text": "Group by Indicates you’re aggregating the data, e.g., counting or summing values."
},
{
"code": null,
"e": 5536,
"s": 5493,
"text": "Order by How you want to sort the results."
},
{
"code": null,
"e": 5606,
"s": 5536,
"text": "Limit Indicates you only want to display a certain number of results."
},
{
"code": null,
"e": 5662,
"s": 5606,
"text": "Let’s write some queries and see all of this in action!"
},
{
"code": null,
"e": 5855,
"s": 5662,
"text": "The first step in a data project is data exploration, getting to know your data. Once you know your data, it will be much easier to use the right methods or functions to answer your questions."
},
{
"code": null,
"e": 5916,
"s": 5855,
"text": "When you’re exploring this dataset, you may start by asking:"
},
{
"code": null,
"e": 5940,
"s": 5916,
"text": "Can I see all the data?"
},
{
"code": null,
"e": 5971,
"s": 5940,
"text": "Can I take a peek at the data?"
},
{
"code": null,
"e": 6026,
"s": 5971,
"text": "Can I see all the possible values of a certain column?"
},
{
"code": null,
"e": 6105,
"s": 6026,
"text": "In this case, you have very little data, so it’s possible to see all the data."
},
{
"code": null,
"e": 6190,
"s": 6105,
"text": "You can use select * to see all the data in a table, i.e., all the rows and columns."
},
{
"code": null,
"e": 6219,
"s": 6190,
"text": "select * from grocery_visit;"
},
{
"code": null,
"e": 6350,
"s": 6219,
"text": "The wildcard * means you want to see all the columns in the resulting dataset. But, you might only be interested in a few columns:"
},
{
"code": null,
"e": 6396,
"s": 6350,
"text": "select date, amount_spent from grocery_visit;"
},
{
"code": null,
"e": 6562,
"s": 6396,
"text": "Notice that, at the end of each query statement there’s always a semicolon ;. This indicates the end of the query, and that sqlite can proceed to evaluate the query."
},
{
"code": null,
"e": 6777,
"s": 6562,
"text": "Even though you see all the data for date and amount_spent columns, it’s difficult to map the values to the respective column. This would be specially handy if you were working with a dataset built by someone else."
},
{
"code": null,
"e": 6874,
"s": 6777,
"text": "In sqlite you can adjust the settings to output column names, also referred to as table headers."
},
{
"code": null,
"e": 6886,
"s": 6874,
"text": ".headers on"
},
{
"code": null,
"e": 6947,
"s": 6886,
"text": "So, if you run the query again you’ll see the columns names."
},
{
"code": null,
"e": 7105,
"s": 6947,
"text": "Seems like a small detail, but now it’s a bit easier to make sense of the results. From now on, all queries will output the headers of the resulting dataset."
},
{
"code": null,
"e": 7138,
"s": 7105,
"text": "Alright, back to your questions!"
},
{
"code": null,
"e": 7294,
"s": 7138,
"text": "If you just want to take a peek at the data you can use, for instance, the limit operand to say limit the result of this query to only X number of records."
},
{
"code": null,
"e": 7331,
"s": 7294,
"text": "select * from grocery_list limit 10;"
},
{
"code": null,
"e": 7394,
"s": 7331,
"text": "This returns the first 10 records from the grocery_list table."
},
{
"code": null,
"e": 7527,
"s": 7394,
"text": "You just took a quick look at the data but, before you start the analysis, it’s also important to check for any data quality issues."
},
{
"code": null,
"e": 7690,
"s": 7527,
"text": "For instance, you may have noticed that some items in the grocery_list don’t have a category. So you can ask Which items in my grocery list don’t have a category?"
},
{
"code": null,
"e": 7805,
"s": 7690,
"text": "To check that, you can use the where clause and filter the output to only include items that have a null category."
},
{
"code": null,
"e": 7860,
"s": 7805,
"text": "select * from grocery_listwhere item_category is null;"
},
{
"code": null,
"e": 8184,
"s": 7860,
"text": "You could also spot-check for invalid values, such as item names with typos or other values that don’t make sense in the column they are associated with. To do that you use the distinct reserved keyword, so it will output the a list of unique values instead of all values from a column, since there may be some duplication."
},
{
"code": null,
"e": 8275,
"s": 8184,
"text": "select distinct item_namefrom grocery_list;select distinct item_categoryfrom grocery_list;"
},
{
"code": null,
"e": 8328,
"s": 8275,
"text": "Even the null category, with no name, shows up here."
},
{
"code": null,
"e": 8470,
"s": 8328,
"text": "In SQL you filter the dataset by defining a set of rules in the where clause. You just used to look for the item categories with Null values."
},
{
"code": null,
"e": 8546,
"s": 8470,
"text": "That was only one simple rule, but you can ask other interesting questions."
},
{
"code": null,
"e": 8670,
"s": 8546,
"text": "In this case you know the exact name of the item category, Fruits and Vegetables, but pretend for a second that you don’t 😀"
},
{
"code": null,
"e": 8956,
"s": 8670,
"text": "You have a hunch that the category name must involve some variation of fruit, Fruit or even its plural. So, you can try to do a pattern match on the item category using the operator like. With this operator, you’re literally saying the filter for any item category like this [pattern]."
},
{
"code": null,
"e": 9015,
"s": 8956,
"text": "select *from grocery_listwhere item_category like 'Fruit';"
},
{
"code": null,
"e": 9157,
"s": 9015,
"text": "But you can’t just use it like this because, in practice, what you did was an exact match, the equivalent of using an equals instead of like."
},
{
"code": null,
"e": 9380,
"s": 9157,
"text": "To do a pattern match you need to use the wildcard %. This says filter for any item category that has Fruit in its name. Since the wildcard is at the end of the string, as long as it starts with Fruit, you’ll have a match."
},
{
"code": null,
"e": 9440,
"s": 9380,
"text": "select *from grocery_listwhere item_category like 'Fruit%';"
},
{
"code": null,
"e": 9562,
"s": 9440,
"text": "In sqlite operator like is case-insensitive, so having condition like ‘Fruit%’ or like ‘fruit%’ produces the same output."
},
{
"code": null,
"e": 9691,
"s": 9562,
"text": "With this question, you want to filter the dataset based on multiple conditions. So you can use the where clause with two rules:"
},
{
"code": null,
"e": 9756,
"s": 9691,
"text": "one that gives you all the days in which you’ve bought avocados,"
},
{
"code": null,
"e": 9817,
"s": 9756,
"text": "one that gives you all the days in which you’ve bought milk."
},
{
"code": null,
"e": 9892,
"s": 9817,
"text": "select *from grocery_listwhere item_name = 'Avocado'or item_name = 'Milk';"
},
{
"code": null,
"e": 10060,
"s": 9892,
"text": "You can re-write this where clause with the in operator, which will filter the dataset based on a list of items. In this case, the list contains only Avocado and Milk."
},
{
"code": null,
"e": 10125,
"s": 10060,
"text": "select *from grocery_listwhere item_name in ('Avocado', 'Milk');"
},
{
"code": null,
"e": 10184,
"s": 10125,
"text": "Either way you want to filter, you’ll get the same output."
},
{
"code": null,
"e": 10285,
"s": 10184,
"text": "You can also filter the dataset to only output the data that is is within a certain range of values."
},
{
"code": null,
"e": 10379,
"s": 10285,
"text": "For instance, you may want to see all the grocery store visits in the first half of December."
},
{
"code": null,
"e": 10457,
"s": 10379,
"text": "select *from grocery_visitwhere date >= '2020-12-01'and date <= '2020-12-15';"
},
{
"code": null,
"e": 10610,
"s": 10457,
"text": "Here you’re filtering the dataset using two conditions in the where clause but, if you want to make it easier to read, you can use the between operator."
},
{
"code": null,
"e": 10686,
"s": 10610,
"text": "select *from grocery_visitwhere date between '2020-12-01' and '2020-12-15';"
},
{
"code": null,
"e": 10789,
"s": 10686,
"text": "Another set of questions you might want to ask can be seen as looking for a way to summarize the data."
},
{
"code": null,
"e": 10861,
"s": 10789,
"text": "For instance a summary of your visits to the grocery store can include:"
},
{
"code": null,
"e": 10934,
"s": 10861,
"text": "Number of times you went to the grocery store, using the count function."
},
{
"code": null,
"e": 11034,
"s": 10934,
"text": "How long was you shortest and longest visits to the grocery store, using the min and max functions."
},
{
"code": null,
"e": 11113,
"s": 11034,
"text": "How much time have you spent shopping, on average, using the average function."
},
{
"code": null,
"e": 11279,
"s": 11113,
"text": "select count(*) as total_visits, min(time_spent_min) as shortest_visit, avg(time_spent_min) as average_visit, max(time_spent_min) as longest_visitfrom grocery_visit;"
},
{
"code": null,
"e": 11454,
"s": 11279,
"text": "In your three visits to the grocery store, the shortest took 10 minutes, the longest took 50 minutes and, on average, your grocery store visits took approximately 29 minutes."
},
{
"code": null,
"e": 11538,
"s": 11454,
"text": "The wildcard *, means you’re counting all the records from the grocery_visit table."
},
{
"code": null,
"e": 11608,
"s": 11538,
"text": "When you’re exploring a dataset, it’s also useful to sort the output."
},
{
"code": null,
"e": 11907,
"s": 11608,
"text": "Going back to the structure of a SQL query, you can use the optional order by clause to specify how you want to sort the results. Then, using the ordering terms asc and desc, the output is sorted in ascending or descending order. By default, the order by clause sorts the output in ascending order."
},
{
"code": null,
"e": 12017,
"s": 11907,
"text": "Here you can use the default, and output the amount_spent in each grocery store visit from lowest to highest."
},
{
"code": null,
"e": 12066,
"s": 12017,
"text": "select *from grocery_visitorder by amount_spent;"
},
{
"code": null,
"e": 12162,
"s": 12066,
"text": "Here it’s the exact same query, but specifying that the results are sorted in descending order."
},
{
"code": null,
"e": 12211,
"s": 12162,
"text": "select datefrom grocery_visitorder by date desc;"
},
{
"code": null,
"e": 12357,
"s": 12211,
"text": "But, instead, you may only want to see the last time you went to the grocery store. Here you can use the clauses and operands you’ve seen so far."
},
{
"code": null,
"e": 12410,
"s": 12357,
"text": "select *from grocery_visitorder by date desclimit 1;"
},
{
"code": null,
"e": 12549,
"s": 12410,
"text": "So far, you’ve been manipulating a single table. However, the most of the time, you’ll need to combine multiple tables to obtain insights."
},
{
"code": null,
"e": 12713,
"s": 12549,
"text": "In SQL, you combine multiple tables using the join operator. There are different types of joins and, each one combines the two tables according to different rules."
},
{
"code": null,
"e": 12838,
"s": 12713,
"text": "Since you also go to the department store often, you decided to store data about those visits in the table dept_store_visit."
},
{
"code": null,
"e": 13109,
"s": 12838,
"text": "create table dept_store_visit(date TEXT, time_spent_min INTEGER, amount_spent REAL);insert into dept_store_visit values ('2020-12-01', 40, 45.99);insert into dept_store_visit values ('2020-12-15', 25, 37.30);insert into dept_store_visit values ('2020-12-19', 20, 15.82);"
},
{
"code": null,
"e": 13189,
"s": 13109,
"text": "With data from visits to both stores, you can ask a very interesting questions."
},
{
"code": null,
"e": 13357,
"s": 13189,
"text": "Joins are usually depicted as Venn diagrams (left), but you can also think about joining two datasets (right) that may or may not share characteristics, i.e., columns."
},
{
"code": null,
"e": 13538,
"s": 13357,
"text": "One way answer this question is to combine each record in one table with every record in the other table, to make sure the resulting dataset captures all the data from both tables."
},
{
"code": null,
"e": 13640,
"s": 13538,
"text": "To do this, you can use a cross join, then filter by the grocery visits when you spent more than $15."
},
{
"code": null,
"e": 13681,
"s": 13640,
"text": "In SQL, you’d write the following query:"
},
{
"code": null,
"e": 13811,
"s": 13681,
"text": "select *from grocery_visitcross join dept_store_visitwhere grocery_visit.amount_spent > 15and dept_store_visit.amount_spent > 15;"
},
{
"code": null,
"e": 13937,
"s": 13811,
"text": "By default in most database engines, and sqlite is no exception, you can omit the cross and you’ll be obtain the same output."
},
{
"code": null,
"e": 14192,
"s": 13937,
"text": "Because the records are mapped many-to-many, and the grocery_visit table only has one record greater than $15, it ends up paired with the 3 records in the dept_store_visit. Hence you see the record from grocery_visit table repeated 3 times in the output."
},
{
"code": null,
"e": 14300,
"s": 14192,
"text": "This definitely answers your question but, the structure of the output many not be exactly what you wanted."
},
{
"code": null,
"e": 14509,
"s": 14300,
"text": "It would be much easier to interpret if the output was a list of the days when you went to the grocery store and to the department store. As if you were appending the result of filtering each of those tables."
},
{
"code": null,
"e": 14552,
"s": 14509,
"text": "To do this you can use the union operator."
},
{
"code": null,
"e": 14780,
"s": 14552,
"text": "And because you are appending the records from each table, it’s mandatory that both tables have either the exact same structure or that you select the columns such that their structure matches by the time you perform the union."
},
{
"code": null,
"e": 14922,
"s": 14780,
"text": "select date, amount_spentfrom grocery_visitwhere amount_spent > 15unionselect date, amount_spentfrom dept_store_visitwhere amount_spent > 15;"
},
{
"code": null,
"e": 15027,
"s": 14922,
"text": "Here again, the data necessary to answer this question lives in multiple tables, so you need to combine:"
},
{
"code": null,
"e": 15070,
"s": 15027,
"text": "grocery_visit to get the amount_spent, and"
},
{
"code": null,
"e": 15143,
"s": 15070,
"text": "grocery_list to filter by bread-making items like flour, yeast and eggs."
},
{
"code": null,
"e": 15193,
"s": 15143,
"text": "You just learned about cross joins. Let’s use it!"
},
{
"code": null,
"e": 15302,
"s": 15193,
"text": "select *from grocery_visitcross join grocery_listwhere grocery_list.item_name in ('Flour', 'Yeast', 'Eggs');"
},
{
"code": null,
"e": 15412,
"s": 15302,
"text": "If you inspect the resulting dataset, before doing the aggregation you see that something is not quite right."
},
{
"code": null,
"e": 15615,
"s": 15412,
"text": "The output dataset indeed has all the items you were looking for but, because you are using a cross join, all the records in the grocery_visit table are paired with the records you want in grocery_list."
},
{
"code": null,
"e": 15751,
"s": 15615,
"text": "If you did the average right now, you’d be looking at the wrong results, because the resulting dataset is not actually what you wanted."
},
{
"code": null,
"e": 15859,
"s": 15751,
"text": "What you really wanted is to only get data for the grocery visits when you’ve bought flour, yeast and eggs."
},
{
"code": null,
"e": 15929,
"s": 15859,
"text": "Thankfully there’s another join operator you can use, the inner join."
},
{
"code": null,
"e": 16220,
"s": 15929,
"text": "With an inner join you’re combining two datasets that have a similar characteristics and returning what’s common between them. For the inner join to work, both tables must have at least one column in common, because you need to specify which characteristic needs to be equal in both tables."
},
{
"code": null,
"e": 16243,
"s": 16220,
"text": "It follows the format:"
},
{
"code": null,
"e": 16315,
"s": 16243,
"text": "tableA inner join tableB on tableA.shared_column = tableB.shared_column"
},
{
"code": null,
"e": 16453,
"s": 16315,
"text": "Even if both tables have one or more columns in common, they must have the exact same value. Otherwise, your output dataset will be null."
},
{
"code": null,
"e": 16540,
"s": 16453,
"text": "Using the Venn diagram analogy, you’re looking for intersection between the two areas."
},
{
"code": null,
"e": 16633,
"s": 16540,
"text": "To answer this question you want to match both tables on the day of the grocery store visit."
},
{
"code": null,
"e": 16783,
"s": 16633,
"text": "select *from grocery_visitinner join grocery_liston grocery_visit.date = grocery_list.datewhere grocery_list.item_name in ('Flour', 'Yeast', 'Eggs');"
},
{
"code": null,
"e": 16844,
"s": 16783,
"text": "So, taking a peek at the result of the inner join, you have:"
},
{
"code": null,
"e": 17073,
"s": 16844,
"text": "You can also notice that you’ve bought multiple of those items on 2020–12–15, so the data for that grocery visit is repeated. However, you only want to calculate the average amount_spent in two visits, 2020–12–15 and 2020–12–23."
},
{
"code": null,
"e": 17243,
"s": 17073,
"text": "So, when you’re calculating the average amount_spent, you need to make sure you don’t count values multiple times. You can use the distinct keyword to take care of that."
},
{
"code": null,
"e": 17438,
"s": 17243,
"text": "select avg(distinct amount_spent) as avg_amount_spentfrom grocery_visitinner join grocery_liston grocery_visit.date = grocery_list.datewhere grocery_list.item_name in ('Flour', 'Yeast', 'Eggs');"
},
{
"code": null,
"e": 17524,
"s": 17438,
"text": "But you might say, What about if different grocery visits have the same amount spent?"
},
{
"code": null,
"e": 17704,
"s": 17524,
"text": "Going back to the anatomy of a SQL query, the from clause can pull data directly from a table like you’ve been doing so far, or from the result of another query, called sub-query."
},
{
"code": null,
"e": 17826,
"s": 17704,
"text": "To make sure you get all the different grocery visits where you bought flour, yeast and eggs, but also take into account:"
},
{
"code": null,
"e": 17901,
"s": 17826,
"text": "Visits that happened in the same day, but have different amount spent and,"
},
{
"code": null,
"e": 17967,
"s": 17901,
"text": "Visits from different days that have the exact same amount spent."
},
{
"code": null,
"e": 18137,
"s": 17967,
"text": "You can encapsulate that logic in a sub-query and only then do the average. That way you guarantee you’re not over-counting nor under-counting any of the grocery visits."
},
{
"code": null,
"e": 18397,
"s": 18137,
"text": "select avg(amount_spent) as avg_amount_spentfrom( select distinct grocery_visit.date, amount_spent from grocery_visit inner join grocery_list on grocery_visit.date = grocery_list.date where grocery_list.item_name in ('Flour', 'Yeast', 'Eggs');)"
},
{
"code": null,
"e": 18601,
"s": 18397,
"text": "Since you’ve already filtered by the items of interest and you’re concerned about not over or under counting the spending in each visit, you can ignore all the columns from grocery_list in the sub-query."
},
{
"code": null,
"e": 18720,
"s": 18601,
"text": "In this question it’s clear that you’ll want to combine data that is in the grocery_visit and dept_store_visit tables."
},
{
"code": null,
"e": 18767,
"s": 18720,
"text": "But the main focus is on grocery store visits."
},
{
"code": null,
"e": 18829,
"s": 18767,
"text": "You’re going to be using a left join to answer this question."
},
{
"code": null,
"e": 18999,
"s": 18829,
"text": "Using the Venn diagram analogy, you’ll want all the data in the grocery_visit and only the records from dept_store_visit that match the days of the grocery store visits."
},
{
"code": null,
"e": 19118,
"s": 18999,
"text": "You can think of a left join as keep everything on the left (table) and bring only the matches from the right (table)."
},
{
"code": null,
"e": 19347,
"s": 19118,
"text": "select grocery_visit.*, dept_store_visit.time_spent_min as time_spent_dept_store, dept_store_visit.amount_spent as amount_spent_dept_storefrom grocery_visitleft join dept_store_visiton grocery_visit.date = dept_store_visit.date;"
},
{
"code": null,
"e": 19425,
"s": 19347,
"text": "Here grocery_visit.* means the output has all the columns from grocery_visit."
},
{
"code": null,
"e": 19615,
"s": 19425,
"text": "You can also think about this question the other way around On the days I went to the department store, did I also go to the grocery store? If so, how much time did I spend in these visits?"
},
{
"code": null,
"e": 19770,
"s": 19615,
"text": "Most database engines support right join, which is exactly what is sounds like, the opposite of a left join. However, sqlite does not support right joins."
},
{
"code": null,
"e": 19955,
"s": 19770,
"text": "With a right join you keep everything on the right (table) and bring only the matches on the left (table). Which, in practice, means flipping the other of the tables in the last query."
},
{
"code": null,
"e": 20118,
"s": 19955,
"text": "You might also have noticed that, in the last query, the output of dept_store_visit was different than the original column names. That’s because we used an alias."
},
{
"code": null,
"e": 20347,
"s": 20118,
"text": "Aliases make it easier to reference tables and sub-queries with more interpretable names. In this case, we used aliases to rename the output columns to something that was distinguishable from the column in the other table table."
},
{
"code": null,
"e": 20559,
"s": 20347,
"text": "You’ve just went through an extensive look at the basics of SQL querying! But don’t worry, it doesn’t have to end here, there are many more nuanced questions you can ask with advanced SQL functions and operands."
},
{
"code": null,
"e": 20642,
"s": 20559,
"text": "Hope this article got you curious about SQL and how to answer questions with data."
}
] |
Building Neural Network Using PyTorch | by Tasnuva Zaman | Towards Data Science
|
“The question of whether a computer can think is no more interesting than the question of whether a submarine can swim.” ― Edsger W. Dijkstra
In this tutorial we will implement a simple neural network from scratch using PyTorch. I am sharing what I have learnt from my recent facebook-udacity scholarship challenge program. This tutorial assumes you have prior knowledge of how a neural network works.
Though there are many libraries out there that can be used for deep learning I like the PyTorch most. As a python programmer, one of the reasons behind my liking is pythonic behavior of PyTorch. It mostly uses the style and power of python which is easy to understand and use.
At its core, PyTorch provides two main features:
An n-dimensional Tensor, similar to numpy but can run on GPUs
Automatic differentiation for building and training neural networks
What is Neural Network?
Neural networks are a set of algorithms, modeled loosely after the human brain, that are designed to recognize patterns. The networks are built from individual parts approximating neurons, typically called units or simply “neurons.” Each unit has some number of weighted inputs. These weighted inputs are summed together (a linear combination) then passed through an activation function to get the unit’s output.
Input Units — Provides information from the outside world to the network and are together referred to as the “Input Layer”. These nodes do not perform any computation, they just pass on the information to the hidden nodes.Hidden Units — These nodes do not have any direct connection with the outside world. They perform computations and transfer information from Input nodes to Output nodes. A collection of hidden nodes forms a “Hidden Layer”. While a feed-forward network will only have a single input layer and a single output layer, it can have zero or multiple Hidden Layers.Output Units — The Output nodes are collectively referred to as the “Output Layer” and are responsible for computations and transferring information from the network to the outside world.
Input Units — Provides information from the outside world to the network and are together referred to as the “Input Layer”. These nodes do not perform any computation, they just pass on the information to the hidden nodes.
Hidden Units — These nodes do not have any direct connection with the outside world. They perform computations and transfer information from Input nodes to Output nodes. A collection of hidden nodes forms a “Hidden Layer”. While a feed-forward network will only have a single input layer and a single output layer, it can have zero or multiple Hidden Layers.
Output Units — The Output nodes are collectively referred to as the “Output Layer” and are responsible for computations and transferring information from the network to the outside world.
Each layer comprises one or more nodes.
Building Neural Network
PyTorch provides a module nn that makes building networks much simpler. We’ll see how to build a neural network with 784 inputs, 256 hidden units, 10 output units and a softmax output.
from torch import nnclass Network(nn.Module): def __init__(self): super().__init__() # Inputs to hidden layer linear transformation self.hidden = nn.Linear(784, 256) # Output layer, 10 units - one for each digit self.output = nn.Linear(256, 10) # Define sigmoid activation and softmax output self.sigmoid = nn.Sigmoid() self.softmax = nn.Softmax(dim=1) def forward(self, x): # Pass the input tensor through each of our operations x = self.hidden(x) x = self.sigmoid(x) x = self.output(x) x = self.softmax(x) return x
Note: The softmax function, also known as softargmax or normalized exponential functionis a function that takes as input a vector of K real numbers, and normalizes it into a probability distribution consisting of K probabilities.
Let’s go through this line by line.
class Network(nn.Module):
Here we’re inheriting from nn.Module. Combined with super().__init__() this creates a class that tracks the architecture and provides a lot of useful methods and attributes. It is mandatory to inherit from nn.Module when you're creating a class for your network. The name of the class itself can be anything.
self.hidden = nn.Linear(784, 256)
This line creates a module for a linear transformation, xW+bxW+b, with 784 inputs and 256 outputs and assigns it to self.hidden. The module automatically creates the weight and bias tensors which we'll use in the forward method. You can access the weight and bias tensors once the network (net) is created with net.hidden.weight and net.hidden.bias.
self.output = nn.Linear(256, 10)
Similarly, this creates another linear transformation with 256 inputs and 10 outputs.
self.sigmoid = nn.Sigmoid()self.softmax = nn.Softmax(dim=1)
Here I defined operations for the sigmoid activation and softmax output. Setting dim=1 in nn.Softmax(dim=1) calculates softmax across the columns.
def forward(self, x):
PyTorch networks created with nn.Module must have a forward method defined. It takes in a tensor x and passes it through the operations you defined in the __init__ method.
x = self.hidden(x)x = self.sigmoid(x)x = self.output(x)x = self.softmax(x)
Here the input tensor x is passed through each operation and reassigned to x. We can see that the input tensor goes through the hidden layer, then a sigmoid function, then the output layer, and finally the softmax function. It doesn't matter what you name the variables here, as long as the inputs and outputs of the operations match the network architecture you want to build. The order in which you define things in the __init__ method doesn't matter, but you'll need to sequence the operations correctly in the forward method.
# Create the network and look at it's text representationmodel = Network()model
Building Neural Network using nn.Sequential
PyTorch provides a convenient way to build networks like this where a tensor is passed sequentially through operations, nn.Sequential(documentation). Using this to build the equivalent network:
# Hyperparameters for our networkinput_size = 784hidden_sizes = [128, 64]output_size = 10# Build a feed-forward networkmodel = nn.Sequential(nn.Linear(input_size, hidden_sizes[0]), nn.ReLU(), nn.Linear(hidden_sizes[0], hidden_sizes[1]), nn.ReLU(), nn.Linear(hidden_sizes[1], output_size), nn.Softmax(dim=1))print(model)
Here our model is the same as before: 784 input units, a hidden layer with 128 units, ReLU activation, 64 unit hidden layer, another ReLU, then the output layer with 10 units, and the softmax output.
You can also pass in an OrderedDict to name the individual layers and operations, instead of using incremental integers. Note that dictionary keys must be unique, so each operation must have a different name.
from collections import OrderedDictmodel = nn.Sequential(OrderedDict([ ('fc1', nn.Linear(input_size, hidden_sizes[0])), ('relu1', nn.ReLU()), ('fc2', nn.Linear(hidden_sizes[0], hidden_sizes[1])), ('relu2', nn.ReLU()), ('output', nn.Linear(hidden_sizes[1], output_size)), ('softmax', nn.Softmax(dim=1))]))model
Now you can access layers either by integer or the name
print(model[0])print(model.fc1)
That’s all for today. Next we will be training a neural network. You will find it here.
You are always welcome with any constructive criticism or feedback.
|
[
{
"code": null,
"e": 314,
"s": 172,
"text": "“The question of whether a computer can think is no more interesting than the question of whether a submarine can swim.” ― Edsger W. Dijkstra"
},
{
"code": null,
"e": 574,
"s": 314,
"text": "In this tutorial we will implement a simple neural network from scratch using PyTorch. I am sharing what I have learnt from my recent facebook-udacity scholarship challenge program. This tutorial assumes you have prior knowledge of how a neural network works."
},
{
"code": null,
"e": 851,
"s": 574,
"text": "Though there are many libraries out there that can be used for deep learning I like the PyTorch most. As a python programmer, one of the reasons behind my liking is pythonic behavior of PyTorch. It mostly uses the style and power of python which is easy to understand and use."
},
{
"code": null,
"e": 900,
"s": 851,
"text": "At its core, PyTorch provides two main features:"
},
{
"code": null,
"e": 962,
"s": 900,
"text": "An n-dimensional Tensor, similar to numpy but can run on GPUs"
},
{
"code": null,
"e": 1030,
"s": 962,
"text": "Automatic differentiation for building and training neural networks"
},
{
"code": null,
"e": 1054,
"s": 1030,
"text": "What is Neural Network?"
},
{
"code": null,
"e": 1467,
"s": 1054,
"text": "Neural networks are a set of algorithms, modeled loosely after the human brain, that are designed to recognize patterns. The networks are built from individual parts approximating neurons, typically called units or simply “neurons.” Each unit has some number of weighted inputs. These weighted inputs are summed together (a linear combination) then passed through an activation function to get the unit’s output."
},
{
"code": null,
"e": 2235,
"s": 1467,
"text": "Input Units — Provides information from the outside world to the network and are together referred to as the “Input Layer”. These nodes do not perform any computation, they just pass on the information to the hidden nodes.Hidden Units — These nodes do not have any direct connection with the outside world. They perform computations and transfer information from Input nodes to Output nodes. A collection of hidden nodes forms a “Hidden Layer”. While a feed-forward network will only have a single input layer and a single output layer, it can have zero or multiple Hidden Layers.Output Units — The Output nodes are collectively referred to as the “Output Layer” and are responsible for computations and transferring information from the network to the outside world."
},
{
"code": null,
"e": 2458,
"s": 2235,
"text": "Input Units — Provides information from the outside world to the network and are together referred to as the “Input Layer”. These nodes do not perform any computation, they just pass on the information to the hidden nodes."
},
{
"code": null,
"e": 2817,
"s": 2458,
"text": "Hidden Units — These nodes do not have any direct connection with the outside world. They perform computations and transfer information from Input nodes to Output nodes. A collection of hidden nodes forms a “Hidden Layer”. While a feed-forward network will only have a single input layer and a single output layer, it can have zero or multiple Hidden Layers."
},
{
"code": null,
"e": 3005,
"s": 2817,
"text": "Output Units — The Output nodes are collectively referred to as the “Output Layer” and are responsible for computations and transferring information from the network to the outside world."
},
{
"code": null,
"e": 3045,
"s": 3005,
"text": "Each layer comprises one or more nodes."
},
{
"code": null,
"e": 3069,
"s": 3045,
"text": "Building Neural Network"
},
{
"code": null,
"e": 3254,
"s": 3069,
"text": "PyTorch provides a module nn that makes building networks much simpler. We’ll see how to build a neural network with 784 inputs, 256 hidden units, 10 output units and a softmax output."
},
{
"code": null,
"e": 3908,
"s": 3254,
"text": "from torch import nnclass Network(nn.Module): def __init__(self): super().__init__() # Inputs to hidden layer linear transformation self.hidden = nn.Linear(784, 256) # Output layer, 10 units - one for each digit self.output = nn.Linear(256, 10) # Define sigmoid activation and softmax output self.sigmoid = nn.Sigmoid() self.softmax = nn.Softmax(dim=1) def forward(self, x): # Pass the input tensor through each of our operations x = self.hidden(x) x = self.sigmoid(x) x = self.output(x) x = self.softmax(x) return x"
},
{
"code": null,
"e": 4138,
"s": 3908,
"text": "Note: The softmax function, also known as softargmax or normalized exponential functionis a function that takes as input a vector of K real numbers, and normalizes it into a probability distribution consisting of K probabilities."
},
{
"code": null,
"e": 4174,
"s": 4138,
"text": "Let’s go through this line by line."
},
{
"code": null,
"e": 4200,
"s": 4174,
"text": "class Network(nn.Module):"
},
{
"code": null,
"e": 4509,
"s": 4200,
"text": "Here we’re inheriting from nn.Module. Combined with super().__init__() this creates a class that tracks the architecture and provides a lot of useful methods and attributes. It is mandatory to inherit from nn.Module when you're creating a class for your network. The name of the class itself can be anything."
},
{
"code": null,
"e": 4543,
"s": 4509,
"text": "self.hidden = nn.Linear(784, 256)"
},
{
"code": null,
"e": 4893,
"s": 4543,
"text": "This line creates a module for a linear transformation, xW+bxW+b, with 784 inputs and 256 outputs and assigns it to self.hidden. The module automatically creates the weight and bias tensors which we'll use in the forward method. You can access the weight and bias tensors once the network (net) is created with net.hidden.weight and net.hidden.bias."
},
{
"code": null,
"e": 4926,
"s": 4893,
"text": "self.output = nn.Linear(256, 10)"
},
{
"code": null,
"e": 5012,
"s": 4926,
"text": "Similarly, this creates another linear transformation with 256 inputs and 10 outputs."
},
{
"code": null,
"e": 5072,
"s": 5012,
"text": "self.sigmoid = nn.Sigmoid()self.softmax = nn.Softmax(dim=1)"
},
{
"code": null,
"e": 5219,
"s": 5072,
"text": "Here I defined operations for the sigmoid activation and softmax output. Setting dim=1 in nn.Softmax(dim=1) calculates softmax across the columns."
},
{
"code": null,
"e": 5241,
"s": 5219,
"text": "def forward(self, x):"
},
{
"code": null,
"e": 5413,
"s": 5241,
"text": "PyTorch networks created with nn.Module must have a forward method defined. It takes in a tensor x and passes it through the operations you defined in the __init__ method."
},
{
"code": null,
"e": 5488,
"s": 5413,
"text": "x = self.hidden(x)x = self.sigmoid(x)x = self.output(x)x = self.softmax(x)"
},
{
"code": null,
"e": 6018,
"s": 5488,
"text": "Here the input tensor x is passed through each operation and reassigned to x. We can see that the input tensor goes through the hidden layer, then a sigmoid function, then the output layer, and finally the softmax function. It doesn't matter what you name the variables here, as long as the inputs and outputs of the operations match the network architecture you want to build. The order in which you define things in the __init__ method doesn't matter, but you'll need to sequence the operations correctly in the forward method."
},
{
"code": null,
"e": 6098,
"s": 6018,
"text": "# Create the network and look at it's text representationmodel = Network()model"
},
{
"code": null,
"e": 6142,
"s": 6098,
"text": "Building Neural Network using nn.Sequential"
},
{
"code": null,
"e": 6336,
"s": 6142,
"text": "PyTorch provides a convenient way to build networks like this where a tensor is passed sequentially through operations, nn.Sequential(documentation). Using this to build the equivalent network:"
},
{
"code": null,
"e": 6761,
"s": 6336,
"text": "# Hyperparameters for our networkinput_size = 784hidden_sizes = [128, 64]output_size = 10# Build a feed-forward networkmodel = nn.Sequential(nn.Linear(input_size, hidden_sizes[0]), nn.ReLU(), nn.Linear(hidden_sizes[0], hidden_sizes[1]), nn.ReLU(), nn.Linear(hidden_sizes[1], output_size), nn.Softmax(dim=1))print(model)"
},
{
"code": null,
"e": 6961,
"s": 6761,
"text": "Here our model is the same as before: 784 input units, a hidden layer with 128 units, ReLU activation, 64 unit hidden layer, another ReLU, then the output layer with 10 units, and the softmax output."
},
{
"code": null,
"e": 7170,
"s": 6961,
"text": "You can also pass in an OrderedDict to name the individual layers and operations, instead of using incremental integers. Note that dictionary keys must be unique, so each operation must have a different name."
},
{
"code": null,
"e": 7606,
"s": 7170,
"text": "from collections import OrderedDictmodel = nn.Sequential(OrderedDict([ ('fc1', nn.Linear(input_size, hidden_sizes[0])), ('relu1', nn.ReLU()), ('fc2', nn.Linear(hidden_sizes[0], hidden_sizes[1])), ('relu2', nn.ReLU()), ('output', nn.Linear(hidden_sizes[1], output_size)), ('softmax', nn.Softmax(dim=1))]))model"
},
{
"code": null,
"e": 7662,
"s": 7606,
"text": "Now you can access layers either by integer or the name"
},
{
"code": null,
"e": 7694,
"s": 7662,
"text": "print(model[0])print(model.fc1)"
},
{
"code": null,
"e": 7782,
"s": 7694,
"text": "That’s all for today. Next we will be training a neural network. You will find it here."
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.